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"));
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
0
        private async Task enviarMailConfirmacion(ApplicationUser user)
        {
            var dataProtectionProvider = Startup.DataProtectionProvider;
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("EvaluandoSoftware");

            //UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
            UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.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);
            var emailSender = new EmailSender();

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(user.Email);
            msg.IsBodyHtml = true;
            msg.From       = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["SMTPUsername"], "Equipo de EvaluandoSoftware.com");
            msg.Subject    = "Confirmar registro en EvaluandoSoftware.com";
            msg.Body       = "Estimado " + user.FirstName + " " + user.LastName + ":<br><br>Usted ha iniciado el proceso de registro en Evaluando Software. <br>Por favor haga click <a href='" + callbackUrl + "'>aquí</a> para confirmar su registracion. <br><br> Lo saluda atentamente, <br>el equipo de <a href='evaluandosoftware.com' target='_blank'>EvaluandoSoftware.com</a>";
            emailSender.Send(msg);

            var updateUser = modelContext.Users.First(x => x.Id == user.Id);

            updateUser.confirmToken = code;
            modelContext.SaveChanges();
        }
        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"));
        }
Ejemplo n.º 5
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);
        }
        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));
        }
Ejemplo n.º 7
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)
            };
        }
Ejemplo n.º 8
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));
        }
Ejemplo n.º 9
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;
 }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public static LicUserManager Create(AppDbContext context)
        {
            var dbcontext   = context;
            var usermanager = new LicUserManager(new UserStore <Appuser>(dbcontext));
            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);
        }
        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;
        }
Ejemplo n.º 14
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));
        }
Ejemplo n.º 15
0
        public static AppUserManager Create(IdentityFactoryOptions <AppUserManager> factory, IOwinContext context)
        {
            var dbcontext   = context.Get <ApplicationDbContext>();
            var usermanager = new AppUserManager(new UserStore <AppUser>(dbcontext));
            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);
        }
Ejemplo n.º 16
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>");
        }
Ejemplo n.º 17
0
        public async Task sendMail(string Id)
        {
            var user = await UserManager.Users.Where(x => x.UserName.Contains("S") && x.UserName == Id).SingleOrDefaultAsync();

            //sa table user table
            //重設資料庫該 user 密碼 並 hash 存入 db
            //重設db密碼
            //1.重設 user 密碼
            string pwd = generateFirstPwd();
            await UserManager.UpdateSecurityStampAsync(user.Id);

            user.PasswordHash            = UserManager.PasswordHasher.HashPassword(pwd);
            user.LastPasswordChangedDate = null;

            var SupAcc = db.SupplierAccount.Where(x => x.SupplierAccountID == Id).SingleOrDefault();

            SupAcc.PasswordHash = user.PasswordHash;

            // 傳送包含此連結的電子郵件
            var    provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("PMSAWebMVC");
            string code     = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            string tempMail    = System.IO.File.ReadAllText(Server.MapPath(@"~\Views\Shared\ResetPwdSupEmailTemplate.html"));
            // 經測試 gmail 不支援 uri data image 所以用網址傳圖比較保險
            string img = "https://ci5.googleusercontent.com/proxy/4OJ0k4udeu09Coqzi7ZQRlKXsHTtpTKlg0ungn0aWQAQs2j1tTS6Q6e8E0dZVW2qsbzD1tod84Zbsx62gMgHLFGWigDzFOPv1qBrzhyFIlRYJWSMWH8=s0-d-e1-ft#https://app.flashimail.com/rest/images/5d8108c8e4b0f9c17e91fab7.jpg";

            string SupAccIDstr = user.UserName;
            string MailBody    = MembersDBService.getMailBody(tempMail, img, callbackUrl, pwd, SupAccIDstr);

            //寄信
            await UserManager.SendEmailAsync(user.Id, "重設您的密碼", MailBody);

            //3.更新db寄信相關欄位
            //SendLetterDate
            SupAcc.SendLetterDate = DateTime.Now;
            //SendLetterStatus
            SupAcc.SendLetterStatus = "S";

            await updateTable(user, SupAcc);

            //新增Supplier
            var userRoles = await UserManager.GetRolesAsync(user.Id);

            if (!userRoles.Contains("Supplier"))
            {
                user.Roles.Clear();
                var result = await UserManager.AddToRolesAsync(user.Id, "Supplier");
            }

            //更新狀態欄位 user sa table
            await AccStatusReset(Id);
        }
        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;
        }
Ejemplo n.º 19
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> sendMailConfirm()
        {
            string LognId = User.Identity.GetUserId();
            //寄驗證信
            // 傳送包含此連結的電子郵件
            var    provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("PMSAWebMVC");
            string code     = await UserManager.GenerateEmailConfirmationTokenAsync(LognId);

            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { Area = "", userId = LognId, code = code }, protocol: Request.Url.Scheme);
            //寄信
            await UserManager.SendEmailAsync(LognId, "信箱驗證", $"<a href='{callbackUrl}'>請點此驗證信箱</a>");

            TempData["Sended"] = "已寄送!請到信箱收信!";
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 21
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),
            };
        }
        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"
            });
        }
Ejemplo n.º 23
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));
        }
Ejemplo n.º 24
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"));
        }
        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));
        }
Ejemplo n.º 26
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 {
            };
        }
        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"));
        }
Ejemplo n.º 28
0
        // 帳戶確認及密碼重設
        private async Task sendMailatIndex(ApplicationUser user, string EmpId)
        {
            //emp table user table
            //重設資料庫該 user 密碼 並 hash 存入 db
            //重設db密碼
            //1.重設 user 密碼
            string pwd = generateFirstPwd();
            await UserManager.UpdateSecurityStampAsync(user.Id);

            user.PasswordHash            = UserManager.PasswordHasher.HashPassword(pwd);
            user.LastPasswordChangedDate = null;
            await UserManager.UpdateAsync(user);

            var emp = db.Employee.Where(x => x.EmployeeID == EmpId).SingleOrDefault();

            emp.PasswordHash = user.PasswordHash;

            // 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771
            // 傳送包含此連結的電子郵件
            var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("PMSAWebMVC");
            //更改密碼要在code之前不然他是拿UpdateSecurityStampAsync 來生code的
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            string tempMail    = System.IO.File.ReadAllText(Server.MapPath(@"~\Views\Shared\ResetPwdEmailTemplate.html"));
            // 經測試 gmail 不支援 uri data image 所以用網址傳圖比較保險
            string img      = "https://ci5.googleusercontent.com/proxy/4OJ0k4udeu09Coqzi7ZQRlKXsHTtpTKlg0ungn0aWQAQs2j1tTS6Q6e8E0dZVW2qsbzD1tod84Zbsx62gMgHLFGWigDzFOPv1qBrzhyFIlRYJWSMWH8=s0-d-e1-ft#https://app.flashimail.com/rest/images/5d8108c8e4b0f9c17e91fab7.jpg";
            string MailBody = MembersDBService.getMailBody(tempMail, img, callbackUrl, pwd);

            //寄信
            await UserManager.SendEmailAsync(user.Id, "重設您的密碼", MailBody);

            //3.更新db寄信相關欄位
            //SendLetterDate
            emp.SendLetterDate = DateTime.Now;
            //SendLetterStatus
            emp.SendLetterStatus = "S";

            //更新狀態欄位 user emo table
            await AccStatusReset(EmpId);
        }
Ejemplo n.º 29
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> 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);
        }
Ejemplo n.º 31
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());
            //}
        }
Ejemplo n.º 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");
        }
        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> 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");
        }