private UserManager<User, int> InitUserManager(UserManager<User, int> manager)
 {
     manager.EmailService = new EmailService();
     manager.SmsService = new SmsService();
     var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Wishlist");
     manager.UserTokenProvider = new DataProtectorTokenProvider<User, int>(provider.Create("EmailConfirmation"));
     return manager;
 }
예제 #2
0
        private UserManager <User, int> InitUserManager(UserManager <User, int> manager)
        {
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Wishlist");

            manager.UserTokenProvider = new DataProtectorTokenProvider <User, int>(provider.Create("EmailConfirmation"));
            return(manager);
        }
        public AccountController(Helpers.MyUserManager userManager)
        {
            //Start of code by Tom
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("MyApp");

            userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>
                                                (provider.Create("EmailConfirmation"));
            //Emd of code added by Tom
            _userManager = userManager;
        }
        public AccountController(UserManager userManager, ApplicationSignInManager signInManager)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("One");

            userManager.UserTokenProvider = new DataProtectorTokenProvider <User>(provider.Create("EmailConfirmation"));
            UserManager = userManager;

            UserManager.UserValidator = new UserValidator <User>(UserManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            SignInManager = signInManager;
        }
예제 #5
0
        public ApplicationUserManager(IUserStore <ApplicationUser> store, IdentityFactoryOptions <ApplicationUserManager> options)
            : base(store)
        {
            // Configure validation logic for usernames
            UserValidator = new UserValidator <ApplicationUser>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            UserLockoutEnabledByDefault          = true;
            DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            EmailService = new EmailService();
            SmsService   = new SmsService();

            var dataProtectionProvider = options.DataProtectionProvider;

            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ASP.NET IDENTITY");

            UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"))
            {
                TokenLifespan = TimeSpan.FromHours(24),
            };
        }
예제 #6
0
        public UnitOfWork(string connectionString, IEmailConfiguration emailConfiguration)
        {
            Database      = new ApplicationContext(connectionString);
            roleManager   = new AppRoleManager(new CustomRoleStore(Database));
            clientManager = new ClientManager(Database);

            userManager = new AppUserManager(new CustomUserStore(Database));

            userManager.UserValidator = new UserValidator <AppUser, int>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false
            };

            userManager.RegisterTwoFactorProvider("PhoneCode",
                                                  new PhoneNumberTokenProvider <AppUser, int>
            {
                MessageFormat = "MVC forum security code is: {0}"
            });
            userManager.RegisterTwoFactorProvider("EmailCode",
                                                  new EmailTokenProvider <AppUser, int>
            {
                Subject    = "MVC Forum security code",
                BodyFormat = "MVC forum security code is: {0}"
            });
            userManager.EmailService = new IdentityEmailService(emailConfiguration);
            Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider dataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("MVC Forum");

            userManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser, int>(
                dataProtectionProvider.Create("ASP.NET Identity"));
        }
        public async Task <ActionResult> ResetPassword(ForgotPasswordViewModel model)
        {
            if (model.userid == null || model.token == null)
            {
                return(View("Error"));
            }
            IdentityResult result;

            try
            {
                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("ForgotPassword"));
                result = await UserManager.ResetPasswordAsync(model.userid, model.token, model.NewPassword);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                ViewBag.errorMessage = ioe.Message;
                return(View("Error"));
            }

            if (result.Succeeded)
            {
                return(View());
            }

            // If we got this far, something failed.
            AddErrors(result);
            ViewBag.errorMessage = "ConfirmEmail failed";
            return(View("Error"));
        }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.UserName);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }
                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("ForgotPassword"));

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account",new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme);

                string body = "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>";
                SendEmailConfirmation(user.Email,"Forgot Password", body);
                
                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //Token Provider Registration.
                    //Here token name is "EmailConfirmation", and below we will create a EmailConfirmationToken against userId.
                    //Where we have to confirm the token, we have to invoke token provider to create token for "EmailConfirmation", then we will match that token and uerId.
                    var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                    UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));

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

                    var callbackUrl = Url.Action(
                        "ConfirmEmail", "Account",
                        new { userId = user.Id, code = code },
                        protocol: Request.Url.Scheme);
                    string body = "Please confirm your account by clicking this link: <a href=\'" + callbackUrl + "\'>link</a>";
                    SendEmailConfirmation(user.Email, "Email Confirmation", body);
                    //await UserManager.SendEmailAsync(user.Id,
                    //    "Confirm your account",
                    //    "Please confirm your account by clicking this link: <a href=\""
                    //    + callbackUrl + "\">link</a>");



                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #10
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/auth/login")
            });

            // configure the user manager
            UserManagerFactory = () =>
            {
                var usermanager = new UserManager <AppUser>(
                    new UserStore <AppUser>(new AppDbContext()));
                // allow alphanumeric characters in username
                usermanager.UserValidator = new UserValidator <AppUser>(usermanager)
                {
                    AllowOnlyAlphanumericUserNames = false
                };
                usermanager.ClaimsIdentityFactory = new AppUserClaimsIdentityFactory();

                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Booktrade");
                usermanager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <AppUser>(provider.Create("PasswordReset"));

                return(usermanager);
            };
            LuceneSearchIndexer.UpdateBooksIndex();
        }
예제 #11
0
        public static UserManager <ApplicationUser, int> Create(IdentityFactoryOptions <UserManager> options, IOwinContext context)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("CIPApplication");

            var userManager = new UserManager <ApplicationUser, int>(new CustomUserStore(context.Get <ApplicationDbContext>()));

            userManager.UserValidator = new UserValidator <ApplicationUser, int>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(provider.Create("CIPApplicationToken"));

            return(userManager);
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.UserName);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }
                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("ForgotPassword"));

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

                var callbackUrl = Url.Action("ResetPassword", "Account", new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme);

                string body = "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>";
                SendEmailConfirmation(user.Email, "Forgot Password", body);

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public AccountController(ApplicationUserManager userManager)
        {
            UserManager = userManager;
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");

            UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
        }
예제 #14
0
        public async Task <bool> EmailConfirmation(string userId, string token)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("YourAppName");

            database.UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
            var result = await database.UserManager.ConfirmEmailAsync(userId, token);

            return(result.Succeeded);
        }
예제 #15
0
        public static AppUserManager Create(ApplicationDbContext context)
        {
            var usermanager = new AppUserManager(new UserStore <AppUser>(context));
            var provider    = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("LicenseProtoType");

            usermanager.UserTokenProvider     = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <AppUser>(provider.Create("EmailConfirmation"));
            usermanager.EmailService          = new EmailService();
            usermanager.ClaimsIdentityFactory = new ClaimsIdentityFactory <AppUser>();
            return(usermanager);
        }
예제 #16
0
        public async Task <ActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(View("Error"));
            }

            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("HireThingsPortal");

            _userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <IHireThingsUser>(provider.Create("EmailConfirmation"))
            {
                //TokenLifespan = TimeSpan.FromMinutes(1)
            };

            var result = await _userManager.ConfirmEmailAsync(userId, code);

            return(View(result.Succeeded ? "ConfirmEmail" : "Error"));
        }
예제 #17
0
        public AppUserManager(IAppUserStore store)
            : base(store)
        {
            //No es posible asignar esto en el constructor, se evita la logica.

            //// Configure validation logic for usernames
            //manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            //{
            //    AllowOnlyAlphanumericUserNames = false,
            //    RequireUniqueEmail = true
            //};


            // Configure validation logic for passwords
            PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };

            // Configure user lockout defaults
            UserLockoutEnabledByDefault          = true;
            DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            MaxFailedAccessAttemptsBeforeLockout = 5;

            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("MDD");

            UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, Guid>(provider.Create("ASP.NET Identity"))
            {
                TokenLifespan = TimeSpan.FromHours(3)
            };
        }
        public async Task<ActionResult> ConfirmEmail(string userId, string code)
        {
            //if (userId == null || code == null)
            //{
            //    return View("Error");
            //}
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
            UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
            //var result = await UserManager.ConfirmEmailAsync(userId, code);
            //if (result.Succeeded)
            //{
            //    return View("ConfirmEmail");
            //}
            //AddErrors(result);
            //return View();
            if (userId == null || code == null)
            {
                return View("Error");
            }
            IdentityResult result;
            try
            {
                result = await UserManager.ConfirmEmailAsync(userId, code);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                ViewBag.errorMessage = ioe.Message;
                return View("Error");
            }

            if (result.Succeeded)
            {
                return View();
            }

            // If we got this far, something failed.
            AddErrors(result);
            ViewBag.errorMessage = "ConfirmEmail failed";
            return View("Error");
        }
예제 #19
0
        private async Task SendEmail(User user)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("EEP");

            _userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <User, Guid>(provider.Create("EmailConfirmation"));

            string code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = user.Id + code;

            await _userManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
        }
        public ApplicationUserManager(IUserStore <IdentityUser> store) : base(store)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Providers");

            UserTokenProvider = new DataProtectorTokenProvider <IdentityUser>(provider.Create("Reset Password"));
        }
        public async Task <ReturnData> ResetPassword(ResetPasswordViewModel model)
        {
            model.PhoneNumber = model.PhoneNumber.RemoveWhiteSpace();
            var user = await _userManager.FindByNameAsync(model.PhoneNumber);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(new ReturnData()
                {
                    State = false,
                    Data = " The user does not exist"
                });
            }

            if (!await _userManager.VerifyChangePhoneNumberTokenAsync(user.Id, model.Code, model.PhoneNumber))
            {
                return(new ReturnData()
                {
                    State = false,
                    Data = " invalid code resend again"
                });
            }
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("NasAPI"); _userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("PasswordReset"));
            var code     = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

            var result = await _userManager.ResetPasswordAsync(user.Id, code, model.Password);

            if (result.Succeeded)
            {
                if (!user.PhoneNumberConfirmed)
                {
                    user.PhoneNumberConfirmed = true;
                    await this._userManager.UpdateAsync(user);
                }
                return(new ReturnData()
                {
                    State = true,
                    Data = "Done"
                });
            }
            return(new ReturnData()
            {
                State = false,
                Data = "couldn't reset the password"
            });
        }
        public async Task<ActionResult> ResetPassword(ForgotPasswordViewModel model)
        {
            if (model.userid == null || model.token == null)
            {
                return View("Error");
            }
            IdentityResult result;
            try
            {
                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("ForgotPassword"));
                result = await UserManager.ResetPasswordAsync(model.userid, model.token, model.NewPassword);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                ViewBag.errorMessage = ioe.Message;
                return View("Error");
            }

            if (result.Succeeded)
            {
                return View();
            }

            // If we got this far, something failed.
            AddErrors(result);
            ViewBag.errorMessage = "ConfirmEmail failed";
            return View("Error");
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    //Token Provider Registration.
                    //Here token name is "EmailConfirmation", and below we will create a EmailConfirmationToken against userId.
                    //Where we have to confirm the token, we have to invoke token provider to create token for "EmailConfirmation", then we will match that token and uerId.
                    var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                    UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));

                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action(
                        "ConfirmEmail", "Account",
                        new { userId = user.Id, code = code },
                        protocol: Request.Url.Scheme);
                    string body = "Please confirm your account by clicking this link: <a href=\'" + callbackUrl + "\'>link</a>";
                    SendEmailConfirmation(user.Email,"Email Confirmation", body);
                    //await UserManager.SendEmailAsync(user.Id,
                    //    "Confirm your account",
                    //    "Please confirm your account by clicking this link: <a href=\""
                    //    + callbackUrl + "\">link</a>");

                    

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #24
0
        private AccountController(UserManager <IHireThingsUser> userManager)
        {
            _userManager = userManager;
            // Create user token provider
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("HireThingsPortal");

            _userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <IHireThingsUser>(provider.Create("EmailConfirmation"))
            {
                //TokenLifespan = TimeSpan.FromMinutes(1)
            };

            _userManager.UserValidator = new UserValidator <IHireThingsUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            _userManager.PasswordValidator = new PasswordValidator {
            };
        }
예제 #25
0
        public ActionResult UsersCreate(RegisterCustomerUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                CustomerUser user = (CustomerUser)model.GetUser();
                user.CustomerID      = model.CustomerID;
                user.UserName        = model.Email;
                user.FirstName       = model.FirstName;
                user.LastName        = model.LastName;
                user.IsCustomerAdmin = model.IsCustomerAdmin;
                user.JobPosition     = model.JobPosition;
                user.Initials        = model.Initials;
                try
                {
                    var result = userManager.Create(user, model.Password);

                    if (result.Succeeded)
                    {
                        //NO SE ESTA USANDO
                        //if (model.IsCustomerAdmin)
                        //{
                        //    userManager.AddToRole(user.Id, "CustomerAdminUser");
                        //}
                        //else
                        //{
                        //    userManager.AddToRole(user.Id, "CustomerUser");
                        //}

                        //Se crea el Usuario
                        userManager.AddToRole(user.Id, "CustomerUser");

                        //Se envian mail de Activacion
                        var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                        userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <CustomerUser>(provider.Create("EmailConfirmation"));
                        string code        = userManager.GenerateEmailConfirmationToken(user.Id);
                        var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        workflowMessageService.SendConfirmEmail(user.Email, "Confirme su cuenta de acceso", "Por favor confirme su cuenta haciendo click <a href=\"" + callbackUrl + "\">aqui</a>");

                        //Se asigna el Canal de Venta
                        AssignSalesChannel(user.Id, model.SalesChannelID);

                        //Se redireccion al Listado de Usuarios
                        return(RedirectToAction("Users", "Customer", new { id = model.CustomerID }));
                    }
                    else
                    {
                        var errors = string.Join(",", result.Errors);
                        ModelState.AddModelError(string.Empty, errors);
                    }
                }
                catch (DbEntityValidationException e)
                {
                    var errors = string.Join("; ", e.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
                    ModelState.AddModelError(string.Empty, errors);
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #26
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            IAccountService service = new AccountService();

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.EmailId);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                if (!(service.VerifySecurityAnswer(model.UserId, model.Answer)))
                {
                    return(View("SecurityInfoError"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // Create user token provider
                var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("HireThingsPortal");
                _userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <IHireThingsUser>(provider.Create("EmailConfirmation"))
                {
                    TokenLifespan = TimeSpan.FromMinutes(1)
                };

                string code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                await _userManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                long userId = Convert.ToInt64(user.Id);
                if (_service.sendEmail(this.HttpContext.ApplicationInstance.Context, model.EmailId, callbackUrl, new EmailServerModel()
                {
                    UserId = user.UserId, UserName = user.UserName
                }, Constant.EmailType.ForgotPassword, userId, user.CountryId))
                {
                    return(RedirectToAction("PasswordChanged", "Account"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #27
0
        public async Task <string> GeneratePasswordResetTokenAsync(string tkey)     //mjb
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ResetPassword");

            _AppUserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <IdentityUser>(provider.Create("ResetPassword"))
            {
                TokenLifespan = TimeSpan.FromHours(3)
            };

            return(_AppUserManager.GeneratePasswordResetToken(tkey));
        }
예제 #28
0
        public static LicUserManager Create(IdentityFactoryOptions <LicUserManager> userManager, IOwinContext context)
        {
            var dbContext   = context.Get <AppDbContext>();
            var userStore   = new UserStore <Appuser>(dbContext);
            var usermanager = new LicUserManager(userStore);
            var provider    = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("LicenseProtoType");

            usermanager.UserTokenProvider     = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <Appuser>(provider.Create("EmailConfirmation"));
            usermanager.ClaimsIdentityFactory = new ClaimsIdentityFactory <Appuser>();
            return(usermanager);
        }
예제 #29
0
        public async Task <IdentityResult> ResetPasswordAsync(string id, string code, string password)     //mjb
        {
            //try
            //{
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ResetPassword");

            _AppUserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <IdentityUser>(provider.Create("ResetPassword"))
            {
                TokenLifespan = TimeSpan.FromHours(100)
            };

            var result = await _AppUserManager.ResetPasswordAsync(id, code, password);

            return(result);

            //}
            //catch (Exception ex)
            //{
            //    var x = ex.InnerException;
            //    List<string> errors = new List<string>() { ex.Message };
            //    return IdentityResult.Failed(errors.ToArray());
            //}
        }
예제 #30
0
        public async Task <string> GenerateEmailConfirmationTokenAsync(string userId)
        {
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("YourAppName");

            database.UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
            return(await database.UserManager.GenerateEmailConfirmationTokenAsync(userId));
        }
예제 #31
0
        private UserManager <ApplicationUser> InitUserManager(UserManager <ApplicationUser> manager)
        {
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("FilmOverflow");

            manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
            return(manager);
        }
예제 #32
0
        public dynamic Put(ChangePasswordDTO objresetpassword)
        {
            CustomResponse objres = new CustomResponse();

            if (objresetpassword.ChageType == 1)
            {
                try
                {
                    //compare key with database
                    if (AccountRepository.CompareResetToken(objresetpassword.userid, objresetpassword.oldpassword))
                    {
                        var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");
                        userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <MyIdentityUser>(provider.Create("EmailConfirmation"));

                        string         resettoken = userManager.GeneratePasswordResetToken(objresetpassword.userid);
                        IdentityResult objresult  = userManager.ResetPassword(objresetpassword.userid, resettoken, objresetpassword.newpassword);
                        if (objresult.Succeeded)
                        {
                            objres.Status   = CustomResponseStatus.Successful;
                            objres.Message  = "Password Updated Successfully";
                            objres.Response = null;
                        }
                        else
                        {
                            objres.Status   = CustomResponseStatus.UnSuccessful;
                            objres.Message  = "Failed";
                            objres.Response = null;
                        }
                    }
                    else
                    {
                        objres.Status   = CustomResponseStatus.UnSuccessful;
                        objres.Message  = "Invalid Access token";
                        objres.Response = null;
                    }
                }
                catch (Exception ex)
                {
                    objres.Status   = CustomResponseStatus.Exception;
                    objres.Message  = ex.Message;
                    objres.Response = null;
                }
                return(objres);
            }
            else if (objresetpassword.ChageType == 2)
            {
                try
                {
                    IdentityResult result = userManager.ChangePassword(objresetpassword.userid, objresetpassword.oldpassword, objresetpassword.newpassword);
                    objres.Response = null;

                    if (result.Succeeded)
                    {
                        objres.Status  = CustomResponseStatus.Successful;
                        objres.Message = "Password Changed Successfully";
                    }
                    else
                    {
                        objres.Status  = CustomResponseStatus.UnSuccessful;
                        objres.Message = "Failed to update Password";
                    }
                }
                catch (Exception ex)
                {
                    objres.Status   = CustomResponseStatus.Successful;
                    objres.Message  = ex.Message;
                    objres.Response = null;
                }

                return(objres);
            }
            else if (objresetpassword.ChageType == 3)
            {
                try
                {
                    MyIdentityUser objuser = userManager.FindByEmail(objresetpassword.Email);
                    objuser.FirstName    = objresetpassword.FirstName;
                    objuser.LastName     = objresetpassword.LastName;
                    objuser.MobileNumber = objresetpassword.MobileNumber;
                    IdentityResult objidentityresult = userManager.Update(objuser);
                    objres.Response = null;

                    if (objidentityresult.Succeeded)
                    {
                        objres.Status  = CustomResponseStatus.Successful;
                        objres.Message = "User Updated Successfully";
                    }
                    else
                    {
                        objres.Status  = CustomResponseStatus.UnSuccessful;
                        objres.Message = "Failed to update User Details";
                    }
                }
                catch (Exception ex)
                {
                    objres.Status   = CustomResponseStatus.Successful;
                    objres.Message  = ex.Message;
                    objres.Response = null;
                }

                return(objres);
            }
            else
            {
                return(null);
            }
        }
        public async Task <ActionResult> ConfirmEmail(string userId, string code)
        {
            //if (userId == null || code == null)
            //{
            //    return View("Error");
            //}
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Sample");

            UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(provider.Create("EmailConfirmation"));
            //var result = await UserManager.ConfirmEmailAsync(userId, code);
            //if (result.Succeeded)
            //{
            //    return View("ConfirmEmail");
            //}
            //AddErrors(result);
            //return View();
            if (userId == null || code == null)
            {
                return(View("Error"));
            }
            IdentityResult result;

            try
            {
                result = await UserManager.ConfirmEmailAsync(userId, code);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                ViewBag.errorMessage = ioe.Message;
                return(View("Error"));
            }

            if (result.Succeeded)
            {
                return(View());
            }

            // If we got this far, something failed.
            AddErrors(result);
            ViewBag.errorMessage = "ConfirmEmail failed";
            return(View("Error"));
        }