/// <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 CredentialsAuthProvider(AppSettings), new JwtAuthProvider(AppSettings) { AuthKey = Convert.FromBase64String("3n/aJNQHPx0cLu/2dN3jWf0GSYL35QlMqgz+LH3hUyA="), RequireSecureConnection = false, }, new ApiKeyAuthProvider(AppSettings), new BasicAuthProvider(AppSettings), })); Plugins.Add(new RegistrationFeature()); var authRepo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); container.Register <IAuthRepository>(c => authRepo); authRepo.InitSchema(); authRepo.CreateUserAuth(new UserAuth { UserName = "******", DisplayName = "Credentials", FirstName = "First", LastName = "Last", FullName = "First Last", }, "test"); }
public override void Configure(Container container) { container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)); var dbFactory = container.Resolve <IDbConnectionFactory>(); this.Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new TwitterAuthProvider(this.AppSettings), new GithubAuthProvider(this.AppSettings), new CredentialsAuthProvider(), })); var authRepo = new OrmLiteAuthRepository <CustomUserAuth, UserAuthDetails>(dbFactory); container.Register <IUserAuthRepository>(authRepo); authRepo.InitSchema(); container.RegisterAs <OrmLiteCacheClient, ICacheClient>(); container.Resolve <ICacheClient>().InitSchema(); using (var db = dbFactory.OpenDbConnection()) { db.CreateTableIfNotExists <TechnologyStack>(); db.CreateTableIfNotExists <Technology>(); db.CreateTableIfNotExists <TechnologyChoice>(); db.CreateTableIfNotExists <UserFavoriteTechnologyStack>(); db.CreateTableIfNotExists <UserFavoriteTechnology>(); } this.Plugins.Add(new AutoQueryFeature { MaxLimit = 1000 }); }
/// <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 CredentialsAuthProvider(AppSettings), new ApiKeyAuthProvider(AppSettings), new BasicAuthProvider(AppSettings), })); Plugins.Add(new RegistrationFeature()); var authRepo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); container.Register <IAuthRepository>(c => authRepo); authRepo.InitSchema(); authRepo.CreateUserAuth(new UserAuth { UserName = "******", DisplayName = "Credentials", FirstName = "First", LastName = "Last", FullName = "First Last", }, "test"); }
private void CreateAdmine(OrmLiteAuthRepository authRepo) { var admine = authRepo.GetUserAuthByUserName("Maksym"); if (admine == null) { string hash; string salt; var adminEmail = ConfigurationManager.AppSettings["adminEmail"]; var adminLastName = ConfigurationManager.AppSettings["adminLastName"]; var adminName = ConfigurationManager.AppSettings["adminName"]; var adminPassword = ConfigurationManager.AppSettings["adminPassword"]; new SaltedHash().GetHashAndSaltString("password", out hash, out salt); authRepo.CreateUserAuth(new UserAuth { Id = 1, DisplayName = adminName, Email = adminEmail, UserName = adminName, FirstName = adminName, LastName = adminLastName, PasswordHash = hash, Salt = salt, Roles = new List <string> { RoleNames.Admin }, // Permissions = new List<string> { "GetStatus" } }, adminPassword); } }
private static void ResetAll(Container container, OrmLiteAuthRepository authRepo) { authRepo.DropAndReCreateTables(); container.Resolve <IDbConnectionFactory>().Run(db => { db.DropAndCreateTable <EmailRegistration>(); db.DropAndCreateTable <SMessageReceipt>(); }); container.Resolve <IRedisClientsManager>().Exec(r => r.FlushAll()); }
public override IUserAuthRepository CreateAuthRepo() { var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider); var sqliteRepo = new OrmLiteAuthRepository(dbFactory); sqliteRepo.InitSchema(); InitTest(sqliteRepo); return(sqliteRepo); }
private void SetupDatabase(Container container) { var connectionString = AppSettings.Get <string>("database:connectionString"); var Db = new OrmLiteConnectionFactory(connectionString, PostgreSqlDialect.Provider); container.Register <IDbConnectionFactory>(c => Db); var OrmAuthRepo = new OrmLiteAuthRepository <AppUser, UserAuthDetails>(Db); container.Register <IAuthRepository>(c => OrmAuthRepo); }
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 override IUserAuthRepository CreateAuthRepo() { var connStr = @"Data Source=.\SQLEXPRESS;database=test;Integrated Security=True;"; var sqlServerFactory = new OrmLiteConnectionFactory(connStr, SqlServerDialect.Provider); var sqlServerRepo = new OrmLiteAuthRepository(sqlServerFactory); sqlServerRepo.InitSchema(); InitTest(sqlServerRepo); return(sqlServerRepo); }
public override IUserAuthRepository CreateAuthRepo() { var sqlServerFactory = new OrmLiteConnectionFactory( TestsConfig.SqlServerConnString, SqlServerDialect.Provider); var sqlServerRepo = new OrmLiteAuthRepository(sqlServerFactory); sqlServerRepo.InitSchema(); InitTest(sqlServerRepo); return(sqlServerRepo); }
public static void ResetUsers(OrmLiteAuthRepository authRepo) { authRepo.DropAndReCreateTables(); CreateUser(authRepo, 1, "test", "test", new List <string> { "TheRole" }, new List <string> { "ThePermission" }); CreateUser(authRepo, 2, "test2", "test2"); }
public void CreateUsers(Container container) { var userRep = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); userRep.DropAndReCreateTables(); container.Register <IUserAuthRepository>(userRep); var appSettings = container.Resolve <PlacesToVisitAppSettings>(); var dataRepository = container.Resolve <IPlacesToVisitRepository>(); userRep.DropAndReCreateTables(); string pwHash; string pwSalt; new SaltedHash().GetHashAndSaltString( appSettings.Get("Salt", "debugSalt"), out pwHash, out pwSalt); var userAuth1 = userRep.CreateUserAuth(new UserAuth { Email = "*****@*****.**", DisplayName = "Darren", UserName = "******", FirstName = "Darren", LastName = "Reid", PasswordHash = pwHash, Salt = pwSalt, Roles = { "Admin" } }, "abc123"); var user1 = userAuth1.ConvertTo <User>(); dataRepository.CreateUserIfNotExists(user1); var userAuth2 = userRep.CreateUserAuth(new UserAuth { Email = "*****@*****.**", DisplayName = "Kyle", UserName = "******", FirstName = "Kyle", LastName = "Hodgson", PasswordHash = pwHash, Salt = pwSalt, Roles = { "Admin" } }, "123abc"); var user2 = userAuth2.ConvertTo <User>(); dataRepository.CreateUserIfNotExists(user2); }
public void Register(IAppHost appHost) { //Pre init process // Dependency var container = appHost.GetContainer(); var appSettings = appHost.AppSettings; //Register all Authentication methods you want to enable for this web app. appHost.Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new ApiKeyAuthProvider(appSettings), new CredentialsAuthProvider() { SessionExpiry = new TimeSpan(0, 30, 0) }, //Sign-in with UserName/Password credentials new BasicAuthProvider() { SessionExpiry = new TimeSpan(0, 30, 0) }, //Sign-in with HTTP Basic Auth } ) { IncludeAssignRoleServices = true, MaxLoginAttempts = 5, ServiceRoutes = new Dictionary <Type, string[]> { { typeof(AuthenticateService), new[] { "/auth", "/auth/{provider}" } }, }, GenerateNewSessionCookiesOnAuthentication = true, DeleteSessionCookiesOnLogout = true, IncludeAuthMetadataProvider = false }); //Store User Data into the referenced SQl server var repo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()) { UseDistinctRoleTables = true }; container.Register <IAuthRepository>(c => repo); container.Register <IUserAuthRepository>(c => repo); repo.InitSchema(); //Custom validators appHost.Register <IValidator <CreateUser> >(new CreateUserValidator()); //Custom services appHost.RegisterService <UserService>(); }
/// <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 CredentialsAuthProvider(AppSettings), new ApiKeyAuthProvider(AppSettings), new BasicAuthProvider(AppSettings), })); Plugins.Add(new RegistrationFeature()); var authRepo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); container.Register <IAuthRepository>(c => authRepo); authRepo.InitSchema(); }
public override void Configure(Container container) { //1. Registering the Authorization Provider Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() })); //2. Enabling the /register service Plugins.Add(new RegistrationFeature()); //3. configuring the Repository that uses SQL Server backend var connString = "Data Source=;Initial Catalog=;User ID=;password="******"johnd") == null) { ormLiteRepository.CreateUserAuth(new UserAuth { UserName = "******", FirstName = "John", LastName = "Doe", Roles = new List <string> { RoleNames.Admin } }, "mypassword"); } //4. Registering the Session Cache container.Register <ICacheClient>(new MemoryCacheClient()); }
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); using (var db = dbFactory.Open()) { db.DropAndCreateTable <UserAuth>(); db.DropAndCreateTable <UserAuthDetails>(); } 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; } }
private void EnableAuthentication(Container container) { Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), //Sign-in with Basic Auth new CredentialsAuthProvider() //HTML Form post of UserName/Password credentials }) { IncludeAssignRoleServices = false }); //Not utilizing roles at this time, so simplifying API. Plugins.Add(new RegistrationFeature()); container.Register <ICacheClient>(new MemoryCacheClient()); var userRep = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); container.Register <IUserAuthRepository>(userRep); container.Resolve <IUserAuthRepository>().InitSchema(); }
public override void Configure(Container container) { Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() })); Plugins.Add(new RegistrationFeature()); container.Register <ICacheClient>(new MemoryCacheClient()); //configuring OrmLiteAuthRepository that uses SQL Server backend var connString = "Data Source=;Initial Catalog=;User ID=;password="******"johnd") == null) { ormLiteRepository.CreateUserAuth(new UserAuth { UserName = "******", FirstName = "John", LastName = "Doe", Roles = new List <string> { RoleNames.Admin } }, "mypassword"); } }
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 CreateUser(OrmLiteAuthRepository authRepo, int id, string username, string password, List <string> roles = null, List <string> permissions = null) { new SaltedHash().GetHashAndSaltString(password, out var hash, out var salt); authRepo.CreateUserAuth(new UserAuth { Id = id, DisplayName = username + " DisplayName", Email = username + "@gmail.com", UserName = username, FirstName = "First " + username, LastName = "Last " + username, PasswordHash = hash, Salt = salt, Roles = roles, Permissions = permissions }, password); authRepo.AssignRoles(id.ToString(), roles, permissions); }
/// <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(); }
/// <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); } } }); }
/// <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()); }
public override void Configure(Funq.Container container) { Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new ConcordAPI.ServiceInterface.ConcordyaBasicAuthProvider() //Sign-in with Basic Auth })); Plugins.Add(new RegistrationFeature()); //Plugins.Add(new AutoQueryFeature { MaxLimit = 100 }); container.Register <ICacheClient>(new MemoryCacheClient()); container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory( new AppSettings().Get( "ConcordAPI.Properties.Settings.LocalSQLConnectionString", db_conn_string), SqlServerDialect.Provider)); //container.Resolve var userRepository = new OrmLiteAuthRepository <UserAccount, UserAccountDetail>(container.Resolve <IDbConnectionFactory>()); container.Register <IUserAuthRepository>(userRepository); InitialDbTables(container, userRepository); }
private static void InitialDbTables(Funq.Container container, OrmLiteAuthRepository <UserAccount, UserAccountDetail> userRepository) { string hash, salt; new SaltedHash().GetHashAndSaltString("password1", out hash, out salt); userRepository.DropAndReCreateTables(); using (var dbConnection = container.Resolve <IDbConnectionFactory>().OpenDbConnection()) { dbConnection.CreateTable <Bill>(true); dbConnection.CreateTable <Invoice>(true); dbConnection.CreateTable <AddressBranching>(true); dbConnection.CreateTable <Address>(true); dbConnection.CreateTable <Company>(true); dbConnection.CreateTable <Category>(true); } userRepository.CreateUserAuth(new UserAccount { UserName = "******", Password = hash, FullName = "Cheng Zhang", Email = "*****@*****.**", Salt = salt, Roles = new List <string> { RoleNames.Admin }, Permissions = new List <string> { "Get" }, CreatedDate = DateTime.Now, Create_On = DateTime.Now, LastLoginTime = DateTime.Now, Last_Updated_By = 0, Last_Updated_On = DateTime.Now }, "password1"); }
/// <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) { JsConfig.EmitCamelCaseNames = true; SetConfig(new HostConfig { DebugMode = AppSettings.Get("DebugMode", false), AddRedirectParamsToQueryString = true, }); this.Plugins.Add(new RazorFormat()); container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory( AppSettings.GetString("ConnectionString"), PostgreSqlDialect.Provider)); this.Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(AppSettings), })); var dbFactory = container.Resolve <IDbConnectionFactory>(); var authRepo = new OrmLiteAuthRepository(dbFactory); container.Register <IUserAuthRepository>(authRepo); authRepo.InitSchema(); container.RegisterAs <OrmLiteCacheClient, ICacheClient>(); container.Resolve <ICacheClient>().InitSchema(); container.Register(c => new ContentCache(new MemoryCacheClient())); using (var db = dbFactory.OpenDbConnection()) { //db.DropAndCreateTable<AutoQueryService>(); db.CreateTableIfNotExists <AutoQueryService>(); } }
private void ConfigureAuth(Container container, IAppSettings appSettings) { //Register all Authentication methods you want to enable for this web app. Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new ApiKeyAuthProvider(appSettings), new CredentialsAuthProvider() { SessionExpiry = new TimeSpan(0, 30, 0) }, //Sign-in with UserName/Password credentials new BasicAuthProvider() { SessionExpiry = new TimeSpan(0, 30, 0) }, //Sign-in with HTTP Basic Auth } ) { IncludeAssignRoleServices = true, MaxLoginAttempts = 5, ServiceRoutes = new Dictionary <Type, string[]> { { typeof(AuthenticateService), new[] { "/auth", "/auth/{provider}" } }, }, GenerateNewSessionCookiesOnAuthentication = true, DeleteSessionCookiesOnLogout = true, IncludeAuthMetadataProvider = false }); Plugins.Add(new RegistrationFeature()); //Store User Data into the referenced SQl server var repo = new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>()); container.Register <IAuthRepository>(c => repo); container.Register <IUserAuthRepository>(c => repo); repo.InitSchema(); }
/// <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) { SetConfig(new HostConfig { AddRedirectParamsToQueryString = true, WebHostUrl = "http://techstacks.io", //for sitemap.xml urls }); JsConfig.DateHandler = DateHandler.ISO8601; if (AppSettings.GetString("OrmLite.Provider") == "Postgres") { container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory(AppSettings.GetString("OrmLite.ConnectionString"), PostgreSqlDialect.Provider)); } else { container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory("~/App_Data/db.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider)); } var dbFactory = container.Resolve <IDbConnectionFactory>(); this.Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new TwitterAuthProvider(AppSettings), new GithubAuthProvider(AppSettings), new JwtAuthProvider(AppSettings) { RequireSecureConnection = false }, })); container.Register(new TwitterUpdates( AppSettings.GetString("WebStacks.ConsumerKey"), AppSettings.GetString("WebStacks.ConsumerSecret"), AppSettings.GetString("WebStacks.AccessToken"), AppSettings.GetString("WebStacks.AccessSecret"))); 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>(); RawHttpHandlers.Add(req => req.PathInfo == "/robots.txt" ? new NotFoundHttpHandler() : null); Plugins.Add(new SitemapFeature { SitemapIndex = { new Sitemap { AtPath = "/sitemap-techstacks.xml", LastModified = DateTime.UtcNow, UrlSet = db.Select(db.From <TechnologyStack>().OrderByDescending(x => x.LastModified)) .Map(x => new SitemapUrl { Location = new ClientTechnologyStack{ Slug = x.Slug }.ToAbsoluteUri(), LastModified = x.LastModified, ChangeFrequency = SitemapFrequency.Weekly, }), }, new Sitemap { AtPath = "/sitemap-technologies.xml", LastModified = DateTime.UtcNow, UrlSet = db.Select(db.From <Technology>().OrderByDescending(x => x.LastModified)) .Map(x => new SitemapUrl { Location = new ClientTechnology{ Slug = x.Slug }.ToAbsoluteUri(), LastModified = x.LastModified, ChangeFrequency = SitemapFrequency.Weekly, }) }, new Sitemap { AtPath = "/sitemap-users.xml", LastModified = DateTime.UtcNow, UrlSet = db.Select(db.From <CustomUserAuth>().OrderByDescending(x => x.ModifiedDate)) .Map(x => new SitemapUrl { Location = new ClientUser{ UserName = x.UserName }.ToAbsoluteUri(), LastModified = x.ModifiedDate, ChangeFrequency = SitemapFrequency.Weekly, }) } } }); } Plugins.Add(new RazorFormat()); 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 = 200 }); 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[] { "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net", "http://null.jsbin.com" }, allowCredentials: true, allowedHeaders: "Content-Type, Allow, Authorization")); }
public static void Settup_Test_Database(IDbConnectionFactory dbFactory = null) { var dbConnectionFactory = dbFactory; if (dbConnectionFactory == null) { var connectionString = ConfigurationManager.ConnectionStrings["Auth202Db"].ConnectionString; dbConnectionFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider); } using (var db = dbConnectionFactory.OpenDbConnection()) { if (db.TableExists("Transaction")) { db.DropTable <Transaction>(); } if (db.TableExists("CurrencyType")) { db.DropTable <CurrencyType>(); } if (db.TableExists("TransactionStatusType")) { db.DropTable <TransactionStatusType>(); } if (db.TableExists("TransactionNotificationStatusType")) { db.DropTable <TransactionNotificationStatusType>(); } if (db.TableExists("TransactionType")) { db.DropTable <TransactionType>(); } db.CreateTable <TransactionType>(); db.CreateTable <TransactionNotificationStatusType>(); db.CreateTable <TransactionStatusType>(); db.CreateTable <CurrencyType>(); db.CreateTable <Transaction>(); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.AuthorizeAndCapture, Description = "Authorize and Capture" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.AuthorizeOnly, Description = "Authorize Only" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.CapturePrior, Description = "Capture Prior Authorization" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.Refund, Description = "Refund" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.Void, Description = "Void" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.ZeroDollar, Description = "An internal zero dollar transaction" }); db.Insert(new TransactionType { Id = (long)TRANSACTION_TYPE.Unknown, Description = "The transaction type is unknown" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.None, Status = "Processing" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.DeclinedNotification, Status = "Declined Notification Sent" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.ErrorNotification, Status = "Error Notifications Sent" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.SettledNotification, Status = "Settled Notifications Sent" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.RefundedNotification, Status = "Refunded Notifications Sent" }); db.Insert(new TransactionNotificationStatusType { Id = (long)TRANSACTION_NOTIFICATION_STATUS.VoidedNotification, Status = "Voided Notifications Sent" }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Pending, Status = "Transaction Approved but pending completion" }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Settled, Status = "Transaction completed. Funds received." }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Refunded, Status = "Transaction completed. Customer refunded." }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Voided, Status = "Transaction voided." }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Expired, Status = "Transaction has expired." }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Declined, Status = "Transaction Declinded.", IsErrorStatus = true }); db.Insert(new TransactionStatusType { Id = (long)TRANSACTION_STATUS.Error, Status = "Transaction Error.", IsErrorStatus = true }); db.Insert(new CurrencyType { Id = (long)CURRENCY_TYPE.USDollar, Description = "US Dollar", Code = "USD", Symbol = "$" }); db.Insert(new CurrencyType { Id = (long)CURRENCY_TYPE.CandianDollar, Description = "Canadian Dollar", Code = "CAD", Symbol = "$" }); db.Insert(new CurrencyType { Id = (long)CURRENCY_TYPE.Peso, Description = "Mexican Peso", Code = "MXN", Symbol = "$" }); } var userRepo = new OrmLiteAuthRepository(dbConnectionFactory); userRepo.DropAndReCreateTables(); var user = new UserAuth { Id = DefaultAdmin.Id, DisplayName = DefaultAdmin.Username, Email = DefaultAdmin.Email, UserName = DefaultAdmin.Username, FirstName = DefaultAdmin.Username, Roles = DefaultAdmin.Roles, Permissions = DefaultAdmin.Permissions }; CreateUser(userRepo, user, DefaultAdmin.Password); }
// 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())); }