Ejemplo n.º 1
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateRequest request)
        {
            if (request == null)
            {
                return(Unauthorized());
            }
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var passwordHash = await BCryptHelper.PasswordHash(request.Password);

            var user = await _userService.GetUserByName(request.Username);

            if (user == null)
            {
                return(BadRequest(new { message = "User not found" }));
            }

            bool isVerified = await BCryptHelper.VerifyHash(request.Password, user.Password);

            if (!isVerified)
            {
                return(BadRequest(new { message = "Invalid username or password" }));
            }

            string tokenString = await JwtHelper.GenerateToken(user, _setting);

            user.RefreshTokens.Add(new RefreshToken {
                Expires     = DateTime.UtcNow.AddHours(1),
                Token       = tokenString,
                Created     = DateTime.UtcNow,
                CreatedByIp = await HttpHelper.GetIP4Address(HttpContext)
            });
            await _userService.Update(user);

            return(Ok(new UserResponse
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Username = user.Username,
                Token = tokenString
            }));
        }