Ejemplo n.º 1
0
        private static Container GetInitializeContainer(IAppBuilder app)
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            container.RegisterPerWebRequest <AppUserManager>();
            container.RegisterPerWebRequest <AppSignInManager>();

            //TODO: Role Manager
            container.RegisterPerWebRequest <AppRoleManager>();
            container.RegisterPerWebRequest <IRoleStore <IdentityRole, string> >(
                () => new RoleStore <IdentityRole>(
                    container.GetInstance <AppDbContext>()));

            container.RegisterPerWebRequest <LunarSFXDbContext>();
            container.RegisterPerWebRequest <IAuthenticationManager>(() =>
                                                                     AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication);
            container.RegisterPerWebRequest <AppDbContext>(() =>
                                                           new AppDbContext("LunarSFXDbConnString"));
            container.RegisterPerWebRequest <IUserStore <AppUser> >(() =>
                                                                    new UserStore <AppUser>(container.GetInstance <AppDbContext>()));

            // Register your stuff here
            container.Register <IBlogRepository, EFBlogRepository>(Lifestyle.Scoped);

            container.RegisterInitializer <AppUserManager>(manager => InitializeUserManager(manager, app));

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();

            return(container);
        }
Ejemplo n.º 2
0
        private void RegisterOwinServices(IAppBuilder app, Container container)
        {
            app.Use(async(context, next) =>
            {
                CallContext.LogicalSetData("IOwinContext", context);
                await next();
            });

            container.RegisterSingleton(app);
            container.Register <ApplicationRoleManager>(Lifestyle.Scoped);
            container.Register <ApplicationUserManager>(Lifestyle.Scoped);
            container.Register(() => new ApplicationDbContext(null), Lifestyle.Scoped);
            container.Register <IUserStore <ApplicationUser> >(() =>
                                                               new UserStore <ApplicationUser>(
                                                                   container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);
            container.Register <SignInManager <ApplicationUser, string>, ApplicationSignInManager>(Lifestyle.Scoped);
            container.Register <IRoleStore <IdentityRole, string> >(() =>
                                                                    new RoleStore <IdentityRole>(
                                                                        container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);
            container.RegisterInitializer <ApplicationUserManager>(
                manager => InitializeUserManager(manager, app, container));
            container.Register(() => AdvancedExtensions.IsVerifying(container)
                ? new OwinContext(new Dictionary <string, object>()).Authentication
                : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
            container.RegisterSingleton <IWebContextProvider>(new WebContextProvider(container));
            container.RegisterSingleton(new ConcurrentDictionary <string, object>());
            app.CreatePerOwinContext(() => container.GetInstance <ApplicationRoleManager>());
            app.CreatePerOwinContext(() => container.GetInstance <ApplicationUserManager>());
            app.CreatePerOwinContext(() => container.GetInstance <SignInManager <ApplicationUser, string> >());
        }
Ejemplo n.º 3
0
        private static void InitializeContainer(Container container)
        {
            container.RegisterPerWebRequest <IVenueWatchRepository, VenueWatchRepository>();
            container.RegisterPerWebRequest <ICurrentUserRetriever, CurrentUserRetriever>();

            container.RegisterPerWebRequest <IViagogoClient>(() =>
            {
                var client = new ViagogoClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               new ProductHeaderValue("VenueWatch"));
                if (!AdvancedExtensions.IsVerifying(container))
                {
                    // Its a shame to make it synchronous, but future plans will be to use another way of setting the token
                    // so that we don't have to do this.
                    var token = client.OAuth2.GetClientAccessTokenAsync(new[] { "read:user" }).Result;
                    client.TokenStore.SetTokenAsync(token);
                }
                return(client);
            });
            container.RegisterPerWebRequest <ApplicationUserManager>(() => new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext())));
            container.RegisterPerWebRequest <IAuthenticationManager>(() =>
                                                                     AdvancedExtensions.IsVerifying(container)
                        ? new OwinContext(new Dictionary <string, object>()).Authentication
                        : HttpContext.Current.GetOwinContext().Authentication);
        }
Ejemplo n.º 4
0
        public static Container GetInitializeContainer(IAppBuilder app)
        {
            var container = new Container();

            // Set the scoped lifestyle one directly after creating the container
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            container.RegisterSingleton <IAppBuilder>(app);

            container.Register <IAuthenticationManager>(() =>
                                                        AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);

            container.Register <SignInManager <ApplicationUser, string>, ApplicationSignInManager>(Lifestyle.Scoped);

            container.Register <ApplicationUserManager>(Lifestyle.Scoped);

            container.Register <ApplicationDbContext>(() => new ApplicationDbContext(), Lifestyle.Scoped);

            container.Register <IUserStore <ApplicationUser> >(() =>
                                                               new UserStore <ApplicationUser>(container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);

            container.Register <IUserService, EfUserService>(Lifestyle.Scoped);

            container.RegisterInitializer <ApplicationUserManager>(
                manager => InitializeUserManager(manager, app));

            container.RegisterMvcControllers(
                Assembly.GetExecutingAssembly());

            return(container);
        }
Ejemplo n.º 5
0
        public static Container GetInitializeContainer(IAppBuilder app)
        {
            var container = new Container();

            // Set the scoped lifestyle one directly after creating the container
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            container.RegisterSingleton <IAppBuilder>(app);

            container.Register <IAuthenticationManager>(() =>
                                                        AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);

            container.Register <SignInManager <ApplicationUser, string>, ApplicationSignInManager>(Lifestyle.Scoped);

            container.Register <ApplicationUserManager>(Lifestyle.Scoped);

            container.Register <ApplicationRoleManager>(Lifestyle.Scoped);

            container.Register <ApplicationDbContext>(() => new ApplicationDbContext(), Lifestyle.Scoped);

            container.Register <IUserStore <ApplicationUser> >(() =>
                                                               new UserStore <ApplicationUser>(container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);

            container.Register <IRoleStore <IdentityRole, string> >(() =>
                                                                    new RoleStore <IdentityRole>(container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);

            container.Register <IFileService, EfFileService>(Lifestyle.Scoped);

            container.Register <ICountryService, EfCountryService>(Lifestyle.Scoped);

            container.Register <IProcessTypeService, EfProcessTypeService>(Lifestyle.Scoped);

            container.Register <IProcessService, EfProcessService>(Lifestyle.Scoped);

            container.Register <ITeamService, EfTeamService>(Lifestyle.Scoped);

            container.Register(() => new ApplicationSettings()
            {
                FilesBasePath = ConfigurationManager.AppSettings["fileBasePath"].TrimEnd('\\') + '\\'
            }, Lifestyle.Scoped);

            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfiles(Assembly.GetAssembly(typeof(UserMappingProfile)));
            });

            container.RegisterSingleton(typeof(IMapper), mapperConfiguration.CreateMapper());

            container.RegisterInitializer <ApplicationUserManager>(
                manager => InitializeUserManager(manager, app));

            container.RegisterMvcControllers(
                Assembly.GetExecutingAssembly());

            return(container);
        }
Ejemplo n.º 6
0
        private static void InitializeContainer(Container container)
        {
            DI.Configure(container);

            container.RegisterPerWebRequest(
                () => new UserManager <ApplicationUser, string>(new UserStore <ApplicationUser>(DI.Resolve <EntityFrameworkDbContext>())));

            container.Register(() => AdvancedExtensions.IsVerifying(container)
                ? new OwinContext(new Dictionary <string, object>()).Authentication
                : HttpContext.Current.GetOwinContext().Authentication);
        }
Ejemplo n.º 7
0
 private static void InitializeContainer(Container container)
 {
     container.RegisterPerWebRequest <IUserStore <Usuario>, UserStore>();
     container.RegisterPerWebRequest <IRoleStore <IdentityRole, string>, RoleStore>();
     container.RegisterPerWebRequest <IdentityDbContext <Usuario>, DBContextUsuario>();
     container.RegisterPerWebRequest <IUserManager, UserManager>();
     container.RegisterPerWebRequest <IRoleManager, RoleManager>();
     container.RegisterPerWebRequest <IServicoUsuario, ServicoUsuario>();
     container.RegisterPerWebRequest <IAuthenticationManager>(() =>
                                                              AdvancedExtensions.IsVerifying(container) ?
                                                              new Microsoft.Owin.OwinContext(new Dictionary <string, object>()).Authentication :
                                                              HttpContext.Current.GetOwinContext().Authentication);
 }
Ejemplo n.º 8
0
        private static void InitializeContainer(Container container)
        {
            BootStrapperApplication.RegisterServices(container);
            BootStrapperDomain.RegisterServices(container);
            BootStrapperInfra.RegisterServices(container);

            container.Register <IUserStore <ApplicationUser> >(() => new UserStore <ApplicationUser>(new ApplicationDbContext()), Lifestyle.Scoped);
            container.Register <IRoleStore <IdentityRole, string> >(() => new RoleStore <IdentityRole>(), Lifestyle.Scoped);
            container.Register <IAuthenticationManager>(() => AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);

            container.Register <ApplicationUserManager>(Lifestyle.Scoped);
            container.Register <ApplicationSignInManager>(Lifestyle.Scoped);
        }
Ejemplo n.º 9
0
        public static void RegisterDependencyInjection()
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            //Asp.Net Identity
            container.Register <IdentitySignInManager>(Lifestyle.Scoped);
            container.Register <IdentityUserManager>(Lifestyle.Scoped);
            container.Register <IdentityRoleManager>(Lifestyle.Scoped);
            container.Register <IIdentitySmsService, SmsService>(Lifestyle.Scoped);

            //Asp.Net Identity internal dependencies
            container.Register(() =>
                               AdvancedExtensions.IsVerifying(container)
                ? new OwinContext(new Dictionary <string, object>()).Authentication
                : HttpContext.Current.GetOwinContext().Authentication,
                               Lifestyle.Scoped);
            container.Register <IUserStore <User, int>, UserStore>(Lifestyle.Scoped);
            container.Register <IRoleStore <Role, int>, RoleStore>(Lifestyle.Scoped);

            //This is how dependency injection is setup when multiple interfaces are inhereted by the same class.
            var emailServiceRegistration = Lifestyle.Scoped.CreateRegistration(typeof(EmailService), container);

            container.AddRegistration(typeof(IIdentityEmailService), emailServiceRegistration);
            container.AddRegistration(typeof(IEmailService), emailServiceRegistration);

            //DataContext
            var dataContextRegistration = Lifestyle.Scoped.CreateRegistration(typeof(DataContext), container);

            container.AddRegistration(typeof(DataContext), dataContextRegistration);
            container.AddRegistration(typeof(IDataContext), dataContextRegistration);

            RegisterServices(container);
            RegisterAutomapper(container);

            //AutoMapper Resolvers
            container.Register <UserRoleListToStringResolver>(Lifestyle.Scoped);

            //Integrated
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
        /// <summary>
        /// Initialize can configure main container types.
        /// </summary>
        private void ConfigureContainerAndRegisterTypes(WebUIConfigs uiConfigs, IAppBuilder appBuilder, Container container, IEnumerable <Assembly> assemblies)
        {
            container.Options.DefaultLifestyle          = new WebRequestLifestyle();
            container.Options.DefaultScopedLifestyle    = new WebRequestLifestyle();
            container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();

            // Register all web platform commont types
            DependencyInjectionInitializer.RegisterWebPlatformCommonTypes(uiConfigs, appBuilder, container, assemblies);

            // Register all optimization bundles
            container.RegisterCollection <Bundle>(assemblies);

            // MVC IFilterProvider attributes
            container.RegisterMvcIntegratedFilterProvider();

            // MVC controllers
            container.RegisterMvcControllers();

            // OAuth user sign in manager
            container.Register <DotUserSignInManager>();

            // IAuthenticationManager
            container.Register(() =>
            {
                // If testing (container.Verify()) or no context available, return a dummy instance
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(new OwinContext().Authentication);
                }

                // Otherwise return current authentication manager instance
                return(HttpContext.Current.GetOwinContext().Authentication);
            });

            // IWebContext
            container.Register <IWebContext>(() =>
            {
                // If testing (container.Verify()) or no context available, return a dummy instance
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(new WebUIContext());
                }

                // Otherwise return current user web context.
                return(new WebUIContext(new CorePrincipal(HttpContext.Current.User)));
            });
        }
Ejemplo n.º 11
0
        private static void InitializeContainer(Container container)
        {
            //For web api
            container.Register <TriviaContext>(Lifestyle.Scoped);

            //For web mvc
            container.Register <ApplicationUserManager>(Lifestyle.Scoped);
            container.Register <ApplicationSignInManager>(Lifestyle.Scoped);
            container.Register <ApplicationDbContext>(Lifestyle.Scoped);
            container.Register <IdentityFactoryOptions <ApplicationUserManager> >(Lifestyle.Scoped);
            container.Register <IUserStore <ApplicationUser> >(() => new UserStore <ApplicationUser>(container.GetInstance <ApplicationDbContext>()), Lifestyle.Scoped);

            container.Register <IAuthenticationManager>(() =>
                                                        AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
        }
Ejemplo n.º 12
0
        private static void InitializeContainer(Container container, IAppBuilder app)
        {
            // Singletons
            container.RegisterSingleton(app);

            // DB Contexts
            container.Register <ApplicationDbContext>(Lifestyle.Scoped);

            // Repositories
            //container.Register(typeof(IRepository<>), typeof(Repository<>));

            // Services
            container.Register <IMailService, MailService>();

            // ASP.NET Identity
            container.Register <ApplicationUserManager>();

            container.Register <IUserStore <ApplicationUser, int> >(() =>
                                                                    new UserStore <ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(container.GetInstance <ApplicationDbContext>()));

            container.RegisterInitializer <ApplicationUserManager>(
                manager => InitializeUserManager(manager, app));

            container.Register <ApplicationSignInManager>();

            container.Register(() =>
                               AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication);

            container.Register <ApplicationRoleManager>();

            container.Register <IRoleStore <ApplicationRole, int> >(() =>
                                                                    new RoleStore <ApplicationRole, int, ApplicationUserRole>(container.GetInstance <ApplicationDbContext>()));

            // For instance:
            // container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
        }
        public static Container GetInitializeContainer(IAppBuilder app)
        {
            var container = new Container();

            container.RegisterSingle(app);

            container.RegisterPerWebRequest <ApplicationUserManager>();

            container.RegisterPerWebRequest(
                () => new ApplicationDbContext("Foo"));


            container.RegisterPerWebRequest <IUserStore <ApplicationUser> >(
                () =>
                new UserStore <ApplicationUser>(
                    container.GetInstance <ApplicationDbContext>()));

            container.RegisterInitializer <ApplicationUserManager>(
                manager => InitializeUserManager(manager, app));

            container.RegisterPerWebRequest <SignInManager <ApplicationUser, string>, ApplicationSignInManager>();

            container.RegisterPerWebRequest <IAuthenticationManager>(
                () => AdvancedExtensions.IsVerifying(container)
                ? new OwinContext(new Dictionary <string, object>()).Authentication
                : HttpContext.Current.GetOwinContext().Authentication);

            container.RegisterPerWebRequest <ApplicationRoleManager>();

            container.RegisterPerWebRequest <IRoleStore <IdentityRole, string> >(
                () => new RoleStore <IdentityRole>(
                    container.GetInstance <ApplicationDbContext>()));

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            return(container);
        }
        public void Initialize(IAppBuilder appBuilder)
        {
            /*
             *
             * Globals
             *
             *********************************/

            //
            JsonConvert.DefaultSettings = () => new SharedJsonSettings();

            /*
             *
             * DI / IoC Registrar
             *
             *********************************/

            var container        = GetContiner();
            var domainAssemblies = GetKnownDomainAssemblies();

            //
            container.Register <AdminStore>();
            container.Register <AdminUserManager>();
            container.Register <AdminSignInManager>();
            container.Register(() => appBuilder.GetDataProtectionProvider());

            container.Register(() =>
            {
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(new OwinContext().Authentication);
                }

                return(HttpContext.Current.GetOwinContext().Authentication);
            });

            //
            var cloudName                  = AppSettings.Cloudinary.CloudName;
            var cloudApiKey                = AppSettings.Cloudinary.CloudApiKey;
            var cloudApiSecret             = AppSettings.Cloudinary.CloudApiSecret;
            var azureBlobsConnection       = AppSettings.Azure.BlobsConnection;
            var azureBlobsDefaultContainer = AppSettings.Azure.BlobsDefaultContainer;
            var fileSystemStorageFolder    = AppSettings.FileSystem.StorageFolder;
            var activeStorageService       = AppSettings.ActiveStorageService;

            var cloudinaryStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>(
                () => new CloudinaryStorageService(cloudName, cloudApiKey, cloudApiSecret), container);

            var azureBlobsStorage = Lifestyle.Singleton.CreateRegistration <IAzureStorageService>(
                () => new AzureStorageService(azureBlobsConnection, azureBlobsDefaultContainer), container);

            var fileSystemStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>(
                () => new FileSystemStorageService(fileSystemStorageFolder), container);

            container.RegisterConditional(typeof(IBlobStorageService), cloudinaryStorage, context => "cloudinary".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobStorageService), azureBlobsStorage, context => "azurestorage".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobStorageService), fileSystemStorage, context => !context.Handled);             // Defaults to filesystem

            var cloudinaryThumbService = Lifestyle.Singleton.CreateRegistration <ICloudinaryThumbService>(
                () => new CloudinaryThumbService(cloudName), container);

            var imageResizerThumbService = Lifestyle.Singleton.CreateRegistration <IImageResizerThumbService>(
                () => new ImageResizerThumbService(), container);

            container.RegisterConditional(typeof(IBlobThumbService), cloudinaryThumbService, context => "cloudinary".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobThumbService), imageResizerThumbService, context => !context.Handled);             // Defaults to image resizer

            //
            var connectionString = WebConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString;

            container.Register <IDbConnectionFactory>(() => new SqlConnectionFactory(connectionString));

            container.Register <IBlobsRepository, BlobsRepository>();
            container.Register <ILogsRepository, LogsRepository>();

            container.Register <IIdentityRepository, IdentityRepository>();
            container.Register <IUsersRepository, UsersRepository>();

            //
            var mailGunApiKey      = AppSettings.MailGun.ApiKey;
            var mailGunDomainName  = AppSettings.MailGun.DomainName;
            var defaultFromAddress = new MailAddress(
                AppSettings.Emails.DefaultEmailFromAddress,
                AppSettings.Emails.DefaultEmailFromDisplayName
                );
            var activeEmailDispatcherService = AppSettings.ActiveEmailDispatcherService;

            var mailGunDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <IMailGunApiEmailDispatcherService>(
                () => new MailGunApiEmailDispatcherService(mailGunApiKey, mailGunDomainName, defaultFromAddress), container);

            var netSmtpDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <ISystemNetSmtpEmailDispatcherService>(
                () => new SystemNetSmtpEmailDispatcherService(defaultFromAddress), container);

            container.RegisterConditional(typeof(IEmailDispatcherService), mailGunDispatcherService, context => "mailgun".Equals(activeEmailDispatcherService));
            container.RegisterConditional(typeof(IEmailDispatcherService), netSmtpDispatcherService, context => !context.Handled);             // Default

            //
            container.RegisterSingleton(() => new BlobServiceConfigs()
            {
                DefaultThumbBackgroundHexColor = AppSettings.Blobs.DefaultThumbBackgroundHexColor,
                DefaultThumbForegroundHexColor = AppSettings.Blobs.DefaultThumbForegroundHexColor
            });

            container.Register <IBlobService, BlobService>();
            container.Register <IGlobalizationService, GlobalizationService>();
            container.Register <IRealtimeService, RealtimeService>();

            //
            container.Register(typeof(IValidator <>), domainAssemblies);
            container.Register(() =>
            {
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(SharedContext.Null);
                }

                var currentPrincipal = new AdminPrincipal(HttpContext.Current.User);

                return(new SharedContext(
                           userId: currentPrincipal.Id
                           ));
            });

            //
            container.Register <IPasswordHasher, PasswordHasher>();

            //
            container.RegisterSingleton <ILogger>(() =>
            {
                var logger = new LoggerConfiguration();

                var loggerFilePath = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    AppSettings.Logger.StorageFolder.Trim('~').Trim('\\', '/').Replace("/", "\\"),
                    "log_.txt"
                    );

                logger = logger.Enrich.With <SerilogActivityIdEnricher>();

                logger = logger.WriteTo.Async((log) => log.File(
                                                  new SerilogTextFormatter(),
                                                  loggerFilePath,
                                                  rollingInterval: RollingInterval.Day,
                                                  shared: true
                                                  ));

                logger = logger.WriteTo.Async((log) => log.MSSqlServer(
                                                  connectionString,
                                                  tableName: "Logs",
                                                  autoCreateSqlTable: true
                                                  ));

                return(logger.CreateLogger());
            });

            //
            container.Register <DatabusHub>();

            //
            container.Verify();

            /*
             *
             * Init Functionalities
             *
             *********************************/

            //
            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                CookieName         = AppSettings.Auth.CookieName,
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(AppSettings.Auth.LogInPath),

                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <AdminUserManager, AdminUserEntity, int>(
                        validateInterval: TimeSpan.FromMinutes(0),
                        regenerateIdentityCallback: (manager, user) =>
                    {
                        var currentPricipal       = HttpContext.Current.User;
                        var currentAdminPrincipal = new AdminPrincipal(currentPricipal);

                        var currentIsPersistentState = currentAdminPrincipal.IsPersistent;
                        var currentScreenLockState   = currentAdminPrincipal.ScreenLocked;

                        return(user.GenerateUserIdentityAsync(
                                   manager,
                                   isPersistentState: currentIsPersistentState,
                                   screenLockedState: currentScreenLockState
                                   ));
                    },
                        getUserIdCallback: (user) =>
                    {
                        return(user.GetUserId <int>());
                    }
                        )
                }
            });

            //
            var imageResizerBlobsInfraPlugin = new ImageResizerThumbPlugin(
                blobService: container.GetInstance <IBlobStorageService>()
                );

            imageResizerBlobsInfraPlugin.Install(ImageResizer.Configuration.Config.Current);

            //
            ValidatorOptions.LanguageManager = new ValidationLanguageManager();

            FluentValidationModelValidatorProvider.Configure(config =>
            {
                config.ValidatorFactory = new SimpleInjectorValidatorFactory(container);
            });

            //
            DependencyResolver.SetResolver(
                new SimpleInjectorDependencyResolver(container)
                );

            //
            var serializer = JsonSerializer.Create(new SharedJsonSettings()
            {
                ContractResolver = new SignalRCamelCaseJsonResolver()
            });

            //
            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
            GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new UserIdProvider());
            GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => new HubsActivator());

            //
            appBuilder.MapSignalR();
        }
        private Container ConfigureDependencyInjectionContainer(IAppBuilder appBuilder)
        {
            var container        = GetContainer();
            var domainAssemblies = GetKnownDomainAssemblies();

            //
            container.Register <AppUserStore>();
            container.Register <AppUserManager>();
            container.Register <AppSignInManager>();
            container.Register(() => appBuilder.GetDataProtectionProvider());

            container.Register(() =>
            {
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(new OwinContext().Authentication);
                }

                return(HttpContext.Current.GetOwinContext().Authentication);
            });

            //
            var cloudName                  = AppSettings.Cloudinary.CloudName;
            var cloudApiKey                = AppSettings.Cloudinary.CloudApiKey;
            var cloudApiSecret             = AppSettings.Cloudinary.CloudApiSecret;
            var azureBlobsConnection       = AppSettings.Azure.BlobsConnection;
            var azureBlobsDefaultContainer = AppSettings.Azure.BlobsDefaultContainer;
            var fileSystemStorageFolder    = AppSettings.FileSystem.StorageFolder;
            var activeStorageService       = AppSettings.ActiveStorageService;

            var cloudinaryStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>(
                () => new CloudinaryStorageService(cloudName, cloudApiKey, cloudApiSecret), container);

            var azureBlobsStorage = Lifestyle.Singleton.CreateRegistration <IAzureStorageService>(
                () => new AzureStorageService(azureBlobsConnection, azureBlobsDefaultContainer), container);

            var fileSystemStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>(
                () => new FileSystemStorageService(fileSystemStorageFolder), container);

            container.RegisterConditional(typeof(IBlobStorageService), cloudinaryStorage, context => "cloudinary".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobStorageService), azureBlobsStorage, context => "azurestorage".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobStorageService), fileSystemStorage, context => !context.Handled);             // Defaults to filesystem

            var cloudinaryThumbService = Lifestyle.Singleton.CreateRegistration <ICloudinaryThumbService>(
                () => new CloudinaryThumbService(cloudName), container);

            var imageResizerThumbService = Lifestyle.Singleton.CreateRegistration <IImageResizerThumbService>(
                () => new ImageResizerThumbService(), container);

            container.RegisterConditional(typeof(IBlobThumbService), cloudinaryThumbService, context => "cloudinary".Equals(activeStorageService));
            container.RegisterConditional(typeof(IBlobThumbService), imageResizerThumbService, context => !context.Handled);             // Defaults to image resizer

            //
            var connectionString = WebConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString;

            container.Register <IDbConnectionFactory>(() => new SqlConnectionFactory(connectionString));

            container.Register <IBlobsRepository, BlobsRepository>();
            container.Register <ILogsRepository, LogsRepository>();

            container.Register <IIdentityRepository, IdentityRepository>();
            container.Register <IUsersRepository, UsersRepository>();

            //
            var mailGunApiKey      = AppSettings.MailGun.ApiKey;
            var mailGunDomainName  = AppSettings.MailGun.DomainName;
            var defaultFromAddress = new MailAddress(
                AppSettings.Emails.DefaultEmailFromAddress,
                AppSettings.Emails.DefaultEmailFromDisplayName
                );
            var activeEmailDispatcherService = AppSettings.ActiveEmailDispatcherService;

            var mailGunDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <IMailGunApiEmailDispatcherService>(
                () => new MailGunApiEmailDispatcherService(mailGunApiKey, mailGunDomainName, defaultFromAddress), container);

            var netSmtpDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <ISystemNetSmtpEmailDispatcherService>(
                () => new SystemNetSmtpEmailDispatcherService(defaultFromAddress), container);

            container.RegisterConditional(typeof(IEmailDispatcherService), mailGunDispatcherService, context => "mailgun".Equals(activeEmailDispatcherService));
            container.RegisterConditional(typeof(IEmailDispatcherService), netSmtpDispatcherService, context => !context.Handled);             // Default

            //
            container.RegisterSingleton(() => new BlobServiceConfigs()
            {
                DefaultThumbBackgroundHexColor = AppSettings.Blobs.DefaultThumbBackgroundHexColor,
                DefaultThumbForegroundHexColor = AppSettings.Blobs.DefaultThumbForegroundHexColor
            });

            container.Register <IBlobService, BlobService>();
            container.Register <IGlobalizationService, GlobalizationService>();
            container.Register <IRealtimeService, RealtimeService>();

            //
            container.Register(typeof(IValidator <>), domainAssemblies);
            container.Register <ISessionContext>(() =>
            {
                if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null)
                {
                    return(UserSessionContext.Null);
                }

                var currentPrincipal = new AppPrincipal(HttpContext.Current.User);

                return(new UserSessionContext(
                           userId: currentPrincipal.Id
                           ));
            });

            //
            container.Register <IPasswordHasher, PasswordHasher>();

            //
            container.RegisterSingleton <ILogger>(() =>
            {
                var logger = new LoggerConfiguration();

                var loggerFilePath = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    AppSettings.Logger.StorageFolder.Trim('~').Trim('\\', '/').Replace("/", "\\"),
                    "log_.txt"
                    );

                logger = logger.Enrich.With <SerilogActivityIdEnricher>();

                logger = logger.WriteTo.Async((log) => log.File(
                                                  new SerilogTextFormatter(),
                                                  loggerFilePath,
                                                  rollingInterval: RollingInterval.Day,
                                                  shared: true
                                                  ));

                logger = logger.WriteTo.Async((log) => log.MSSqlServer(
                                                  connectionString,
                                                  tableName: "Logs",
                                                  autoCreateSqlTable: true
                                                  ));

                return(logger.CreateLogger());
            });

            //
            container.Register <DatabusHub>();

            //
            container.Verify();

            return(container);
        }
Ejemplo n.º 16
0
        // Para obtener más información para configurar la autenticación, visite http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure el contexto de base de datos, el administrador de usuarios y el administrador de inicios de sesión para usar una única instancia por solicitud
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <UserManager>(UserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Permitir que la aplicación use una cookie para almacenar información para el usuario que inicia sesión
            // y una cookie para almacenar temporalmente información sobre un usuario que inicia sesión con un proveedor de inicio de sesión de terceros
            // Configurar cookie de inicio de sesión
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Permite a la aplicación validar la marca de seguridad cuando el usuario inicia sesión.
                    // Es una característica de seguridad que se usa cuando se cambia una contraseña o se agrega un inicio de sesión externo a la cuenta.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <UserManager, User>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Permite que la aplicación almacene temporalmente la información del usuario cuando se verifica el segundo factor en el proceso de autenticación de dos factores.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Permite que la aplicación recuerde el segundo factor de verificación de inicio de sesión, como el teléfono o correo electrónico.
            // Cuando selecciona esta opción, el segundo paso de la verificación del proceso de inicio de sesión se recordará en el dispositivo desde el que ha iniciado sesión.
            // Es similar a la opción Recordarme al iniciar sesión.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Quitar los comentarios de las siguientes líneas para habilitar el inicio de sesión con proveedores de inicio de sesión de terceros
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            // --  Container
            var container = new Container();

            // -- Register Services
            container.RegisterPerWebRequest(() => new ApplicationDbContext());
            container.RegisterPerWebRequest(() => AdvancedExtensions.IsVerifying(container) ? new OwinContext(new Dictionary <string, object>()).Authentication : HttpContext.Current.GetOwinContext().Authentication); container.Register <IJobService, JobService>();


            // -- Register in Conttroller and WebApi
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            // -- Verify
            container.Verify();

            // -- Inject Global
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }