private void SetDefaultConfiguration(IConfigurationManager configurationManager)
        {
            int.TryParse(configurationManager.GetByKey("DefaultConfirmationTokenTimeSpanInHours"), out var confirmationTokenTimeSpan);

            var dataProtectionProvider = new MachineKeyProtectionProvider();

            UserTokenProvider = new DataProtectorTokenProvider <User, int>(dataProtectionProvider.Create("EmailConfirmation", "ConfirmationToken"))
            {
                TokenLifespan = TimeSpan.FromHours(confirmationTokenTimeSpan)
            };

            bool.TryParse(configurationManager.GetByKey("UserLockoutEnabledByDefault"), out var userLockoutEnabled);

            if (!userLockoutEnabled)
            {
                return;
            }
            int.TryParse(configurationManager.GetByKey("MaxFailedAccessAttemptsBeforeLockout"), out var maxFailedAccessAttempts);

            int.TryParse(configurationManager.GetByKey("DefaultAccountLockoutTimeSpanInHours"), out var accountLockoutTimeSpan);

            MaxFailedAccessAttemptsBeforeLockout = maxFailedAccessAttempts;
            UserLockoutEnabledByDefault          = true;
            DefaultAccountLockoutTimeSpan        = TimeSpan.FromHours(accountLockoutTimeSpan);
        }
        protected override void Initialize()
        {
            // http://stackoverflow.com/questions/23455579/generating-reset-password-token-does-not-work-in-azure-website/23661872#23661872
            Container.RegisterType<IUserTokenProvider<User, int>>(
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c =>
                {
                    var provider = new MachineKeyProtectionProvider(); // This may not be Azure compatible.
                    return new DataProtectorTokenProvider<User, int>(provider.Create("Identity Passwords"));
                })
            );

            Container.RegisterType<IUserStore<User, int>, AppUserStore>(new PerRequestLifetimeManager());
            Container.RegisterType<IRoleStore<Role, int>, AppRoleStore>(new PerRequestLifetimeManager());
            Container.RegisterType<SignInManager<User, int>, AppSignInManager>(new PerRequestLifetimeManager());
            Container.RegisterType<UserManager<User, int>, AppUserManager>(new PerRequestLifetimeManager());
            Container.RegisterType<RoleManager<Role, int>, AppRoleManager>(new PerRequestLifetimeManager());
            Container.RegisterType<IAuthenticationManager>(
                new PerRequestLifetimeManager(),
                new InjectionFactory(c =>
                {
                    return HttpContext.Current.GetOwinContext().Authentication;
                })
            );

            Container.RegisterType<PorpoiseBoardDbContext>(
                new PerRequestLifetimeManager(),
                new InjectionFactory(c =>
                {
                    return new PorpoiseBoardDbContext("DefaultConnectionString");
                })
            );
        }
示例#3
0
        public async Task <ActionResult> Reset(ResetViewModel model)
        {
            if (model.Email == "*****@*****.**")
            {
                ModelState.AddModelError("lName", "You are not allowed to change the password on the demo site");
                return(View(model));
            }

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("lName", "Last Name  not found");
                return(View(model));
            }

            var provider = new MachineKeyProtectionProvider();

            UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, Guid>(provider.Create("PasswordReset"));
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid email address.");
                return(View(model));
            }

            // todo: locked out & not active:
            //if (!user.LockoutEndDateUtc)
            //{
            //    ModelState.AddModelError("", "Invalid email address.");
            //    return View(model);
            //}

            var result = await UserManager.ResetPasswordAsync(user.Id, model.Token, model.Password);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", result.Errors.First());
                return(View(model));
            }

            var message = new MailMessage();

            message.To.Add(new MailAddress(user.Email));
            message.Subject = "Password Changed";
            message.Body    = user.FirstName + Environment.NewLine;
            message.Body   += Environment.NewLine;
            message.Body   += "Your password has been changed." + Environment.NewLine;

            Utilities.Email.SendMail(message, Settings);

            if (!user.EmailConfirmed)
            {
                user.EmailConfirmed = true;
            }
            await UserManager.UpdateAsync(user);

            return(RedirectToAction("Login", new { msg = "passwordchanged" }));
        }
示例#4
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options,
                                                    IOwinContext context)
        {
            ApplicationContext     db      = context.Get <ApplicationContext>();
            ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));

            manager.EmailService = new EmailService();
            var provider = new MachineKeyProtectionProvider();

            manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(
                provider.Create("ASP.NET Identity"));
            return(manager);
        }
示例#5
0
        public bool ChangePassword(string email, string UpdatedPassword)
        {
            /* var provider = new DpapiDataProtectionProvider("GotChamp");
             * _userManager.UserTokenProvider = new DataProtectorTokenProvider<Player>(provider.Create("TokenConfirmation"));
             */
            var provider = new MachineKeyProtectionProvider();

            _userManager.UserTokenProvider = new DataProtectorTokenProvider <Player>(provider.Create("ResetPasswordPurposes"));

            Player user = FindUser(email);

            var userToken = _userManager.GeneratePasswordResetToken(user.Id);

            var result = _userManager.ResetPassword(user.Id, userToken, UpdatedPassword);

            return(result.Succeeded);
        }
示例#6
0
        public AuthRepository(bool isTest)
        {
            _context     = new WebApiDbEntities();
            _userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_context));
            _roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(_context));
            _provider    = new MachineKeyProtectionProvider();
            _userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(_provider.Create("EmailConfirmation"));

            if (isTest)
            {
                _connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=DB_A15604_sportoweswiry;Integrated Security=True;";
            }
            else
            {
                _connectionString = @"Data Source=SQL5025.SmarterASP.NET;Initial Catalog=DB_A15604_sportoweswiry;User Id=DB_A15604_sportoweswiry_admin;Password=haslo123;";
            }
        }
示例#7
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //todo: html email
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid email address.");
                return(View(model));
            }

            // todo: locked out & not active:
            //if (!user.LockoutEndDateUtc)
            //{
            //    ModelState.AddModelError("", "Invalid email address.");
            //    return View(model);
            //}

            var provider = new MachineKeyProtectionProvider();

            UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, Guid>(provider.Create("PasswordReset"));
            var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

            var rootUrl = ConfigurationManager.AppSettings["RootUrl"];
            var message = new MailMessage();

            message.To.Add(new MailAddress(user.Email));
            message.Subject = "Password Reset";
            message.Body    = user.FirstName + Environment.NewLine;
            message.Body   += Environment.NewLine;
            message.Body   += "A password reset has been requested. Please use the link below to reset your password." + Environment.NewLine;
            message.Body   += Environment.NewLine;
            message.Body   += rootUrl + "reset?e=" + user.Email + "&t=" + HttpUtility.UrlEncode(resetToken) + Environment.NewLine;

            Email.SendMail(message, Settings);

            return(RedirectToAction("Login", new { msg = "tokensent" }));
        }
示例#8
0
        public ApplicationUserManager(IUserStore <ApplicationUser> store)
            : base(store)
        {
            var provider = new MachineKeyProtectionProvider();

            this.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("NET "));
            this.EmailService      = new EmailService();
            this.SmsService        = new SmsService();

            this.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is: {0}"
            });
            this.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "SecurityCode",
                BodyFormat = "Your security code is {0}"
            });
        }
        public async Task <IHttpActionResult> ForgotPassword(string email)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(email))
                {
                    return(Content(System.Net.HttpStatusCode.InternalServerError, "Please enter a valid email address"));
                }
                var user = await UserManager.FindByEmailAsync(email);

                if (user == null)
                {
                    return(Content(System.Net.HttpStatusCode.InternalServerError, "Sorry, we can't recognize that email."));
                }

                var provider = new MachineKeyProtectionProvider();
                UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("ForgotPassword"));

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                code = HttpUtility.UrlEncode(code);
                var    userId      = HttpUtility.UrlEncode(user.Id);
                var    callbackUrl = ConfigurationManager.AppSettings["AppUrl"] + "#/reset-password/" + userId + "/" + code;
                string to          = user.Email;//user.Email;
                string subject     = "Reset Account password for MAX";
                string body        = "Please reset your password by clicking here: <a href=" + callbackUrl + ">Reset Password</a>";
                string from        = "*****@*****.**";

                bool mailSent = new EmailController().SendEmail(from, "", to, subject, body);

                if (!mailSent)
                {
                    return(Content(System.Net.HttpStatusCode.InternalServerError, "Error occoured while sending mail please try again later!"));
                }
                return(Ok());
            }

            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(System.Net.HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        private void sendConfirmationEmail(User user)
        {
            var provider = new MachineKeyProtectionProvider();
            UserManager <User, int> um = new UserManager <User, int>(ur);

            um.UserTokenProvider = new DataProtectorTokenProvider <User, int>(provider.Create("EmailConfirmation"));
            um.EmailService      = new EmailService();
            TempData.Add("confirmEmail", "Le hemos enviado un correo electrónico para confirmar su cuenta, comprube la carpeta spam");

            if (Url != null)
            {
                var code = um.GenerateEmailConfirmationToken(user.U_id);

                var callbackUrl = Url.Action(
                    "ConfirmEmail", "Home",
                    new { userId = user.Id, code = code },
                    protocol: "http");
                um.SendEmail(user.Id,
                             "Confirma tu correo",
                             "Por favor confirme su correo haciendo click en este <a href=\""
                             + callbackUrl + "\">link</a>");
            }
        }
        public async Task <ActionResult> ConfirmEmail(int userId, string code)
        {
            if (userId == 0 || code == null)
            {
                TempData.Add("confirmEmail", "No se ha podido confirmar el email");
                return(View("Login"));
            }
            IdentityResult result;

            try
            {
                var provider = new MachineKeyProtectionProvider();
                UserManager <User, int> um = new UserManager <User, int>(ur);
                um.UserTokenProvider = new DataProtectorTokenProvider <User, int>(provider.Create("EmailConfirmation"));
                result = await um.ConfirmEmailAsync(userId, code);
            }
            catch (ArgumentNullException)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                TempData.Add("confirmEmail", "Usuario no encontrado");
                return(View("Login"));
            }
            catch (ArgumentException)
            {
                TempData.Add("confirmEmail", "El email ya ha sido validado anteriormente");
                return(View("Login"));
            }

            if (result.Succeeded)
            {
                TempData.Add("confirmEmail", "Se ha confirmado su email correctamente");
                return(View("Login"));
            }

            TempData.Add("confirmEmail", result);
            return(View("Login"));
        }
        public async Task <IHttpActionResult> SetPassword(SetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            model.Code   = HttpUtility.UrlDecode(model.Code);
            model.UserId = HttpUtility.UrlDecode(model.UserId);

            var provider = new MachineKeyProtectionProvider();

            UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("ForgotPassword"));
            var result = await UserManager.ResetPasswordAsync(model.UserId, model.Code, model.NewPassword);

            //IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static ContainerBuilder Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            // Register your Web API controllers.

            // builder.RegisterAssemblyTypes(typeof(ApiController).Assembly);

            //builder.RegisterControllers(typeof(ApiController).Assembly);

            builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);

            builder.Register(c => new NoisContext())
            .As <DbContext>().InstancePerDependency();
            #region cache

            builder.RegisterType <MemoryCacheManager>()
            .As <ICacheManager>().InstancePerDependency();

            #endregion
            #region logging

            builder.RegisterType <Log4NetService>()
            .As <INoisLoggingService>().InstancePerDependency();
            #endregion

            builder.RegisterType <SendgridEmailService>()
            .As <IEmailService>().InstancePerDependency();

            var dataProtectionProvider = new MachineKeyProtectionProvider();
            builder.Register <IDataProtectionProvider>(cc => dataProtectionProvider).InstancePerDependency();

            //business
            builder.RegisterType <YayYoApplicationService>()
            .As <IYayYoApplicationService>().InstancePerDependency();
            builder.RegisterType <SafetySettingService>()
            .As <ISafetySettingService>().InstancePerDependency();
            builder.RegisterType <ContactService>()
            .As <IContactService>().InstancePerDependency();
            builder.RegisterType <LogSosService>()
            .As <ILogSosService>().InstancePerDependency();
            builder.RegisterType <LogRideInformationService>()
            .As <ILogRideInformationService>().InstancePerDependency();
            builder.RegisterType <SosGeolocationService>()
            .As <ISosGeolocationService>().InstancePerDependency();
            builder.RegisterType <YayYoService>()
            .As <IYayYoService>().InstancePerDependency();
            builder.RegisterType <ScheduleTaskService>()
            .As <IScheduleTaskService>().InstancePerDependency();
            builder.RegisterType <TaskService>()
            .As <ITaskService>().InstancePerDependency();

            builder.RegisterType <ContactListService>()
            .As <IContactListService>().InstancePerDependency();

            builder.RegisterType <ExportExelService>()
            .As <IExportExel>().InstancePerDependency();
            builder.RegisterType <ExportPdfService>()
            .As <IExportPdf>().InstancePerDependency();


            //Twilio Service
            builder.RegisterType <TwilioService>()
            .As <ITwilioService>().InstancePerDependency();

            //register AzureBlobSavingService
            builder.RegisterType <AzureBlobSavingService>()
            .As <IMediaService>().InstancePerDependency();
            return(builder);
        }
示例#14
0
        public void Token()
        {
            var provider = new MachineKeyProtectionProvider();

            UserManager.UserTokenProvider = new DataProtectorTokenProvider <User>(provider.Create("ASP.NET Identity"));
        }