Esempio n. 1
0
 public override IUserAuthRepository CreateAuthRepo()
 {
     var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
     var sqliteRepo = new OrmLiteAuthRepository(dbFactory);
     sqliteRepo.InitSchema();
     InitTest(sqliteRepo);
     return sqliteRepo;
 }
Esempio n. 2
0
 public override IUserAuthRepository CreateAuthRepo()
 {
     var connStr = @"Server=localhost;Database=test;User Id=test;Password=test;";
     var sqlServerFactory = new OrmLiteConnectionFactory(connStr, SqlServerDialect.Provider);
     var sqlServerRepo = new OrmLiteAuthRepository(sqlServerFactory);
     sqlServerRepo.InitSchema();
     InitTest(sqlServerRepo);
     return sqlServerRepo;
 }
        public void SetUp()
        {
			try
			{
                tests = new OAuthUserSessionTests();

                appHost = new BasicAppHost().Init();
                
                var inMemoryRepo = new InMemoryAuthRepository();
				inMemoryRepo.Clear();
				userAuthRepositorys.Add(inMemoryRepo);

                var appSettings = new AppSettings();
				var redisRepo = new RedisAuthRepository(new BasicRedisClientManager(new[] { 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);

                    sqliteInMemoryRepo.InitSchema();
                    sqliteInMemoryRepo.Clear();
					userAuthRepositorys.Add(sqliteInMemoryRepo);

					var sqliteDbFactory = new OrmLiteConnectionFactory( 
						"~/App_Data/auth.sqlite".MapProjectPath()); 
                    var sqliteDbRepo = new OrmLiteAuthRepository(sqliteDbFactory);
                    sqliteDbRepo.InitSchema();
					userAuthRepositorys.Add(sqliteDbRepo);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
				throw;
			}
		}
        public static void Main()
        {
            const string adminName = "Administrator";
            const string adminPassword = "******";
            const string userName = "******";
            const string userPassword = "******";

            var recreateAuthTables = ConfigurationManager.AppSettings["RecreateAuthTables"];
            var dbConnectionFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["AuthDB"].ConnectionString, SqlServerDialect.Provider);

            _authRepository = new OrmLiteAuthRepository(dbConnectionFactory);

            if ("true".Equals(recreateAuthTables, StringComparison.CurrentCultureIgnoreCase))
            {
                _authRepository.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
                CreateUser(1, adminName, "*****@*****.**", adminPassword, new List<string> {"Admin"}, new List<string> {"Administrator"});
                CreateUser(2, userName, null, userPassword, new List<string> { "TheRole" }, new List<string> { "ThePermission" });
            }
            else
            {
                _authRepository.InitSchema(); //Create only the missing tables
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        /// <param name="container"></param>
        public override void Configure(Container container)
        {
            //Config examples
            //this.Plugins.Add(new PostmanFeature());
            //this.Plugins.Add(new CorsFeature());

            this.Plugins.Add(new RazorFormat());
            Plugins.Add(new AutoQueryFeature {MaxLimit = 10000});
            Plugins.Add(new SwaggerFeature());
            //   Feature disableFeatures = Feature.Json| Feature.Html;
            SetConfig(new HostConfig()
            {
                AllowFileExtensions = {"json"},
                DefaultContentType = MimeTypes.Json,
                GlobalResponseHeaders =
                {
                    {"Access-Control-Allow-Origin", "*"},
                    {"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"},
                    {"Access-Control-Allow-Headers", "Content-Type"},
                },
                //  DefaultRedirectPath = "/page/login"
            });
            JsConfig<DateTime>.SerializeFn =time => new DateTime(time.Ticks, DateTimeKind.Local).ToString("yyyy-MM-dd HH:mm:ss");
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) =>
            {
                var builder = new StringBuilder();
                builder.AppendLine(httpReq.AbsoluteUri);
                builder.AppendLine(request.ToJsv());
                builder.AppendLine(exception.Message);
                builder.AppendLine(exception.StackTrace);
                return DtoUtils.CreateErrorResponse(request, exception);
            }
                );

            this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
            {
                var builder = new StringBuilder("UncaughtException\r\n");
                builder.AppendLine(req.AbsoluteUri);
                builder.AppendLine(req.Dto.ToJson());

                builder.AppendLine(req.GetRawBody());
                builder.AppendLine(ex.Message);
                builder.AppendLine(ex.StackTrace);
                res.EndRequest(skipHeaders: true);
            });
            Plugins.Add(new RegistrationFeature());
            var appSettings = new AppSettings();
            container.Register(appSettings);
            var dbFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), SqlServerDialect.Provider);
            container.Register<IDbConnectionFactory>(c =>dbFactory);
            var respo = new OrmLiteAuthRepository(dbFactory);
            respo.InitSchema();
            container.Register<IUserAuthRepository>(c => respo);
            Plugins.Add(new AuthFeature(
               () => new AuthUserSession(),
               new IAuthProvider[] { new CustomCredentialsAuthProvider() }, "/#/page/login"
               ));
            container.Register<IRedisClientsManager>(new PooledRedisClientManager(appSettings.GetString("redisHost")));
            dbFactory.OpenDbConnection().CreateTable<Cost>();
            dbFactory.OpenDbConnection().CreateTable<OrderCost>();
        }
        /// <summary>
        /// Configure ServiceStack Authentication plugin.
        /// </summary>
        /// <param name="container">The container.</param>
        private void ConfigureAuth(Container container)
        {
            Plugins.Add(new AuthFeature(() => new AuthUserSession(), 
                new IAuthProvider[]
                {
                    new BasicAuthProvider(AppSettings), 
                    new ApiKeyAuthProvider(AppSettings), 
                })
            {
                ServiceRoutes = new Dictionary<Type, string[]> {
                  { typeof(AuthenticateService), new[] { "/api/auth", "/api/auth/{provider}" } },
                }
            });

            var authRepo = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>());
            container.Register<IAuthRepository>(c => authRepo);
            authRepo.InitSchema();
        }
Esempio n. 7
0
        public override void Configure(Container container)
        {
            Plugins.Add(new RazorFormat());
            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new MetadataFeature());
            Plugins.Add(new RequestLogsFeature()
            {
                RequiredRoles = null,

            });
            Plugins.Add(new CsvFormat());
            Plugins.Add(new AutoQueryFeature()
            {
                MaxLimit = 100,
            });

            Plugins.Add(
                new CorsFeature(
                    (ConfigurationManager.AppSettings.Get("AllowOriginWhitelist") ?? "").Split(new char[] { ',' })));
            //Plugins.Add(new ValidationFeature
            //{
            //    ErrorResponseFilter = CustomValidationError
            //});
            //   Plugins.Add(new RequestLogsFeature{});

            SetConfig(new HostConfig { DebugMode = true });
            SetConfig(new HostConfig
            {
                DefaultContentType = MimeTypes.Json,
                EnableFeatures = Feature.All.Remove(Feature.Html),
                GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, },
                AllowFileExtensions = { "json" },
            });

            LogManager.LogFactory=new NullLogFactory(true);
            //SetConfig(new HostConfig
            //{
            //    AddMaxAgeForStaticMimeTypes =
            //    {
            //        {"image/png", TimeSpan.FromHours(10)}
            //    }
            //});
            JsConfig.ExcludeTypeInfo = true;
            JsConfig<DateTime>.SerializeFn =
                time => new DateTime(time.Ticks, DateTimeKind.Local).ToString("yyyy-MM-dd HH:mm:ss");

            //   JsConfig.DateHandler =DateHandler.ISO8601;
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) =>
            {
                var builder = new StringBuilder();
                builder.AppendLine(string.Format("{0}{1}", DateTime.Now, httpReq.AbsoluteUri));
                builder.AppendLine(request.ToJsv());
                builder.AppendLine(exception.Message);
                builder.AppendLine(exception.StackTrace);
               // Log.Error(builder);
                return DtoUtils.CreateErrorResponse(request, exception);
            });
            this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
            {
                var builder = new StringBuilder("UncaughtException\r\n");
                builder.AppendLine(string.Format("{0}{1}", DateTime.Now, req.AbsoluteUri));
                builder.AppendLine(req.Dto.ToJson());
                builder.AppendLine(ex.Message);
                builder.AppendLine(ex.StackTrace);
             //   Log.Error(builder);
                res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                res.EndRequest(true);
            });

            #region 数据库连接创建

            OrmLiteConnectionFactory dbFactory = null;

            dbFactory = new OrmLiteConnectionFactory(
                ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString,
                SqlServerOrmLiteDialectProvider.Instance)
            {
            #if DEBUG
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            #endif
            };

            #endregion

            container.Register<IDbConnectionFactory>(dbFactory);

            #region Validators
            //所有的验证方法放在一个类,这里不需要再加了
             //   container.RegisterValidators(typeof(ActivityFullReduceAddValidator).Assembly);
            #endregion

            JsConfig.DateHandler = DateHandler.ISO8601;
            SetConfig(new HostConfig()
            {
                EnableFeatures = Feature.All.Remove(Feature.Metadata),
            });

            var appSettings = new AppSettings();

            container.Register(appSettings);

            Plugins.Add(new RegistrationFeature());
            var redisFactory = new PooledRedisClientManager("localhost")
            {
                ConnectTimeout = 100,
                //...
            };

            //        container.Register<IDbConnectionFactory>(
            //new OrmLiteConnectionFactory(":memory:",ServiceStack.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider());
            container.Register<IRedisClientsManager>(c => redisFactory
               );
            container.Register<ICacheClient>(new MemoryCacheClient());
            container.Register(appSettings);
            var ormLiteAuthRepository = new OrmLiteAuthRepository(dbFactory);
            ormLiteAuthRepository.InitSchema();
            container.Register<IUserAuthRepository>(c => ormLiteAuthRepository);
            Plugins.Add(new AuthFeature(
                () => new AuthUserSession(),
                new IAuthProvider[] { new CustomCredentialsAuthProvider() }, "/views/login/login.html"
                ));
            AlertTable(dbFactory);
        }