public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var user = await UserManager.FindByNameAsync(model.Email);
                var user = await UserManager2.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager2.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    ModelState.AddModelError("", "無效的帳號");
                    return(View());
                }

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

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager2.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");

                ViewBag.Link = callbackUrl;
                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["ViewData"] = ViewData;
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                return(View(model));
            }
            var user = await UserManager2.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "使用者不存在");
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                // Don't reveal that the user does not exist
                return(View());
            }

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

            //if (string.IsNullOrEmpty(model.Code) || !code.Equals(model.Code))
            //{
            //    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
            //    return Redirect(model.ReturnUrl);
            //}

            var result = await UserManager2.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
                    return(Redirect(model.ReturnUrl));
                }
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            TempData["ViewData"] = ViewData;
            if (!string.IsNullOrEmpty(model.ReturnUrl))
            {
                return(Redirect(model.ReturnUrl));
            }
            return(View());
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            FormsAuthentication.SignOut();
            AuthenticationManager.SignOut();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            //比對驗證碼
            if (System.Configuration.ConfigurationManager.AppSettings["VerificationCode"] != null)
            {
                var VerificationText = System.Configuration.ConfigurationManager.AppSettings["VerificationCode"];
                var VerificationCode = Session[VerificationText].ToString();
                if (string.IsNullOrEmpty(model.VerificationCode) || VerificationCode.ToUpper() != model.VerificationCode.ToUpper())
                {
                    ModelState.AddModelError("", "無效的驗證碼");
                    return(View());
                }
            }

            //使用者是否存在
            var user = await UserManager2.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            //密碼檢查
            PasswordVerificationResult status = UserManager2.PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password);

            if (user == null || !status.Equals(PasswordVerificationResult.Success))
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            if (!user.EmailConfirmed)
            {
                //return RedirectToAction("SendCode");
                ModelState.AddModelError("", "未完成信箱驗證");
                return(View(model));
            }



            if (user != null && status.Equals(PasswordVerificationResult.Success))
            {
                //SignIn(user,model.RememberMe);
                await SignInAsync(user, model.RememberMe);

                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

                serializeModel.ID       = user.Id;
                serializeModel.Name     = user.UserName;
                serializeModel.Email    = user.Email;
                serializeModel.UserCode = user.UserCode;
                serializeModel.UserType = user.UserType;
                var UserRoles = (from rr in RoleManager2.Roles.ToList()
                                 join r1 in user.Roles on rr.Id equals r1.RoleId
                                 select rr.Name).ToList();

                //var r = (from uRoles in user.Roles
                //        join rr in RoleManager.Roles.ToList() on uRoles.RoleId == rr.RoleId).to


                serializeModel.roles = string.Join(",", UserRoles);
                // serializeModel.roles = "Admin";
                var ExpireDateTime = DateTime.Now.AddDays(3);
                if (model.RememberMe)
                {
                    ExpireDateTime = DateTime.Now.AddDays(15);
                }

                string userData = JsonConvert.SerializeObject(serializeModel);
                FormsAuthenticationTicket authTicket = null;
                authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddDays(15), false, userData);

                string     encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                {
                    Expires = authTicket.Expiration, Path = "/"
                };
                System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);

                _db.SystemLog.Add(new SystemLog
                {
                    Created        = DateTime.Now,
                    Creator        = model.Email,
                    IP             = IPaddress,
                    LogCode        = "Time",
                    LogType        = "SignIn",
                    LogDescription = "登入時間",
                    LogValue       = DateTime.Now.ToString()
                });
                _db.SaveChanges();

                return(RedirectToLocal(returnUrl));
            }


            return(View(model));
        }
        public async Task <ActionResult> ChangePassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["ViewData"] = ViewData;
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                return(View(model));
            }


            var user = await UserManager2.FindByEmailAsync(model.Email);


            if (user == null)
            {
                TempData["ErrorMessage"] = "密碼變更,使用者不存在";
                ModelState.AddModelError("", "使用者不存在");
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                // Don't reveal that the user does not exist
                FormsAuthentication.SignOut();
                AuthenticationManager.SignOut();
                return(Redirect("~/Home/AccountForUser"));
            }
            else
            {
                if (CurrentUser.Id != user.Id)
                {
                    TempData["ErrorMessage"] = "密碼變更,帳號不符";
                    ModelState.AddModelError("", "帳號不符");
                    FormsAuthentication.SignOut();
                    AuthenticationManager.SignOut();
                    return(Redirect("~/Home/AccountForUser"));
                }
            }

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


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

            if (result.Succeeded)
            {
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
                    return(Redirect(model.ReturnUrl));
                }
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            TempData["ViewData"] = ViewData;
            if (!string.IsNullOrEmpty(model.ReturnUrl))
            {
                return(Redirect(model.ReturnUrl));
            }
            return(View());
        }