コード例 #1
0
ファイル: UserController.cs プロジェクト: jason0100/Temple
        public async Task <IActionResult> ResetPassword(UserForRecoverPW model)
        {
            ResultModel result = new ResultModel();

            if (String.IsNullOrEmpty(model.newPassword) || String.IsNullOrEmpty(model.ConfirmNewPassword))
            {
                TempData["IsSuccess"] = false;
                TempData["msg"]       = "請確認密碼欄位均輸入";
                return(View(model));
            }
            else
            {
                if (model.newPassword.Trim() != model.ConfirmNewPassword.Trim())
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"]       = "兩次密碼輸入不相同";
                    return(View(model));
                }

                var data = JsonConvert.SerializeObject(model);
                result = await _callApi.CallAPI(data, new Uri(_config["api"].ToString() + "/auth/ResetPassword"), "POST");

                if (result.IsSuccess == true)
                {
                    TempData["SendMailSuccess"] = "重設密碼郵件已寄出,請於15分鐘內點擊郵件內的連結。ps.請留意垃圾信件匣";
                }
                TempData["IsSuccess"] = result.IsSuccess;
                TempData["msg"]       = "重設密碼成功";
                return(RedirectToAction(nameof(Login)));
            }
        }
コード例 #2
0
ファイル: UserController.cs プロジェクト: jason0100/Temple
        public async Task <IActionResult> ResetPassword(UserForRecoverPW model, string url)
        {
            if (String.IsNullOrEmpty(model.token) || model.id == 0)
            {
                return(RedirectToAction(nameof(Login)));
            }


            return(View(model));
        }
コード例 #3
0
ファイル: AuthController.cs プロジェクト: jason0100/Temple
        public async Task <ResultModel> ResetPassword([FromBody] UserForRecoverPW user)
        {
            var result = new ResultModel();

            if (String.IsNullOrEmpty(user.newPassword))
            {
                result.IsSuccess = false;
                result.Message   = "New password required.";
                return(result);
            }

            result = await _repo.ResetPassword(user);

            logger.Info("userId=" + user.id + ", username="******"\nResetPassword " + result.Message);
            return(result);
        }
コード例 #4
0
ファイル: UserController.cs プロジェクト: jason0100/Temple
        public async Task <IActionResult> RecoverPassword(UserForRecoverPW model)
        {
            ResultModel result = new ResultModel();
            var         data   = JsonConvert.SerializeObject(model);

            result = await _callApi.CallAPI(data, new Uri(_config["api"].ToString() + "/auth/RecoverPassword"), "POST");

            TempData["IsSuccess"] = result.IsSuccess;
            TempData["msg"]       = result.Message;
            if (result.IsSuccess == true)
            {
                TempData["SendMailSuccess"] = "重設密碼郵件已寄出,請於15分鐘內點擊郵件內的連結。ps.請留意垃圾信件匣";
            }

            return(View());
        }
コード例 #5
0
ファイル: AuthController.cs プロジェクト: jason0100/Temple
        public async Task <ResultModel> RecoverPassword([FromBody] UserForRecoverPW user)
        {
            var result = new ResultModel();

            result = await _repo.RecoverPassword(user);

            if (result.IsSuccess)
            {//set guid success
                //user = JsonConvert.DeserializeObject<UserForRecoverPW>(result.Data.ToString());
                var    url     = _config["web"];
                string message = url + "/User/ResetPassword?token=" + user.token + "&id=" + user.id;
                result = await _emailSender.SendEmailAsync(user.username, "Recover Password", message);
            }

            logger.Info("userId=" + user.id + ", username="******"\nRecoverPassword " + result.Message);
            return(result);
        }
コード例 #6
0
        public async Task <ResultModel> RecoverPassword(UserForRecoverPW user)
        {
            var result    = new ResultModel();
            var existUser = _context.Users.FirstOrDefault(u => u.UserName == user.username);

            if (existUser == null)
            {
                result.IsSuccess = false;
                result.Message   = "Username not exist.";
                return(result);
            }
            existUser.guid = Guid.NewGuid().ToString();

            try
            {
                _context.Entry(existUser).CurrentValues.SetValues(existUser);
                await _context.SaveChangesAsync(); // Save changes to database.

                result.IsSuccess = true;
                result.Message   = "Set guid success.";

                //generate token
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_config["TokenKey"]);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[] {
                        new Claim("GUID", existUser.guid)
                    }),
                    Expires = DateTime.Now.AddMinutes(15),

                    // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
                };
                user.token  = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
                user.id     = existUser.Id;
                result.Data = user;
            }
            catch (Exception e) {
                result.IsSuccess = false;
                result.Message   = "DB error";
            }
            return(result);
        }
コード例 #7
0
        public async Task <ResultModel> ResetPassword(UserForRecoverPW user)
        {
            var result = new ResultModel();
            //================驗證token signature===========
            var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(_config["TokenKey"]);
            var validationParameters = new TokenValidationParameters() // 生成驗證token的參數
            {
                RequireExpirationTime = true,                          // token是否包含有效期
                ValidateLifetime      = true,
                ValidateIssuer        = false,                         // 驗證秘鑰發行人,如果要驗證在這裏指定發行人字符串即可
                ValidateAudience      = false,                         // 驗證秘鑰的接受人,如果要驗證在這裏提供接收人字符串即可
                IssuerSigningKey      = new SymmetricSecurityKey(key)  // 生成token時的安全秘鑰
            };
            SecurityToken    securityToken;                            // 接受解碼後的token對象
            JwtSecurityToken jwtToken;

            try
            {
                jwtToken = tokenHandler.ReadToken(user.token) as JwtSecurityToken; // 將字符串token解碼成token對象
                var principal = tokenHandler.ValidateToken(user.token, validationParameters, out securityToken);
            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Message   = "Token invalid.";
                return(result);
            }

            var id   = user.id;
            var guid = jwtToken.Claims.FirstOrDefault(c => c.Type == "GUID");

            if (id == 0 || guid == null)
            {
                result.IsSuccess = false;
                result.Message   = "Token invalid.";
                return(result);
            }
            //==============================================
            var existUser = _context.Users.Find(id);

            if (existUser == null)
            {
                result.IsSuccess = false;
                result.Message   = "Username not exist.";
                return(result);
            }
            if (existUser.guid != guid.Value)
            {
                result.IsSuccess = false;
                result.Message   = "Invalid .";
            }
            else
            {
                if (String.IsNullOrEmpty(user.newPassword))
                {
                    result.IsSuccess = false;
                    result.Message   = "New password invalid .";
                    return(result);
                }
                //變更新密碼
                CreatePasswordHash(user.newPassword, out byte[] passwordHash, out byte[] passwordSalt);
                existUser.PasswordHash = passwordHash;
                existUser.PasswordSalt = passwordSalt;
                //existUser.guid = "";
                await _context.SaveChangesAsync();
            }
            result.IsSuccess = true;
            result.Message   = "重設密碼成功 .";
            return(result);
        }