Beispiel #1
0
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                goto VALIDATION_ERROR;
            }

            var user = default(User);
            using (var db = new SecurityDbContext())
            {
                user = await db.Users.Where(u => u.LoginName == model.Name && u._Password == model.Password && !u._IsLocked).FirstOrDefaultAsync();
            }

            if (user == null)
            {
                goto LOGIN_ERROR;
            }

            var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString("D", CultureInfo.InvariantCulture)),
                    new Claim(ClaimTypes.Name, user.DisplayName),
                    new Claim(ClaimTypes.Role, user.Role.ToString()),
                    new Claim(CommonHelper.IdentityProviderClaimType, CommonHelper.IdentityProvider)
                },
                CommonHelper.DefaultAuthenticationType);
            this.AuthenticationManager.SignIn(identity);

            goto SUCCESS;

        VALIDATION_ERROR:

            if (this.Request.IsAjaxRequest())
            {
                return new HttpStatusCodeResult(HttpStatusCode.PreconditionFailed);
            }

            return this.View(model);

        LOGIN_ERROR:

            if (this.Request.IsAjaxRequest())
            {
                return new HttpStatusCodeResult(HttpStatusCode.PreconditionFailed);
            }

            this.ModelState.AddModelError(default(string), default(string));
            return this.View(model);

        SUCCESS:

            if (this.Request.IsAjaxRequest())
            {
                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }

            return this.RedirectToLocal();
        }
		public SecurityHelper() {
			if (_db == null) {
				_db = SecurityDbContext.Create();
			}

			//var provider = new DpapiDataProtectionProvider("CarrotCake CMS");

			//this.UserToken = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("UserToken")) {
			//	TokenLifespan = TimeSpan.FromDays(7)
			//};
		}
        public void TestInitialize()
        {
            TestCleanup();

            using (var db = new SecurityDbContext())
            {
                for (int i = 0; i < 108; i++)
                {
                    var user = new User()
                    {
                        Role = GenerateEnumValue<Role>(),
                        LoginName = string.Format("login-name-{0}", i + 1),
                        DisplayName = string.Format("display-name-{0}", i + 1),
                        _Password = string.Format("password-{0}", i + 1),
                        _IsLocked = (i % 3 == 0),
                        _LockDateTimeUtc = DateTimeOffset.UtcNow
                    };
                    FillEntityCommonValues(user, DateTimeOffset.UtcNow);

                    db.Users.Add(user);
                }

                db.SaveChanges();
            }
        }
        public static Task <ApplicationUser> CheckEncryptedKeys(this ApplicationUser user, SecurityDbContext applicationDbContext)
        {
            try
            {
                bool generated = false;

                if (user.EncryptionIv == null || user.EncryptionIv.Length < 1)
                {
                    generated         = true;
                    user.EncryptionIv = KeyGenerator.GetRandomData(128);
                }

                if (user.EncryptionKey == null || user.EncryptionKey.Length < 1)
                {
                    generated          = true;
                    user.EncryptionKey = KeyGenerator.GetRandomData(256);
                }

                if (generated)
                {
                    applicationDbContext.Users.Update(user);
                }

                applicationDbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }

            return(Task.FromResult(user));
        }
        public void GetUsersServerPaging()
        {
            var tokens = ODataClientHelper.GetServerPaging(SecurityServiceRootUrl + "Users");
            var users = default(IList<User>);
            using (var db = new SecurityDbContext())
            {
                users = db.Users.Where(u => !u._IsLocked).ToArray();
            }

            CompareCollection(users, tokens, Compare);
        }
 private bool ApplicationRoleExists(string id)
 {
     db = Request.GetOwinContext().Get <SecurityDbContext>();
     return(db.ApplicationRoles.Count(e => e.Id == id) > 0);
 }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory, KnowledgeContext context, SecurityDbContext securityContext)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else if (env.IsStaging())
            {
                app.UseExceptionHandler(b =>
                {
                    b.Run(async ctx =>
                    {
                        ctx.Response.StatusCode = 500;
                        await ctx.Response.WriteAsync("An unexpected fault happend. Try again later.");
                    });
                });
            }

            ConfigureAutoMapper();

            app.UseStaticFiles();

            app.UseAuthentication();

            // This method need to be called after the initial migration is added and database updated.
            context.EnsureSeedData();

            app.UseSwagger();
            app.UseSwaggerUI(opt =>
            {
                opt.SwaggerEndpoint("/swagger/v1/swagger.json", "PaceTime.API Swagger Document Endpoint");
            });

            app.UseMvc();
        }
 public UserRepository(SecurityDbContext dbContext)
 {
     _dbContext = dbContext;
 }
 public LoginValidator(object instance, SecurityDbContext context) : base(instance, context)
 {
 }
        public async Task <IHttpActionResult> Search(EmployeeRequestModel request)
        {
            db      = Request.GetOwinContext().Get <SecurityDbContext>();
            manager = Request.GetOwinContext().Get <ApplicationUserManager>();
            var id = User.Identity.GetUserId();

            me = manager.FindById(id);

            try
            {
                IdentityRole role  = null;
                var          users =
                    db.Users.AsQueryable().Where(x => x.ShopId == me.ShopId);

                if (!string.IsNullOrWhiteSpace(request.Role))
                {
                    role = db.Roles.FirstOrDefault(x => x.Name == request.Role);
                    if (role != null)
                    {
                        users = users.Where(x => x.Roles.Any(y => y.RoleId == role.Id));
                    }
                }

                // apply the filters here
                if (!string.IsNullOrWhiteSpace(request.Keyword))
                {
                    request.Keyword = request.Keyword.ToLower();
                    users           = users.Where(
                        x => x.FirstName.ToLower().Contains(request.Keyword) ||
                        x.LastName.ToLower().Contains(request.Keyword) ||
                        x.PhoneNumber.ToLower().Contains(request.Keyword));
                }

                users = users.OrderBy(x => x.FirstName);
                var content = await users.Select(x => new AppUserViewModel
                {
                    FirstName = x.FirstName ?? String.Empty,
                    LastName  = x.LastName ?? String.Empty,
                    UserName  = x.UserName,
                    Email     = x.Email,
                    // RoleId = x.Roles.First().RoleId,
                    // RoleName = roles[x.Roles.First().RoleId],
                    PhoneNumber = x.PhoneNumber,
                    IsActive    = x.IsActive,
                    Id          = x.Id,
                    ShopId      = x.ShopId
                }).ToListAsync();

                Tuple <List <AppUserViewModel>, int> result = new Tuple <List <AppUserViewModel>, int>(content, content.Count);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);
                response.Headers.Add("Count", content.Count.ToString());

                return(ResponseMessage(response));
            }
            catch (Exception exception)
            {
                Logger.Fatal(exception,
                             "Exception occurred while Searching EmployeeQueryControllerwith Request {Request}", request);
                return(InternalServerError(exception));
            }
        }
Beispiel #11
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion

            Func<IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType<IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance<Func<IPlatformRepository>>(platformRepositoryFactory);
            var moduleCatalog = container.Resolve<IModuleCatalog>();
            var manifestProvider = container.Resolve<IModuleManifestProvider>();

            #region Caching

            var cacheProvider = new HttpCacheProvider();
            var cacheSettings = new[]
            {
                new CacheSettings(CacheGroups.Settings, TimeSpan.FromDays(1)),
                new CacheSettings(CacheGroups.Security, TimeSpan.FromMinutes(1)),
            };

            var cacheManager = new CacheManager(cacheProvider, cacheSettings);
            container.RegisterInstance<CacheManager>(cacheManager);

            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType = ModuleSetting.TypeInteger,
                                    Title = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance<ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType<IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();
            var notifier = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance<IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance<INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance<INotificationManager>(notificationManager);
            container.RegisterInstance<INotificationTemplateResolver>(resolver);
            container.RegisterInstance<IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance<ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);


            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var fileSystemBlobProvider = new FileSystemBlobProvider(assetsConnectionString);

                    container.RegisterInstance<IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance<IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance<IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance<IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var packagesPath = HostingEnvironment.MapPath("~/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance<IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath("~/App_Data/Uploads");
            container.RegisterType<ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance<IChangeLogService>(changeLogService);

            #endregion

            #region Security

            var permissionService = new PermissionService(platformRepositoryFactory, manifestProvider, cacheManager);
            container.RegisterInstance<IPermissionService>(permissionService);

            container.RegisterType<IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance<IApiAccountProvider>(apiAccountProvider);

            container.RegisterType<IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType<SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType<IUserStore<ApplicationUser>, ApplicationUserStore>();
            container.RegisterType<IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType<ApplicationUserManager>();
            container.RegisterType<ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance<ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType<ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType<IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
Beispiel #12
0
        private static void InitializePlatform(IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance <Func <IPlatformRepository> >(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching

            var cacheProvider = new HttpCacheProvider();
            var cacheSettings = new[]
            {
                new CacheSettings(CacheGroups.Settings, TimeSpan.FromDays(1)),
                new CacheSettings(CacheGroups.Security, TimeSpan.FromMinutes(1)),
            };

            var cacheManager = new CacheManager(cacheProvider, cacheSettings);
            container.RegisterInstance <CacheManager>(cacheManager);

            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryNotifierImpl(hubSignalR);
            container.RegisterInstance <INotifier>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager         = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            container.RegisterInstance <INotificationTemplateResolver>(resolver);
            container.RegisterInstance <IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            //notificationManager.RegisterNotificationType(
            //	() => new RegistrationSmsNotification(defaultSmsNotificationSendingGateway)
            //	{
            //		DisplayName = "Registration notification",
            //		Description = "This notification sends by sms to client when he finish registration",
            //		ObjectId = "Platform",
            //		NotificationTemplate = new NotificationTemplate
            //		{
            //			Body = @"Dear {{ context.first_name }} {{ context.last_name }}, you has registered on our site. Your login  - {{ context.login }} Your login - {{ context.password }}",
            //			Subject = @"",
            //			NotificationTypeId = "RegistrationSmsNotification",
            //			ObjectId = "Platform"
            //		}
            //	}
            //);

            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties             = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider               = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var fileSystemBlobProvider = new FileSystemBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var sourcePath   = HostingEnvironment.MapPath("~/App_Data/SourcePackages");
            var packagesPath = HostingEnvironment.MapPath("~/App_Data/InstalledPackages");

            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath, sourcePath);
            container.RegisterInstance <IPackageService>(packageService);
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, sourcePath));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security

            var permissionService = new PermissionService(platformRepositoryFactory, manifestProvider, cacheManager);
            container.RegisterInstance <IPermissionService>(permissionService);

            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterType <ApplicationSignInManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Get <ApplicationSignInManager>()));
            container.RegisterType <ApplicationUserManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>()));
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

            var nonEditableUsers = GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
 public static string GetLastForgotPassCode(string userName)
 {
     using (SecurityDbContext securityDbContext = new SecurityDbContext())
         return(securityDbContext.ForgotPasswordEntities.Where <ForgotPasswordEntity>((Expression <Func <ForgotPasswordEntity, bool> >)(fpe => fpe.UserName == userName && fpe.IsActive)).OrderByDescending <ForgotPasswordEntity, int>((Expression <Func <ForgotPasswordEntity, int> >)(fpe => fpe.ID)).Select <ForgotPasswordEntity, string>((Expression <Func <ForgotPasswordEntity, string> >)(fpe => fpe.Code)).FirstOrDefault <string>());
 }
Beispiel #14
0
 public UsuariosRepository(SecurityDbContext context) : base(context)
 {
 }
Beispiel #15
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                .WithUpdateMode(CacheUpdateMode.Up)
                .WithSystemRuntimeCacheHandle("memCacheHandle")
                .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance <ICacheManager <object> >(cacheManager);
            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SmtpClient",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server host",
                                    Description = "Smtp server host"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Smtp server port",
                                    Description = "Smtp server port"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server login",
                                    Description = "Smtp server login"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server password",
                                    Description = "Smtp server password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Security",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                    ValueType    = ModuleSetting.TypeString,
                                    Title        = "Account types",
                                    Description  = "Dictionary for possible account types",
                                    IsArray      = true,
                                    ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                    DefaultValue = AccountType.Manager.ToString()
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager         = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            //var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);
            var emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            container.RegisterInstance <INotificationTemplateResolver>(resolver);
            container.RegisterInstance <IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);


            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties             = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider               = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var storagePath            = HostingEnvironment.MapPath(properties["rootPath"]);
                    var publicUrl              = properties["publicUrl"];
                    var fileSystemBlobProvider = new FileSystemBlobProvider(storagePath, publicUrl);

                    container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var packagesPath   = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance <IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Uploads");
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
Beispiel #16
0
        public void WriteObjects(TestType testType)
        {
            int         count1 = 100;
            int         count2 = 10;
            List <long> times  = new List <long>();
            List <Func <IDbContextConnectionClass> > contexts = PerformanceTestsHelper.GetCollectionContextCreators();

            foreach (Func <IDbContextConnectionClass> createContext in contexts)
            {
                using (IDisposable disposableContextInterface = (IDisposable)createContext()) {
                    IDbContextConnectionClass contextInterface = (IDbContextConnectionClass)disposableContextInterface;
                    DbContext context = (DbContext)contextInterface;
                    context.ResetDatabase();

                    for (int companyIndex = 0; companyIndex < count1; companyIndex++)
                    {
                        string companySuffix = companyIndex.ToString();

                        Company company = new Company();
                        company.CompanyName = companySuffix;
                        company.Description = "Description" + companySuffix;

                        for (int officeIndex = 0; officeIndex < count2; officeIndex++)
                        {
                            string officeSuffix = officeIndex.ToString();
                            Office office       = new Office();
                            office.Name        = officeSuffix;
                            office.Description = "Description" + companySuffix;

                            company.Offices.Add(office);
                        }

                        contextInterface.Company.Add(company);
                    }
                    context.SaveChanges();
                }

                using (IDisposable disposableContextInterface = (IDisposable)createContext()) {
                    IDbContextConnectionClass contextInterface = (IDbContextConnectionClass)disposableContextInterface;
                    DbContext context = (DbContext)contextInterface;

                    if (testType == TestType.WithOnePermission)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddOneCollectionPermission(securityDbContext, SecurityOperation.Delete);
                        }
                    }

                    if (testType == TestType.WithMultiplePermissions)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddMultipleCollectionPermissions(securityDbContext, SecurityOperation.Delete);
                        }
                    }

                    List <Company> objects = contextInterface.Company.Select(obj => obj).Include(obj => obj.Offices).ToList();
                    Assert.AreEqual(count1, objects.Count);

                    Stopwatch watch = new Stopwatch();
                    watch.Start();

                    for (int companyIndex = 0; companyIndex < count1; companyIndex++)
                    {
                        Company company = objects[companyIndex];

                        for (int officeIndex = 0; officeIndex < count2 - 1; officeIndex += 2)
                        {
                            Office curOffice  = company.Offices[officeIndex];
                            Office nextOffice = company.Offices[officeIndex + 1];

                            company.Offices[officeIndex]     = nextOffice;
                            company.Offices[officeIndex + 1] = curOffice;
                        }
                    }

                    context.SaveChanges();

                    watch.Stop();
                    times.Add(watch.ElapsedMilliseconds);
                }
            }

            double securedContextTime = PerformanceTestsHelper.GetSecuredContextValue(times);
            double nativeContextTime  = PerformanceTestsHelper.GetNativeContextValue(times);

            double nominalTimeDifference = GetTimeDifference(testType);
            double timeDifference        = securedContextTime - nativeContextTime;

            Assert.IsTrue(timeDifference <= nominalTimeDifference, GetTimeDifferenceErrorString(timeDifference, nominalTimeDifference));
            Debug.WriteLine(GetDebugTimeString(securedContextTime, nativeContextTime));
        }
 private static void UpdateUser(Guid id)
 {
     using (var db = new SecurityDbContext())
     {
         var user = db.Users.Find(id);
         user.DisplayName += " changed";
         user.Modified = DateTimeOffset.UtcNow;
         user.ModifiedBy = "test";
         db.SaveChanges();
     }
 }
Beispiel #18
0
        /// <summary>
        /// Delete Object From AjaxJQuery
        /// </summary>
        /// <param name="id">PK Value</param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            DbContextTransaction Transaction = null;

            //DbContextTransaction SecurityTransaction = null;

            try
            {
                Empresa empresa = db.Empresas.Include(e => e.Sedes).Include(e => e.Peticións).Where(e => e.EmpresaID.Equals(id)).FirstOrDefault();
                if (empresa != null)
                {
                    if (empresa.Sedes != null && empresa.Sedes.Count > 0)
                    {
                        return(new JsonResult
                        {
                            Data = new { Message = "No es posible eliminar una empresa que tiene sedes asociadas.", Success = false },
                            ContentEncoding = System.Text.Encoding.UTF8,
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        });
                    }

                    if (empresa.Peticións != null && empresa.Peticións.Count > 0)
                    {
                        return(new JsonResult
                        {
                            Data = new { Message = "No es posible eliminar una empresa que tiene peticiones asociadas.", Success = false },
                            ContentEncoding = System.Text.Encoding.UTF8,
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        });
                    }

                    Transaction = db.Database.BeginTransaction();

                    SecurityDbContext dbSecurity = new SecurityDbContext();
                    //SecurityTransaction = dbSecurity.Database.BeginTransaction();

                    var UsersToDelete = dbSecurity.Users.Include(u => u.Groups).Where(u => u.EmpresaID == empresa.EmpresaID).ToList();
                    if (UsersToDelete != null && UsersToDelete.Count > 0)
                    {
                        for (int i = 0; i < UsersToDelete.Count; i++)
                        {
                            var ResultUsr = ApplicationUser.ClearUserGroups(UsersToDelete[i]);
                            if (!ResultUsr.Succeeded)
                            {
                                return(new JsonResult
                                {
                                    Data = new { Message = String.Join(", ", ResultUsr.Errors.Select(u => u.ToString())), Success = false },
                                    ContentEncoding = System.Text.Encoding.UTF8,
                                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                                });
                            }
                            else
                            {
                                //ApplicationUser editUserViewModel = dbSecurity.Users.Find(UsersToDelete[i].Id);
                                dbSecurity.Users.Remove(UsersToDelete[i]);
                            }
                        }

                        dbSecurity.SaveChanges();
                    }

                    db.Empresas.Remove(empresa);
                    db.SaveChanges();

                    Transaction.Commit();
                    //SecurityTransaction.Commit();
                }
                else
                {
                    return(new JsonResult
                    {
                        Data = new { Message = "No es posible identificar la empresa. Por favor, intente de nuevo.", Success = false },
                        ContentEncoding = System.Text.Encoding.UTF8,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    });
                }

                return(new JsonResult
                {
                    Data = new { Message = string.Empty, Success = true },
                    ContentEncoding = System.Text.Encoding.UTF8,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
            catch
            {
                if (Transaction != null)
                {
                    Transaction.Rollback();
                }

                //if (SecurityTransaction != null)
                //    SecurityTransaction.Rollback();

                //
                // Log Exception eX
                //

                return(new JsonResult
                {
                    Data = new { Message = "Error ejecutando la acción de eliminar. Por favor inténtelo de nuevo", Success = false },
                    ContentEncoding = System.Text.Encoding.UTF8,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
        }
Beispiel #19
0
 internal ExternalLoginRepository(SecurityDbContext context)
     : base(context)
 {
 }
Beispiel #20
0
		public BaseRepository(SecurityDbContext _context)
		{
			context = _context;
		}
Beispiel #21
0
 public SecurityDbService()
 {
     _context = new SecurityDbContext();
 }
 public EFUserRepository(DataDbContext dataCtx, SecurityDbContext securityCtx)
 {
     this.dataCtx     = dataCtx;
     this.securityCtx = securityCtx;
 }
Beispiel #23
0
 public UsersController(SecurityDbContext context, UserManager <ApplicationUser> userManager)
 {
     _context         = context;
     this.userManager = userManager;
 }
        public static async Task <object> GenerateJwt(ClaimsIdentity identity, IJwtFactory jwtFactory,
                                                      JwtIssuerOptions jwtOptions, ApplicationUser user, List <dynamic> roles,
                                                      JsonSerializerSettings serializerSettings, SecurityDbContext db)
        {
            // string roleId = identity.Claims.Single(c => c.Type == "roleId").Value;
            string id    = identity.Claims.Single(c => c.Type == "id").Value;
            var    name  = user.FirstName + " " + user.LastName;
            string token = await jwtFactory.GenerateEncodedToken(user.UserName, identity);

            //IQueryable<ApplicationPermission> permissions = db.Permissions.Where(x => x.RoleId == roleId && x.IsAllowed);
            //var resources =
            //    permissions.Select(x => new { name = x.Resource.Name, isAllowed = x.IsAllowed, isDisabled = x.IsDisabled })
            //        .ToList();
            // string allowedResources = JsonConvert.SerializeObject(resources);

            var response = new
            {
                id       = id,
                name     = name,
                userName = user.UserName,
                role     = user.RoleName,
                //roleId = roleId,
                //resources = allowedResources,
                access_token = token,
                expires_in   = (int)jwtOptions.ValidFor.TotalSeconds,
                token_type   = "bearer"
            };

            return(response);
        }
Beispiel #25
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                .WithUpdateMode(CacheUpdateMode.Up)
                .WithSystemRuntimeCacheHandle("memCacheHandle")
                .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "SendGrid UserName",
                                Description = "Your SendGrid account username"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid Password",
                                Description = "Your SendGrid account password"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }


            #endregion

            #region Modularity

            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, ConfigurationManager.AppSettings.GetValues("VirtoCommerce:ModulesDataSources"), container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
 public ApplicationUserTokensController(SecurityDbContext context, RedisService redisService)
 {
     _context          = context;
     this.redisService = redisService;
 }
Beispiel #27
0
 public ApplicationResourcesController(SecurityDbContext context)
 {
     _context = context;
 }
Beispiel #28
0
 public IdentityService(UserManager <IdentityUser> userManager, TokenValidationParameters tokenValidationParameters, SecurityDbContext context, RoleManager <IdentityRole> roleManager)
 {
     _userManager = userManager;
     _tokenValidationParameters = tokenValidationParameters;
     _context     = context;
     _roleManager = roleManager;
 }
Beispiel #29
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string connectionString, HangfireLauncher hangfireLauncher, string modulesPath, ModuleInitializerOptions moduleInitializerOptions)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionString))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            ICacheManager <object> cacheManager = null;

            //Try to load cache configuration from web.config first
            //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
            var cacheManagerSection = ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) as CacheManagerSection;
            if (cacheManagerSection != null && cacheManagerSection.CacheManagers.Any(p => p.Name.EqualsInvariant("platformCache")))
            {
                var configuration = ConfigurationBuilder.LoadConfiguration("platformCache");

                if (configuration != null)
                {
                    configuration.LoggerFactoryType          = typeof(CacheManagerLoggerFactory);
                    configuration.LoggerFactoryTypeArguments = new object[] { container.Resolve <ILog>() };
                    cacheManager = CacheFactory.FromConfiguration <object>(configuration);
                }
            }
            if (cacheManager == null)
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5));
                });
            }

            container.RegisterInstance(cacheManager);

            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.RegionalFormat",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Regional format",
                                Description  = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.TimeZone",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Time zone",
                                Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.ShowMeridian",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Meridian labels based on user preferences",
                                Description  = "When set to true (by default), system will display time in format like '12 hour format' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.UseTimeAgo",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Use time ago format when is possible",
                                Description  = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.FullDateThreshold",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Full date threshold",
                                Description = "Number of units after time ago format will be switched to full date format"
                            },
                            new ModuleSetting
                            {
                                Name          = "VirtoCommerce.Platform.UI.FullDateThresholdUnit",
                                ValueType     = ModuleSetting.TypeString,
                                Title         = "Full date threshold unit",
                                Description   = "Unit of full date threshold",
                                DefaultValue  = "Never",
                                AllowedValues = new[]
                                {
                                    "Never",
                                    "Seconds",
                                    "Minutes",
                                    "Hours",
                                    "Days",
                                    "Weeks",
                                    "Months",
                                    "Quarters",
                                    "Years"
                                }
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var redisConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"];

            // Redis
            if (redisConnectionString != null && !string.IsNullOrEmpty(redisConnectionString.ConnectionString))
            {
                // Cache
                RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString.ConnectionString));

                // SignalR
                // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues
                GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString.ConnectionString, "VirtoCommerce.Platform.SignalR"));
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();
            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration {
                EnableJavaScriptProxies = false
            };
            app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration);

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("AssetsConnectionString"));

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(pathMapper, blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString, blobConnectionString.CdnUrl);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }

            container.RegisterType <IAssetEntryService, AssetEntryService>(new ContainerControlledLifetimeManager());
            container.RegisterType <IAssetEntrySearchService, AssetEntryService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionString));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            container.RegisterType <IPasswordCheckService, PasswordCheckService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion

            #region Events
            var inProcessBus = new InProcessBus();
            container.RegisterInstance <IHandlerRegistrar>(inProcessBus);
            container.RegisterInstance <IEventPublisher>(inProcessBus);

            inProcessBus.RegisterHandler <UserChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserPasswordChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserResetPasswordEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            #endregion
        }
 public RolesRepository(SecurityDbContext context) : base(context)
 {
 }
        public void GetUsersFilterByRole()
        {
            var tokens = ODataClientHelper.GetServerPaging(SecurityServiceRootUrl + "Users?$filter=Role eq Home.Services.SecurityService.Role'Administrator'");
            var users = default(IList<User>);
            using (var db = new SecurityDbContext())
            {
                users = db.Users.Where(u => !u._IsLocked && u.Role == Role.Administrator).ToArray();
            }

            CompareCollection(users, tokens, Compare);
        }
Beispiel #32
0
 public UnitOfWork(SecurityDbContext context)
 {
     Context = context;
 }
 public void TestCleanup()
 {
     using (var db = new SecurityDbContext())
     {
         db.Database.ExecuteSqlCommand("DELETE tc_employee WHERE created_by <> N'system'");
         db.SaveChanges();
     }
 }
Beispiel #34
0
 internal RoleRepository(SecurityDbContext context)
     : base(context)
 {
 }
 private static User GetUser()
 {
     using (var db = new SecurityDbContext())
     {
         return db.Users.First(u => !u._IsLocked);
     }
 }
Beispiel #36
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType<ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType<IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve<AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func<IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve<AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType<IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve<IModuleCatalog>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                    .WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id = "VirtoCommerce.Platform",
                Version = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                ValueType = ModuleSetting.TypeString,
                                Title = "SendGrid UserName",
                                Description = "Your SendGrid account username"
                            },
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                ValueType = ModuleSetting.TypeSecureString,
                                Title = "SendGrid Password",
                                Description = "Your SendGrid account password"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType = ModuleSetting.TypeInteger,
                                Title = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType = ModuleSetting.TypeString,
                                Title = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType = ModuleSetting.TypeInteger,
                                Title = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType = ModuleSetting.TypeString,
                                Title = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType = ModuleSetting.TypeSecureString,
                                Title = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType = ModuleSetting.TypeBoolean,
                                Title = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType = ModuleSetting.TypeString,
                                Title = "Account types",
                                Description = "Dictionary for possible account types",
                                IsArray = true,
                                ArrayValues = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance<ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType<IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();
            var notifier = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance<IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance<INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance<INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance<INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance<ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance<IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance<IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance<IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance<IBlobUrlResolver>(azureBlobProvider);
            }

            #endregion

            #region Modularity

            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, ConfigurationManager.AppSettings.GetValues("VirtoCommerce:ModulesDataSources"), container.Resolve<ILog>());
            container.RegisterType<ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve<IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance<IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance<IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType<IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance<IApiAccountProvider>(apiAccountProvider);

            container.RegisterType<IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType<SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType<IUserStore<ApplicationUser>, ApplicationUserStore>();
            container.RegisterType<IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType<ApplicationUserManager>();
            container.RegisterType<ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance<ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType<ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType<IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType<IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
 public UserRepository(SecurityDbContext securityDbContext)
 {
     _securityDbContext = securityDbContext;
     _users             = _securityDbContext.Users;
 }
 public AccessControlService(SecurityDbContext securityDbContext)
 {
     _securityDbContext = securityDbContext;
 }
		public SecurityHelper(SecurityDbContext db)
			: this() {
			if (_db == null) {
				_db = db;
			}
		}
Beispiel #40
0
        public void DeleteObjects(TestType testType)
        {
            int         count1       = 100;
            int         count2       = 10;
            List <long> memoryUsages = new List <long>();
            List <Func <IDbContextConnectionClass> > contexts = PerformanceTestsHelper.GetMemoryTestsCollectionContextCreators();

            foreach (Func <IDbContextConnectionClass> createContext in contexts)
            {
                long initialUsedMemory = 0;
                long usedMemory        = 0;

                initialUsedMemory = PerformanceTestsHelper.GetCurrentUsedMemory();

                using (IDisposable disposableContextInterface = (IDisposable)createContext()) {
                    IDbContextConnectionClass contextInterface = (IDbContextConnectionClass)disposableContextInterface;
                    DbContext context = (DbContext)contextInterface;
                    context.ResetDatabase();

                    for (int companyIndex = 0; companyIndex < count1; companyIndex++)
                    {
                        string companySuffix = companyIndex.ToString();

                        Company company = new Company();
                        company.CompanyName = companySuffix;
                        company.Description = "Description" + companySuffix;

                        for (int officeIndex = 0; officeIndex < count2; officeIndex++)
                        {
                            string officeSuffix = officeIndex.ToString();
                            Office office       = new Office();
                            office.Name        = officeSuffix;
                            office.Description = "Description" + companySuffix;

                            company.Offices.Add(office);
                        }

                        contextInterface.Company.Add(company);
                    }
                    context.SaveChanges();
                }

                using (IDisposable disposableContextInterface = (IDisposable)createContext()) {
                    IDbContextConnectionClass contextInterface = (IDbContextConnectionClass)disposableContextInterface;
                    DbContext context = (DbContext)contextInterface;

                    if (testType == TestType.WithOnePermission)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddOneCollectionPermission(securityDbContext, SecurityOperation.Delete);
                        }
                    }

                    if (testType == TestType.WithMultiplePermissions)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddMultipleCollectionPermissions(securityDbContext, SecurityOperation.Delete);
                        }
                    }

                    List <Company> objects = contextInterface.Company.Select(obj => obj).Include(obj => obj.Offices).ToList();
                    Assert.AreEqual(count1, objects.Count);

                    for (int companyIndex = 1; companyIndex < count1; companyIndex++)
                    {
                        Company company = objects[companyIndex];

                        foreach (var office in company.Offices.Where(office => office.Id % 2 == 0).ToList())
                        {
                            company.Offices.Remove(office);
                        }
                    }

                    context.SaveChanges();
                }

                long beforeCollect = GC.GetTotalMemory(true);
                usedMemory = PerformanceTestsHelper.GetCurrentUsedMemory();

                memoryUsages.Add(usedMemory - initialUsedMemory);
            }

            double securedContextBytesGrow = PerformanceTestsHelper.GetSecuredContextValue(memoryUsages);
            double nativeContextBytesGrow  = PerformanceTestsHelper.GetNativeContextValue(memoryUsages);

            Assert.IsTrue(false, "our: " + securedContextBytesGrow.ToString() + " bytes, native: " + nativeContextBytesGrow.ToString() + " bytes");
        }
Beispiel #41
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion


            Func<IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType<IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve<IModuleCatalog>();
            var manifestProvider = container.Resolve<IModuleManifestProvider>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                    .WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance<ICacheManager<object>>(cacheManager);
            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType = ModuleSetting.TypeInteger,
                                    Title = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name = "Platform|Notifications|SmtpClient",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "Smtp server host",
                                    Description = "Smtp server host"
                                },
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                    ValueType = ModuleSetting.TypeInteger,
                                    Title = "Smtp server port",
                                    Description = "Smtp server port"
                                },
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "Smtp server login",
                                    Description = "Smtp server login"
                                },
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "Smtp server password",
                                    Description = "Smtp server password"
                                }
                            }
                        },

                         new ModuleSettingsGroup
                        {
                            Name = "Platform|Security",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name = "VirtoCommerce.Platform.Security.AccountTypes",
                                    ValueType = ModuleSetting.TypeString,
                                    Title = "Account types",
                                    Description = "Dictionary for possible account types",
                                    IsArray = true,
                                    ArrayValues = Enum.GetNames(typeof(AccountType)),
                                    DefaultValue = AccountType.Manager.ToString()
                                }
                            }
                        }
                      
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance<ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType<IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();
            var notifier = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance<IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            //var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);
            var emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance<INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance<INotificationManager>(notificationManager);
            container.RegisterInstance<INotificationTemplateResolver>(resolver);
            container.RegisterInstance<IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance<ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);


            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");
 
                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var storagePath = HostingEnvironment.MapPath(properties["rootPath"]);
                    var publicUrl = properties["publicUrl"];
                    var fileSystemBlobProvider = new FileSystemBlobProvider(storagePath, publicUrl);

                    container.RegisterInstance<IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance<IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance<IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance<IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var packagesPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance<IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Uploads");
            container.RegisterType<ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance<IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance<IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType<IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance<IApiAccountProvider>(apiAccountProvider);

            container.RegisterType<IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType<SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType<IUserStore<ApplicationUser>, ApplicationUserStore>();
            container.RegisterType<IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType<ApplicationUserManager>();
            container.RegisterType<ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance<ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType<ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType<IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
Beispiel #42
0
        public void ReadObjects(TestType testType)
        {
            int         count        = 100;
            List <long> memoryUsages = new List <long>();
            List <Func <IDbContextMultiClass> > contexts = PerformanceTestsHelper.GetMemoryTestsContextCreators();

            foreach (Func <IDbContextMultiClass> createContext in contexts)
            {
                long initialUsedMemory = 0;
                long usedMemory        = 0;

                initialUsedMemory = PerformanceTestsHelper.GetCurrentUsedMemory();

                using (IDisposable disposableInterface = (IDisposable)createContext()) {
                    IDbContextMultiClass contextInterface = (IDbContextMultiClass)disposableInterface;
                    DbContext            context          = (DbContext)contextInterface;
                    context.ResetDatabase();

                    for (int i = 0; i < count; i++)
                    {
                        DbContextObject1 obj = new DbContextObject1();
                        obj.Description = "Description " + i.ToString();
                        context.Add(obj);
                    }
                    context.SaveChanges();
                }

                using (IDisposable disposableInterface = (IDisposable)createContext()) {
                    IDbContextMultiClass contextInterface = (IDbContextMultiClass)disposableInterface;
                    DbContext            context          = (DbContext)contextInterface;

                    if (testType == TestType.WithOnePermission)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddOnePermission(securityDbContext, SecurityOperation.Read);
                        }
                    }

                    if (testType == TestType.WithMultiplePermissions)
                    {
                        SecurityDbContext securityDbContext = context as SecurityDbContext;
                        if (securityDbContext != null)
                        {
                            PerformanceTestsHelper.AddMultiplePermissions(securityDbContext, SecurityOperation.Read);
                        }
                    }

                    List <DbContextObject1> objects = contextInterface.dbContextDbSet1.Select(obj => obj).ToList();
                    Assert.AreEqual(count, objects.Count);
                }

                long beforeCollect = GC.GetTotalMemory(true);
                usedMemory = PerformanceTestsHelper.GetCurrentUsedMemory();

                memoryUsages.Add(usedMemory - initialUsedMemory);
            }

            double securedContextBytesGrow = PerformanceTestsHelper.GetSecuredContextValue(memoryUsages);
            double nativeContextBytesGrow  = PerformanceTestsHelper.GetNativeContextValue(memoryUsages);

            Assert.IsTrue(false, "our: " + securedContextBytesGrow.ToString() + " bytes, native: " + nativeContextBytesGrow.ToString() + " bytes");
        }