Exemple #1
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            SetConfig(new HostConfig
            {
                DefaultRedirectPath = "/metadata",
                DebugMode           = AppSettings.Get(nameof(HostConfig.DebugMode), false)
            });

            var builder = new ContainerBuilder();

            builder.RegisterType <WinOrLose>().AsImplementedInterfaces();
            builder.RegisterType <TenantBankingProvider>().AsImplementedInterfaces();
            builder.Register(c => new BackgroundMqService()).AsImplementedInterfaces().SingleInstance();

            IContainerAdapter adapter = new AutofacIocAdapter(builder.Build());

            container.Adapter = adapter;

            var mqServer = container.Resolve <IMessageService>();

            mqServer.RegisterHandler <ProcessPaymentRequest>(ExecuteMessage);
            mqServer.RegisterHandler <TenantBankingSetupRequest>(ExecuteMessage);
            mqServer.RegisterHandler <TenantBankingSetupError>(ExecuteMessage);
            mqServer.RegisterHandler <EnqueuePaymentRequest>(ExecuteMessage, 4);

            AfterInitCallbacks.Add(host => {
                mqServer.Start();
                //ExecuteService(new RetryPendingNotifications());
            });
        }
            public override void Configure(Container container)
            {
                Plugins.Add(new ValidationFeature());
                Plugins.Add(new GrpcFeature(App));

                container.Register <IAuthRepository>(new InMemoryAuthRepository());
                container.Resolve <IAuthRepository>().InitSchema();

                Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                            new IAuthProvider[]
                {
                    new BasicAuthProvider(),
                    new CredentialsAuthProvider(),
                    new JwtAuthProvider
                    {
                        AuthKey = AuthKey,
                        RequireSecureConnection = false,
                        AllowInQueryString      = true,
                        AllowInFormData         = true,
                        IncludeJwtInConvertSessionToTokenResponse = true,
                    },
                    new ApiKeyAuthProvider(AppSettings)
                    {
                        RequireSecureConnection = false
                    },
                }));

                Plugins.Add(new RegistrationFeature());

                GlobalRequestFilters.Add((req, res, dto) =>
                {
                    LastApiKey = req.GetApiKey();
                });

                AfterInitCallbacks.Add(host => {
                    var authRepo = GetAuthRepository();
                    (authRepo as InMemoryAuthRepository).Clear();

                    authRepo.CreateUserAuth(new UserAuth
                    {
                        Id          = userId.ToInt(),
                        UserName    = Username,
                        FirstName   = "First",
                        LastName    = "Last",
                        DisplayName = "Display",
                    }, Password);

                    apiRepo            = (IManageApiKeys)container.Resolve <IAuthRepository>();
                    var apiKeyProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                    var apiKeys        = apiKeyProvider.GenerateNewApiKeys(userId);
                    using (authRepo as IDisposable)
                    {
                        apiRepo.StoreAll(apiKeys);
                    }
                    liveKey = apiKeys.First(x => x.Environment == "live");
                    testKey = apiKeys.First(x => x.Environment == "test");
                });
            }
Exemple #3
0
    public override void Configure(Container container)
    {
        var mqServer = new RabbitMqServer {
            RetryCount = 1
        };

        container.Register <IMessageService>(c => mqServer);
        mqServer.RegisterHandler <ThrowVoid>(ExecuteMessage);
        AfterInitCallbacks.Add(appHost => mqServer.Start());
    }
Exemple #4
0
            public override void Configure(Container container)
            {
                Plugins.Add(new SharpPagesFeature());

                AfterInitCallbacks.Add(host => {
                    var memFs = VirtualFileSources.GetMemoryVirtualFiles();
                    foreach (var entry in HtmlFiles)
                    {
                        memFs.AppendFile(entry.Key, entry.Value);
                    }
                });
            }
Exemple #5
0
        public override void Configure(Container container)
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(AppContext.BaseDirectory)
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            AppSettings = new NetCoreAppSettings(configurationBuilder.Build());

            var redisFactory = new PooledRedisClientManager(
                AppSettings.GetString(AppSettingsKeys.RedisConnection));
            var mqServer = new RedisMqServer(redisFactory, retryCount: AppSettings.Get <int>(AppSettingsKeys.RedisRetries));

            var cacheClient          = redisFactory.GetCacheClient();
            var jobGroupId           = AppSettings.GetString(AppSettingsKeys.JobGroupId);
            var jobCompletedCacheKey = CacheKeys.JobCompleted <JobResponse>(jobGroupId);
            var numberOfJobs         = AppSettings.Get <int>(AppSettingsKeys.NumberOfJobs);

            cacheClient.Remove(jobCompletedCacheKey);

            mqServer.RegisterHandler <JobResponse>(m => {
                Console.WriteLine("Received: " + m.GetBody().Result);

                cacheClient.Increment(jobCompletedCacheKey, 1);
                if (cacheClient.Get <int>(jobCompletedCacheKey) >= numberOfJobs)
                {
                    appLifetime.StopApplication();
                }

                return(null);
            });

            AfterInitCallbacks.Add(host => {
                mqServer.Start();

                var mqClient = mqServer.CreateMessageQueueClient();
                for (var i = 1; i <= numberOfJobs; i++)
                {
                    mqClient.Publish(new JobRequest
                    {
                        JobId       = Guid.NewGuid().ToString(),
                        GroupId     = jobGroupId,
                        Description = $"Job {i}"
                    });
                }
            });
        }
        public override void Configure(Container container)
        {
            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(ValidateTestMqValidator).Assembly);

            container.Register(c => createMqServerFn());

            var mqServer = container.Resolve <IMessageService>();

            mqServer.RegisterHandler <AnyTestMq>(ExecuteMessage);
            mqServer.RegisterHandler <AnyTestMqAsync>(ExecuteMessage);
            mqServer.RegisterHandler <PostTestMq>(ExecuteMessage);
            mqServer.RegisterHandler <ValidateTestMq>(ExecuteMessage);
            mqServer.RegisterHandler <ThrowGenericError>(ExecuteMessage);
            mqServer.RegisterHandler <ThrowVoid>(ExecuteMessage);

            AfterInitCallbacks.Add(appHost => mqServer.Start());
        }
Exemple #7
0
        public override void Configure(Container container)
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(AppContext.BaseDirectory)
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            AppSettings = new NetCoreAppSettings(configurationBuilder.Build());

            var redisFactory = new PooledRedisClientManager(
                AppSettings.GetString(AppSettingsKeys.RedisConnection));
            var mqServer = new RedisMqServer(redisFactory, retryCount: AppSettings.Get <int>(AppSettingsKeys.RedisRetries));

            mqServer.RegisterHandler <JobRequest>(base.ExecuteMessage);

            AfterInitCallbacks.Add(host => {
                mqServer.Start();
            });
        }
Exemple #8
0
        /// <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),
            }));

            var authRepo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>());

            container.Register <IAuthRepository>(c => authRepo);
            authRepo.InitSchema();

            5.Times(x => authRepo.CreateUserAuth(new UserAuth {
                UserName = $"user{x}",
                Email    = $"user{x}@email.com",
            }, "test"));

            AfterInitCallbacks.Add(host =>
            {
                var authProvider = (ApiKeyAuthProvider)
                                   AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                using (var db = host.TryResolve <IDbConnectionFactory>().Open())
                {
                    var userWithKeysIds = db.Column <string>(db.From <ApiKey>()
                                                             .SelectDistinct(x => x.UserAuthId)).Map(int.Parse);

                    var userIdsMissingKeys = db.Column <string>(db.From <UserAuth>()
                                                                .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id))
                                                                .Select(x => x.Id));

                    foreach (var userId in userIdsMissingKeys)
                    {
                        var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString());
                        authRepo.StoreAll(apiKeys);
                    }
                }
            });
        }
Exemple #9
0
        public override void Configure(Container container)
        {
            var authFeature = new AuthFeature(() => new AuthUserSession(),
                                              new IAuthProvider[]
            {
                new CredentialsAuthProvider(AppSettings),
                new AzureAuthenticationProvider(new TestAzureGraphService())
                {
                }
            });

            Plugins.Add(authFeature);

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
            container.Register <IApplicationRegistryService>(
                c => new OrmLiteMultiTenantApplicationRegistryService(c.Resolve <IDbConnectionFactory>()));
            container.Register <IAuthRepository>(
                c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));


            AfterInitCallbacks.Add(appHost =>
            {
                var authRepo = appHost.TryResolve <IAuthRepository>();
                authRepo.InitSchema();

                var regService = appHost.TryResolve <IApplicationRegistryService>();
                regService.InitSchema();
                regService.RegisterApplication(new ApplicationRegistration
                {
                    ClientId      = "clientid",
                    ClientSecret  = "clientsecret",
                    DirectoryName = "foodomain.com"
                });
            });
        }
Exemple #10
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
//            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);
            log = LogManager.GetLogger(typeof(AppHost));

            // enable server-side rendering, see: http://templates.servicestack.net
            Plugins.Add(new TemplatePagesFeature {
            });
            GetPlugin <NativeTypesFeature>().MetadataTypesConfig.BaseUrl = "https://www.techstacks.io";

            var debugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false);

            SetConfig(new HostConfig
            {
                AddRedirectParamsToQueryString = true,
                DebugMode = debugMode,
            });

            JsConfig.DateHandler = DateHandler.ISO8601;

            var dbFactory = new OrmLiteConnectionFactory(
                Environment.GetEnvironmentVariable("TECHSTACKS_DB") ?? AppSettings.GetString("OrmLite.ConnectionString"),
                PostgreSqlDialect.Provider);

            dbFactory.RegisterDialectProvider(nameof(PostgreSqlDialect), PostgreSqlDialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[]
            {
                new TwitterAuthProvider(AppSettings),
                new GithubAuthProvider(AppSettings),
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    IncludeJwtInConvertSessionToTokenResponse = true,
                    CreatePayloadFilter = (payload, session) =>
                    {
                        var githubAuth = session.ProviderOAuthAccess.Safe()
                                         .FirstOrDefault(x => x.Provider == "github");
                        payload["ats"] = githubAuth?.AccessTokenSecret;
                    },
                    PopulateSessionFilter = (session, obj, req) =>
                    {
                        session.ProviderOAuthAccess = new List <IAuthTokens>
                        {
                            new AuthTokens {
                                Provider = "github", AccessTokenSecret = obj["ats"]
                            }
                        };
                    }
                },
                new DiscourseAuthProvider {
                    Provider     = "servicestack",
                    DiscourseUrl = "https://forums.servicestack.net",
                },
            })
            {
                HtmlRedirect = "/"
            });

            container.Register <IMarkdownProvider>(c =>
                                                   new GitHubApiMarkdownProvider(Environment.GetEnvironmentVariable("GITHUB_AUTH")));

            container.Register(new TwitterUpdates(
                                   AppSettings.GetString("WebStacks.ConsumerKey"),
                                   AppSettings.GetString("WebStacks.ConsumerSecret"),
                                   AppSettings.GetString("WebStacks.AccessToken"),
                                   AppSettings.GetString("WebStacks.AccessSecret"))
            {
                BaseUrl = AppSettings.GetString("PublicBaseUrl"),
            });

            container.Register(new EmailProvider {
                UserName  = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_USER") ?? AppSettings.GetString("smtp.UserName"),
                Password  = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_PASS") ?? AppSettings.GetString("smtp.Password"),
                EnableSsl = true,
                Host      = AppSettings.GetString("smtp.Host"),
                Port      = AppSettings.Get <int>("smtp.Port"),
                Bcc       = AppSettings.GetString("smtp.Bcc"),
            });

            var authRepo = new OrmLiteAuthRepository <CustomUserAuth, UserAuthDetails>(dbFactory);

            container.Register <IUserAuthRepository>(authRepo);
            authRepo.InitSchema();

            using (var db = dbFactory.OpenDbConnection())
            {
                db.CreateTableIfNotExists <TechnologyStack>();
                db.CreateTableIfNotExists <Technology>();
                db.CreateTableIfNotExists <TechnologyChoice>();
                db.CreateTableIfNotExists <UserFavoriteTechnologyStack>();
                db.CreateTableIfNotExists <UserFavoriteTechnology>();

                var baseUrl = "https://techstacks.io";

                Plugins.Add(new SitemapFeature
                {
                    SitemapIndex =
                    {
                        new Sitemap {
                            Location     = baseUrl + "/sitemap-techstacks.xml",
                            AtPath       = "/sitemap-techstacks.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <TechnologyStack>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl
                            {
                                Location = baseUrl + new ClientTechnologyStack{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            }),
                        },
                        new Sitemap {
                            Location     = baseUrl + "/sitemap-technologies.xml",
                            AtPath       = "/sitemap-technologies.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Technology>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl
                            {
                                Location = baseUrl + new ClientTechnology{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap
                        {
                            Location     = baseUrl + "/sitemap-users.xml",
                            AtPath       = "/sitemap-users.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <CustomUserAuth>().OrderByDescending(x => x.ModifiedDate))
                                           .Map(x => new SitemapUrl
                            {
                                Location = baseUrl + new ClientUser{
                                    UserName = x.UserName
                                }.ToAbsoluteUri(),
                                LastModified    = x.ModifiedDate,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap {
                            Location     = baseUrl + "/sitemap-organizations.xml",
                            AtPath       = "/sitemap-organizations.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Organization>().Where(x => x.Deleted == null).OrderByDescending(x => x.Modified))
                                           .Map(x => new SitemapUrl
                            {
                                Location        = baseUrl + $"/{x.Slug}",
                                LastModified    = x.Modified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap {
                            Location     = baseUrl + "/sitemap-posts.xml",
                            AtPath       = "/sitemap-posts.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Post>().Where(x => x.Type != PostType.Question && x.Deleted == null && x.Hidden == null).Take(1000).OrderByDescending(x => x.Modified))
                                           .Map(x => new SitemapUrl
                            {
                                Location        = baseUrl + $"/posts/{x.Id}/{x.Slug}",
                                LastModified    = x.Modified,
                                ChangeFrequency = SitemapFrequency.Hourly,
                            })
                        }
                    }
                });
            }

            Plugins.Add(new ValidationFeature());
            Plugins.Add(new AutoQueryMetadataFeature
            {
                AutoQueryViewerConfig =
                {
                    ServiceDescription        = "Discover what technologies were used to create popular Websites and Apps",
                    ServiceIconUrl            = "/img/app/logo-76.png",
                    BackgroundColor           = "#0095F5",
                    TextColor                 = "#fff",
                    LinkColor                 = "#ffff8d",
                    BrandImageUrl             = "/img/app/brand.png",
                    BrandUrl                  = "http://techstacks.io",
                    BackgroundImageUrl        = "/img/app/bg.png",
                    IsPublic                  = true,
                    OnlyShowAnnotatedServices = true,
                }
            });
            Plugins.Add(new AutoQueryFeature
            {
                MaxLimit         = 500,
                StripUpperInLike = false,
                ResponseFilters  =
                {
                    ctx => ctx.Response.Meta["Cache"] = Stopwatch.GetTimestamp().ToString()
                }
            });
            Plugins.Add(new AdminFeature());
            Plugins.Add(new OpenApiFeature());

            container.RegisterValidators(typeof(AppHost).Assembly);
            container.RegisterValidators(typeof(TechnologyServices).Assembly);

            RegisterTypedRequestFilter <IRegisterStats>((req, res, dto) =>
                                                        dbFactory.RegisterPageView(dto.GetStatsId()));

            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] { "https://techstacks.io", "https://www.techstacks.io",
                                                          "http://localhost:3000", "http://localhost:16325", "http://localhost:8080", "http://null.jsbin.com", "http://run.plnkr.co" },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization",
                            maxAge: 60 * 60)); //Cache OPTIONS permissions

            container.Register <IMessageService>(c => new BackgroundMqService());
            var mqServer = container.Resolve <IMessageService>();

            mqServer.RegisterHandler <SendNotification>(ExecuteMessage, 4);
            mqServer.RegisterHandler <SendSystemEmail>(ExecuteMessage);

            mqServer.Start();

            AfterInitCallbacks.Add(host => ExecuteService(new RetryPendingNotifications()));
        }
Exemple #11
0
        /// <summary>
        /// Configure the service with plugins and features.
        /// </summary>
        public override void Configure(Container container)
        {
            //set up orm connection factory, mainly used for auth stuff
            var dbFactory = new OrmLiteConnectionFactory(AppSettings.GetConnectionString("AUTH_DB"), SqlServer2012Dialect.Provider);

            container.Register <IDbConnectionFactory>(c => dbFactory);
            Plugins.Add(new OpenApiFeature()); //the open api feature
            //implement the custom auth provider
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                //new AspNetWindowsAuthProvider(this), //<-- this can only be used when hoisting in IIS!!!
                new ApiKeyAuthProvider(AppSettings)
                {
                    SessionCacheDuration = TimeSpan.FromMinutes(10),
                    KeyTypes             = new[] { "secret", "publishable" },
                },
                new CredentialsAuthProvider(AppSettings),
                new JwtAuthProvider(AppSettings),         //<--when not using Microsoft.Identity.Client to get JWT token.
                //new AadJwtAuthProvider(AppSettings),
                //new MicrosoftGraphAuthProvider(AppSettings),
                //new IdentityServerAuthFeature(AppSettings),
                //new CustomCredentialsAuthProvider(), //<-- we will use this to look at active directory, although should be changed to something else
                //other providers can be used for external connections.
            }));

            //allso add the registration feature, where we can register users, roles and permissions
            Plugins.Add(new RegistrationFeature());
            //add a memory cache client to the container.
            //container.Register<ICacheClient>(new MemoryCacheClient()); //<-- to do this in memory while in dev.
            //container.RegisterAs<OrmLiteCacheClient, ICacheClient>();
            //container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["AUTH_DB"].ConnectionString, SqlServer2012Dialect.Provider));
            //container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
            //{ UseDistinctRoleTables = true });
            //container.Resolve<IAuthRepository>().InitSchema();
            //container.Resolve<ICacheClient>().InitSchema();
            //container.Register<ICacheClient>(new JarsCacheClient());
            //container.Register<IAuthRepository>(c => new JarsAuthRepository());
            container.Register <ICacheClient>(new OrmLiteCacheClient()
            {
                DbFactory = dbFactory
            });
            container.Resolve <ICacheClient>().InitSchema();
            container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(dbFactory));
            container.Resolve <IAuthRepository>().InitSchema();
            //new SaltedHash().GetHashAndSaltString("password", out string hash, out string salt);
            //then we need to add a user to authenticate to the user repository.

            var authRepo = container.Resolve <IAuthRepository>();

            //add in default user/s

            if (authRepo.GetUserAuthByUserName("JarsAdminUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Admin",
                    LastName    = "Admin",
                    DisplayName = "Jars Admin",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { RoleNames.Admin },
                    Permissions = { JarsPermissions.Full }
                }, "J@r5@dm1nU53r");
            }

            if (authRepo.GetUserAuthByUserName("AdminUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "AdminTest",
                    LastName    = "AdminTest",
                    DisplayName = "Jars Admin Test",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { RoleNames.Admin },
                    Permissions = { JarsPermissions.Full }
                }, "adminuser");
            }

            if (authRepo.GetUserAuthByUserName("GuestUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Guest",
                    LastName    = "User",
                    DisplayName = "Guest User",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.Guest },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanViewAppointment }
                }, "guestuser");
            }

            if (authRepo.GetUserAuthByUserName("TestUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Test",
                    LastName    = "User",
                    DisplayName = "Test User",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.User },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanEdit, }
                }, "testuser");
            }

            if (authRepo.GetUserAuthByUserName("TestUserAdd") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Test",
                    LastName    = "User",
                    DisplayName = "Test User Add",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.User },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanAdd }
                }, "testuser");
            }

            if (authRepo.GetUserAuthByUserName("TestUserAddEdit") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Test",
                    LastName    = "User",
                    DisplayName = "Test User Add Edit",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.User },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanAdd, JarsPermissions.CanEdit }
                }, "testuser");
            }

            if (authRepo.GetUserAuthByUserName("PowerUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Power",
                    LastName    = "User",
                    DisplayName = "Power User",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.PowerUser },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanAdd, JarsPermissions.CanEdit, JarsPermissions.CanDelete }
                }, "poweruser");
            }

            if (authRepo.GetUserAuthByUserName("ManagerUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "Manager",
                    LastName    = "User",
                    DisplayName = "Manager User",
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    Roles       = { JarsRoles.Manager },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanAdd, JarsPermissions.CanEdit, JarsPermissions.CanDelete }
                }, "manageruser");
            }

            if (authRepo.GetUserAuthByUserName("MobileAppUser") == null)
            {
                authRepo.CreateUserAuth(new UserAuth()
                {
                    FirstName   = "MobileApp",
                    LastName    = "User",
                    DisplayName = "MobileApp User",
                    UserName    = "******",
                    //Email = "*****@*****.**",
                    Roles       = { JarsRoles.MobileApp },
                    Permissions = { JarsPermissions.CanView, JarsPermissions.CanAdd, JarsPermissions.CanEdit, JarsPermissions.CanDelete }
                }, "thisneedstochange");
            }
            AfterInitCallbacks.Add(host =>
            {
                var authProvider = (ApiKeyAuthProvider)
                                   AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                using (var db = host.TryResolve <IDbConnectionFactory>().Open())
                {
                    var userWithKeysIds = db.Column <string>(db.From <ApiKey>()
                                                             .SelectDistinct(x => x.UserAuthId)).Map(int.Parse);

                    var userIdsMissingKeys = db.Column <string>(db.From <UserAuth>()
                                                                .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id))
                                                                .Select(x => x.Id));

                    var aRepo = (IManageApiKeys)host.TryResolve <IAuthRepository>();
                    foreach (var userId in userIdsMissingKeys)
                    {
                        var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString());
                        aRepo.StoreAll(apiKeys);
                    }
                }
            });
        }
Exemple #12
0
        /// <summary>
        /// 个性化配置
        /// 用户初始化服务器需要的IOC资源
        /// </summary>
        public override void Configure(Container container)
        {
            //注册模板页面
            SetConfig(new HostConfig
            {
                //调试模式
                DebugMode = AppSettings.Get("DebugMode", false),
                ////隐藏metadata page页面
                //EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //没有登录可以使用?authsecret=xxx方式,和登录效果一致
                AdminAuthSecret = AppSettings.Get("AdminAuthSecret", "secretz"),
                //注册网页根目录
                //WebHostPhysicalPath = MapProjectPath("~/my-project/dist"),
                //WebHostPhysicalPath = MapProjectPath("~/wwwroot"),
                AddRedirectParamsToQueryString = true,
                //UseCamelCase = true,
                //注册接口服务地址
                HandlerFactoryPath = "api",
                DefaultContentType = MimeTypes.Json,
            });
            //注册测试页
            Plugins.Add(new TemplatePagesFeature());

            Plugins.Add(new AdminFeature());

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

            //Plugins.Add(new BasicAuthFeature());

            //添加一个request filter 确认用户的登录session
            //this.GlobalRequestFilters.Add((req, res, requestDto) =>
            //{
            //    if (!req.GetSession().IsAuthenticated)
            //    {
            //        res.ReturnAuthRequired();
            //    }
            //});

            //container.Register<IAuthProvider>(r => new myAuthProvider());


            //获取连接字符串
            var connectionString = ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString;

            //注册数据库连接工厂
            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
            //注册数据库连接
            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = true
            });
            //获取用户表的数据库连接,如果没有生成表则自动生成
            container.Resolve <IAuthRepository>().InitSchema();


            //Also store User Sessions in SQL Server
            container.RegisterAs <OrmLiteCacheClient, ICacheClient>();
            container.Resolve <ICacheClient>().InitSchema();


            //获取数据库的配置连接
            //container.Register<IAppSettings>(c => new OrmLiteAppSettings(c.Resolve<IDbConnectionFactory>()));

            //container.Register<IAppSettings>(c => new AppSettings());
            //获取配置
            //var appsetting = (AppSettings)container.Resolve<IAppSettings>();
            //初始化数据表
            //appsetting.InitSchema();

            //appsetting.Get("test", "test");

            var privateKey   = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048);
            var publicKeyXml = privateKey.ToPublicKeyXml();


            //所有需要用账号访问的方法,都会调用认证界面CustomUserSession,myAuthProvider为自定义的方法
            //Add Support for
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                    AllowInQueryString      = true,
                    SessionExpiry           = TimeSpan.FromDays(1),
                    //RedirectUrl = "www.baidu.com",
                    ExpireRefreshTokensIn = TimeSpan.FromDays(1),
                    ExpireTokensIn        = TimeSpan.FromDays(100),
                    CreatePayloadFilter   = (payload, session) =>
                    {
                        if (session.IsAuthenticated)
                        {
                            payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString();
                            payload["exp"]       = DateTime.UtcNow.AddYears(1).ToUnixTime().ToString();
                        }
                    },

                    //AuthKeyBase64 = "Base64AuthKey",//AppSettings.GetString("AuthKeyBase64") //"Base64AuthKey",
                    //HashAlgorithm = "RS256",
                    //PrivateKeyXml ="PrivateKey2016Xml", //AppSettings.GetString("PrivateKeyXml")
                },
                new ApiKeyAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    ExpireKeysAfter         = TimeSpan.FromDays(100),
                    SessionCacheDuration    = TimeSpan.FromMinutes(10),
                    InitSchema        = true,
                    AllowInHttpParams = true,
                    //KeyTypes = new[] { "secret", "publishable" },
                },                             //Sign-in with API Key
                new CredentialsAuthProvider(), //Sign-in with UserName/Password credentials
                new BasicAuthProvider(),       //Sign-in with HTTP Basic Auth
            })
            {
                IncludeRegistrationService   = true,
                IncludeAssignRoleServices    = true,
                IncludeAuthMetadataProvider  = true,
                ValidateUniqueEmails         = true,
                ValidateUniqueUserNames      = true,
                DeleteSessionCookiesOnLogout = true,
                SaveUserNamesInLowerCase     = true,
                GenerateNewSessionCookiesOnAuthentication = true,
            });

            //Default route: /register
            //Plugins.Add(new RegistrationFeature() { AllowUpdates = true });
            ////The IAuthRepository is used to store the user credentials etc.
            ////Implement this interface to adjust it to your app's data storage



            //CreateUser(10, "jinchaoqian1", "*****@*****.**", "j4012693", new List<string> { "TheRole" }, new List<string> { "ThePermission" });

            //记录日志
            LogManager.LogFactory = new MyLoggerFactory();
            //启用日志
            Plugins.Add(new RequestLogsFeature()
            {
                EnableRequestBodyTracking = true,
                EnableResponseTracking    = true,
                EnableSessionTracking     = true,
                EnableErrorTracking       = true,
            });
            //启用跨域访问
            this.Plugins.Add(new CorsFeature(allowedMethods: "GET, POST"));
            //注册Swagger插件进行API的Web调试
            Plugins.Add(new SwaggerFeature());
            //启用验证插件
            Plugins.Add(new ValidationFeature());
            //注册验证插件
            container.RegisterValidators(typeof(LoginValidator).Assembly);
            ////自动扫描验证插件
            //Plugins.Add(new ValidationFeature
            //{
            //    ScanAppHostAssemblies = true
            //});


            //JsConfig.EmitLowercaseUnderscoreNames = true;
            //JsConfig.ExcludeDefaultValues = true;
            //序列化时的日期格式
            JsConfig <DateTime> .SerializeFn = dateTime => dateTime.ToString("yyyy-MM-dd");
            JsConfig <TimeSpan> .SerializeFn = time =>
                                               (time.Ticks < 0 ? "-" : "") + time.ToString("hh':'mm':'ss'.'fffffff");

            //container.Register<ICacheClient>(c => new OrmLiteCacheClient(){DbFactory = c.Resolve<IDbConnectionFactory>()});

            //var cache = container.Resolve<OrmLiteCacheClient>();
            //cache.DbFactory = container.Resolve<IDbConnectionFactory>();

            //container.RegisterAs<OrmLiteCacheClient, ICacheClient>();

            ////Create 'CacheEntry' RDBMS table if it doesn't exist already
            //container.Resolve<ICacheClient>().InitSchema();

            container.Register <ICacheClient>(new MemoryCacheClient());



            //虚拟目录,使用插件方式或者是重载GetVirtualFileSources
            //Plugins.Add(new Disk1Plugin());

            //捕捉到被处理过的错误
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                //记录错误信息
                //TODO:
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return(null); //返回默认错误

                //或者自定义错误
                //return DtoUtils.CreateErrorResponse(request, exception);
            });

            //处理未被系统处理的错误
            //E.g. Exceptions during Request binding or in filters:
            this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
            {
                res.WriteAsync($"Error: {ex.GetType().Name}: {ex.Message}");
                res.EndRequest(skipHeaders: true);
            });

            AfterInitCallbacks.Add(host =>
            {
                var authProvider = (ApiKeyAuthProvider)
                                   AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                using (var db = host.TryResolve <IDbConnectionFactory>().Open())
                {
                    var userWithKeysIds = db.Column <string>(db.From <ApiKey>()
                                                             .SelectDistinct(x => x.UserAuthId)).Map(int.Parse);

                    var userIdsMissingKeys = db.Column <string>(db.From <UserAuth>()
                                                                .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id))
                                                                .Select(x => x.Id));

                    var authRepo = (IManageApiKeys)host.TryResolve <IAuthRepository>();
                    foreach (var userId in userIdsMissingKeys)
                    {
                        var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString());
                        authRepo.StoreAll(apiKeys);
                    }
                }
            });
        }