Exemple #1
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);
            }
		}
        private void CreateUser(OrmLiteAuthRepository authRepo, int id, string username, string email, string password)
        {
            string hash;
            string salt;
            new SaltedHash().GetHashAndSaltString(password, out hash, out salt);

            authRepo.CreateUserAuth(new UserAuth
            {
                Id = id,
                DisplayName = "DisplayName",
                Email = email ?? "as@if" + id.ToString() + ".com",
                UserName = username,
                FirstName = "FirstName",
                LastName = "LastName",
                PasswordHash = hash,
                Salt = salt,
            }, password);
        }
		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);
			}
			
		}
Exemple #4
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);
			}	
		}