Exemplo n.º 1
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            var connectionString = ConfigurationManager.ConnectionStrings["conString"].ToString();
            Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));

            var appSettings = new AppSettings();
            Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[]
                {
                    new CredentialsAuthProvider(),
                    new FacebookAuthProvider(appSettings),
                    new GoogleOpenIdOAuthProvider(appSettings),
                }));

            Plugins.Add(new RegistrationFeature());

            var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>());
            container.Register<IUserAuthRepository>(userRep);
            var redisCon = ConfigurationManager.AppSettings["redisUrl"].ToString();
            container.Register<IRedisClientsManager>(new PooledRedisClientManager(20, 60, redisCon));
            container.Register<ICacheClient>(c => (ICacheClient)c.Resolve<IRedisClientsManager>().GetCacheClient());

            userRep.CreateMissingTables();
            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Exemplo n.º 2
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            container.Register<ICacheClient>(new MemoryCacheClient());
            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["Db"].ToString(), SqlServerDialect.Provider));

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(MeetingValidator).Assembly);

            //https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#userauth-persistence---the-iuserauthrepository
            //Use ServiceStacks authentication/authorization persistence

            var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>());
            container.Register<IUserAuthRepository>(userRep);
            userRep.CreateMissingTables(); //Create missing Auth

            var appSettings = new AppSettings();
            Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[]
                {
                    new CredentialsAuthProvider(),
                    new GoogleOpenIdOAuthProvider(appSettings),
                }));

            Plugins.Add(new RegistrationFeature());

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
        public void SetUp()
        {
			try
			{
                tests = new OAuthUserSessionTests();
				var inMemoryRepo = new InMemoryAuthRepository();
				inMemoryRepo.Clear();
				userAuthRepositorys.Add(inMemoryRepo);

                var appSettings = new AppSettings();
				var redisRepo = new RedisAuthRepository(new BasicRedisClientManager(new string[] { appSettings.GetString("Redis.Host") ?? "localhost" }));
				redisRepo.Clear();
				userAuthRepositorys.Add(redisRepo);

				if (OAuthUserSessionTestsBase.UseSqlServer)
				{
					var connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\auth.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
					var sqlServerFactory = new OrmLiteConnectionFactory(connStr, SqlServerOrmLiteDialectProvider.Instance);
					var sqlServerRepo = new OrmLiteAuthRepository(sqlServerFactory);
					sqlServerRepo.DropAndReCreateTables();
				}
				else
				{
					var sqliteInMemoryRepo = new OrmLiteAuthRepository(dbFactory);
					dbFactory.Run(db => {
						db.CreateTable<UserAuth>(true);
						db.CreateTable<UserOAuthProvider>(true);
					});
					sqliteInMemoryRepo.Clear();
					userAuthRepositorys.Add(sqliteInMemoryRepo);

					var sqliteDbFactory = new OrmLiteConnectionFactory(
						"~/App_Data/auth.sqlite".MapProjectPath());
					var sqliteDbRepo = new OrmLiteAuthRepository(sqliteDbFactory);
					sqliteDbRepo.CreateMissingTables();
					userAuthRepositorys.Add(sqliteDbRepo);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
				throw;
			}
		}
Exemplo n.º 4
0
		public override void Configure(Funq.Container container)
		{
			//Set JSON web services to return idiomatic JSON camelCase properties
			ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            //https://github.com/wordnik/swagger-core/wiki
            //Document your code and expose it to the world
            Plugins.Add(new SwaggerFeature());

            //Registers authorization service and endpoints /auth and /auth{provider}
            Plugins.Add(new AuthFeature(
                    () => new AuthUserSession(),
                    new IAuthProvider[] { new CredentialsAuthProvider() }
                ) {HtmlRedirect = null});

            //Registers registartion service and endpoints /register, /assignroles, /unassignroles
            Plugins.Add(new RegistrationFeature());
            this.RegisterAs<MyRegistrationValidator, IValidator<Registration>>();
            
            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(CreateOrderValidator).Assembly);

            var dataFilePath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "\\data.db";
		    container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(dataFilePath, SqliteDialect.Provider));

            var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>());
		    container.Register<IUserAuthRepository>(userRep);
            var redisCon = ConfigurationManager.AppSettings["redisUrl"].ToString();
		    container.Register<IRedisClientsManager>(new PooledRedisClientManager(20, 60, redisCon));
            container.Register<ICacheClient>(c =>(ICacheClient)c.Resolve<IRedisClientsManager>().GetCacheClient());

		    //Set MVC to use the same Funq IOC as ServiceStack
			ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));

            //https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisPubSub
            //start threads that subscribe to Redis channels for Pub/Sub
            new OrderSubscribers(container).StartSubscriberThreads();
            new FulfillmentSubscribers(container).StartSubscriberThreads();

            //https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#userauth-persistence---the-iuserauthrepository
            //Use ServiceStacks authentication/authorization persistence
            userRep.CreateMissingTables(); //Create missing Auth
            
            //Re-Create Tables for the demo
            using (var con = AppHostBase.Resolve<IDbConnectionFactory>().OpenDbConnection())
		    {
                con.CreateTable<Order>(true);
                con.CreateTable<Fulfillment>(true);
		    }

            //clear redis
		    using (var redis = AppHostBase.Resolve<IRedisClientsManager>().GetClient())
		    {
		    }
		    //Create dummy user accounts (TestUser/Password)
            foreach(var user in DummyUserAccounts.GetDummyAccounts())
            {
                if(userRep.GetUserAuthByUserName(user.UserName) == null)
                    userRep.CreateUserAuth(new UserAuth {UserName = user.UserName}, user.Password);
            }
		}
Exemplo n.º 5
0
        /// <summary>
        /// Configures the authentication.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="factory">The factory.</param>
        public void ConfigureAuth(Funq.Container container, OrmLiteConnectionFactory factory)
        {
            // Instantiate the authentication repository with the configured OrmLiteConnectionFactory.
            var authRepository = new OrmLiteAuthRepository(factory);

            // Create the missing tables if they are not yet configured.
            authRepository.CreateMissingTables();

            // Register the authentication repository.
            container.Register<IUserAuthRepository>(c => authRepository);

            // Register all Authentication methods needed.
            Plugins.Add(
                new AuthFeature(
                    () => new AuthUserSession(),
                    new IAuthProvider[] { new CredentialsAuthProvider(), new BasicAuthProvider() }));

            // HtmlRedirect = null --^

            // Provide service for new users to register so they can login with supplied credentials.
            Plugins.Add(new RegistrationFeature());
        }
		private void ConfigureAuth(Container container){
			
			container.Register<ICacheClient>(new MemoryCacheClient());
			
			Plugins.Add(new AuthFeature(
				 () => new AuthUserSession(), // or Use your own typed Custom AuthUserSession type
				new IAuthProvider[]
        	{
				new CredentialsAuthProvider()
        	}));
		    
			var appSettings = new ConfigurationResourceManager();
				
			var dbFactory = new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("UserAuth")) ;
			
			OrmLiteAuthRepository authRepo = new OrmLiteAuthRepository(
				dbFactory
			);
			
			container.Register<IUserAuthRepository>(
				c => authRepo
			); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info

			
			if (appSettings.Get("RecreateAuthTables", false))
				authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
			else{
				authRepo.CreateMissingTables();   //Create only the missing tables				
			}
						
			Plugins.Add( new  RegistrationFeature());
			
		    //Add admin user  
			string userName = "******";
			string password = "******";
		
			List<string> userPermissions= new List<string>(
			new string[]{	
			"Customer.create", "Company.create", "Country.create", "City.create", "Author.create", "Person.create",	
			"Customer.read",   "Company.read",   "Country.read",   "City.read",   "Author.read",   "Person.read",
			"Customer.update", "Company.update", "Country.update", "City.update", "Author.update", "Person.update"
			});
			
			List<string> adminPermissions= new List<string>(userPermissions);
			adminPermissions.AddRange(new string[]{	
			"Customer.destroy","Company.destroy","Country.destroy","City.destroy","Author.destroy","Person.destroy"
			});
			
			if ( authRepo.GetUserAuthByUserName(userName)== default(UserAuth) ){
				List<string> roles= new List<string>();
				roles.Add(RoleNames.Admin);
			    string hash;
			    string salt;
			    new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
			    authRepo.CreateUserAuth(new UserAuth {
				    DisplayName = userName,
			        Email = userName+"@mail.com",
			        UserName = userName,
			        FirstName = "",
			        LastName = "",
			        PasswordHash = hash,
			        Salt = salt,
					Roles =roles,
					Permissions=adminPermissions,
			    }, password);
			}
			// user
			userName="******";
			password="******";
			var meta= new Dictionary<string,string>();
			meta.Add("ExpiresAt", DateTime.UtcNow.SerializeToString());
			
			if ( authRepo.GetUserAuthByUserName(userName)== default(UserAuth) ){
				string hash;
			    string salt;
			    new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
			    authRepo.CreateUserAuth(new UserAuth {
				    DisplayName = userName,
			        Email = userName+"@mail.com",
			        UserName = userName,
			        FirstName = "",
			        LastName = "",
			        PasswordHash = hash,
			        Salt = salt,
					Permissions=userPermissions,
					Meta= meta
				}, password);
			}
			
		}
Exemplo n.º 7
0
		private void ConfigureAuth(Container container){
			
			
			var appSettings = new ConfigurationResourceManager();
			double se= appSettings.Get("DefaultSessionExpiry", 480);
			AuthProvider.DefaultSessionExpiry=TimeSpan.FromMinutes(se);			

			if (appSettings.Get("EnableRedisForAuthCache", false)){
				string cacheHost= appSettings.Get("AuthCacheHost", "localhost:6379");			
				int cacheDb= appSettings.Get("AuthCacheDb",8);				
										
				string cachePassword= appSettings.Get("AuthCachePassword",string.Empty);
						
				var p = new PooledRedisClientManager(new string[]{cacheHost},
							new string[]{cacheHost},
							cacheDb); 
				
				if(! string.IsNullOrEmpty(cachePassword))
					p.GetClient().Password= cachePassword;
				
				container.Register<ICacheClient>(p);
			}
			else
			{
				container.Register<ICacheClient>(new MemoryCacheClient());	
			}
			
			Plugins.Add(new AuthFeature(
				 () => new AuthUserSession(), // or Use your own typed Custom AuthUserSession type
				new IAuthProvider[]
        	{
				new AuthenticationProvider(){SessionExpiry=TimeSpan.FromMinutes(se)}
        	})
			{
				IncludeAssignRoleServices=false, 
			});
		    				
			var dbFactory = new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("UserAuth")) ;
			
			OrmLiteAuthRepository authRepo = new OrmLiteAuthRepository(
				dbFactory
			);
			
			container.Register<IUserAuthRepository>(
				c => authRepo
			); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info

			
			if (appSettings.Get("EnableRegistrationFeature", false))
				Plugins.Add( new  RegistrationFeature());
			
			
			
			if (!appSettings.Get("AddUsers", false)) return;
			
			
			// addusers
			var oldL =FirebirdOrmLiteDialectProvider.Instance.DefaultStringLength;
			
			FirebirdOrmLiteDialectProvider.Instance.DefaultStringLength=1024;
			if (appSettings.Get("RecreateAuthTables", false))
				authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
			else{
				authRepo.CreateMissingTables();   //Create only the missing tables				
			}
			
			FirebirdOrmLiteDialectProvider.Instance.DefaultStringLength=oldL;
						
		    //Add admin user  
			string userName = "******";
			string password = "******";
		
			List<string> permissions= new List<string>(
			new string[]{	
		
			});
			
			if ( authRepo.GetUserAuthByUserName(userName)== default(UserAuth) ){
				List<string> roles= new List<string>();
				roles.Add(RoleNames.Admin);
			    string hash;
			    string salt;
			    new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
			    authRepo.CreateUserAuth(new UserAuth {
				    DisplayName = userName,
			        Email = userName+"@mail.com",
			        UserName = userName,
			        FirstName = "",
			        LastName = "",
			        PasswordHash = hash,
			        Salt = salt,
					Roles =roles,
					Permissions=permissions
			    }, password);
			}
			
			userName = "******";
			password = "******";
		
			permissions= new List<string>(
			new string[]{	
			
			});
			
			if ( authRepo.GetUserAuthByUserName(userName)== default(UserAuth) ){
				List<string> roles= new List<string>();
				roles.Add("Test");
				string hash;
			    string salt;
			    new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
			    authRepo.CreateUserAuth(new UserAuth {
				    DisplayName = userName,
			        Email = userName+"@mail.com",
			        UserName = userName,
			        FirstName = "",
			        LastName = "",
			        PasswordHash = hash,
			        Salt = salt,
					Roles =roles,
					Permissions=permissions
			    }, password);
			}	
		}