Ejemplo n.º 1
0
        //Post => api/User/Login
        public async Task <ActionResult> Login(LoginUserViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var user = await _userManager.FindByNameAsync(model.UserName);

                    if ((user != null) && (await _userManager.CheckPasswordAsync(user, model.Password)))
                    {
                        var token = _jwtCreator.GenerateToken(user.UserName);

                        user.RefreshToken = GenerateRefreshToken();

                        var result = await _userManager.UpdateAsync(user);

                        if (result.Succeeded)
                        {
                            AppendCookies(token, user.RefreshToken);

                            _logger.LogInformation($"DateTime: {DateTime.Now} -- User {user.UserName} has logged in");

                            return(Ok());
                        }
                        else
                        {
                            _logger.LogWarning($"DateTime: {DateTime.Now} -- Error: Couldn't update the refresh token of into database");
                            return(BadRequest());
                        }
                    }
                    else
                    {
                        return(BadRequest(new { message = "Username or password is incorrect." }));
                    }
                }
                else
                {
                    _logger.LogWarning($"DateTime: {DateTime.Now} -- Error: Login Format isn't right from Login");
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"DateTime:{DateTime.Now} -- Error:{e.Message}\n{e.StackTrace}");
                return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to get user data"));
            }
        }