Implement Refresh Token on startup

Co-authored-by: Reimar <mail@reim.ar>
This commit is contained in:
Sandertp 2024-08-29 13:25:02 +02:00
parent ffb5e20f79
commit a471a11015
6 changed files with 20 additions and 11 deletions

View File

@ -82,6 +82,8 @@ namespace API.Application.Users.Commands
CreatedAt = DateTime.UtcNow.AddHours(2),
UpdatedAt = DateTime.UtcNow.AddHours(2),
HashedPassword = hashedPassword,
RefreshToken = System.Guid.NewGuid().ToString(),
RefreshTokenExpiresAt = DateTime.UtcNow.AddDays(7),
};
}
}

View File

@ -34,7 +34,7 @@ namespace API.Application.Users.Commands
}
var jwtToken = _tokenHelper.GenerateJwtToken(user);
return new OkObjectResult(new { token = jwtToken, id = user.Id});
return new OkObjectResult(new { token = jwtToken, id = user.Id, refreshToken = user.RefreshToken});
}
}

View File

@ -89,12 +89,10 @@ namespace API.Controllers
return await _deleteUser.Handle(id);
}
[Authorize]
[HttpPost("/RefreshToken")]
public async Task<IActionResult> RefreshToken()
public async Task<IActionResult> RefreshToken(RefreshTokenDTO refreshTokenDTO)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _repository.QueryUserByIdAsync(userId);
User user = await _repository.QueryUserByRefreshTokenAsync(refreshTokenDTO.RefreshToken);
return new OkObjectResult(_tokenHelper.GenerateJwtToken(user));
}

View File

@ -39,3 +39,8 @@ public class UpdateUserDTO
public string Password { get; set; }
}
public class RefreshTokenDTO
{
public string RefreshToken { get; set; }
}

View File

@ -10,5 +10,6 @@ namespace API.Persistence.Repositories
Task<User> QueryUserByIdAsync(string id);
Task<User> QueryUserByEmailAsync(string email);
Task<bool> UpdateUserAsync(User user);
Task<User> QueryUserByRefreshTokenAsync(string refreshToken);
}
}

View File

@ -7,6 +7,7 @@ namespace API.Persistence.Repositories
public class UserRepository(AppDBContext context) : IUserRepository
{
private readonly AppDBContext _context = context;
public async Task<List<User>> QueryAllUsersAsync()
{
return await _context.Users.ToListAsync();
@ -16,14 +17,12 @@ namespace API.Persistence.Repositories
{
try
{
return await _context.Users
.FirstOrDefaultAsync(user => user.Id == id);
return await _context.Users.FirstOrDefaultAsync(user => user.Id == id);
}
catch (Exception)
{
return new User();
}
}
public async Task<string> CreateUserAsync(User user)
@ -73,7 +72,11 @@ namespace API.Persistence.Repositories
public async Task<User> QueryUserByEmailAsync(string email)
{
return await _context.Users.SingleOrDefaultAsync(u => u.Email == email);
}
public async Task<User> QueryUserByRefreshTokenAsync(string refreshToken)
{
return await _context.Users.SingleOrDefaultAsync(u => u.RefreshToken == refreshToken);
}
}
}