Add: JWT authentication in Web API. Related configuration and services are added.
62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using System.Text.Json.Serialization;
|
|
using OptixServe.Core.Services;
|
|
using OptixServe.Api.Dtos;
|
|
using OptixServe.Api.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
namespace OptixServe.Api.Endpoints;
|
|
|
|
|
|
[JsonSerializable(typeof(UserDto))]
|
|
[JsonSerializable(typeof(IEnumerable<UserDto>))]
|
|
[JsonSerializable(typeof(LoginRequestDto))]
|
|
[JsonSerializable(typeof(LoginResponseDto))] // For returning the token string
|
|
public partial class UserJsonContext : JsonSerializerContext { }
|
|
|
|
public static class UserEndpoint
|
|
{
|
|
public static void Register(RouteGroupBuilder parentGroup)
|
|
{
|
|
var group = parentGroup.MapGroup("/users");
|
|
|
|
group.MapPost("/login", LoginUser);
|
|
group.MapGet("/", GetAllUsers).RequireAuthorization();
|
|
group.MapGet("/{id}", GetUserById).RequireAuthorization();
|
|
}
|
|
|
|
public static IResult LoginUser(LoginRequestDto loginRequest, IUserService userService, ITokenService tokenService)
|
|
{
|
|
if (string.IsNullOrEmpty(loginRequest.UserName) || string.IsNullOrEmpty(loginRequest.Password))
|
|
{
|
|
return Results.BadRequest("Username and password are required.");
|
|
}
|
|
|
|
// Password hashing and salting will be implemented later.
|
|
var user = userService.GetUserByUsername(loginRequest.UserName);
|
|
|
|
if (user == null || user.Password != loginRequest.Password)
|
|
{
|
|
return Results.Unauthorized();
|
|
}
|
|
|
|
var token = tokenService.GenerateToken(user);
|
|
return Results.Ok(new LoginResponseDto { Token = token });
|
|
}
|
|
|
|
public static IResult GetAllUsers(IUserService userService)
|
|
{
|
|
var users = userService.GetUsers()
|
|
.Select(u => new UserDto { Id = u.Id, UserName = u.UserName });
|
|
return Results.Ok(users);
|
|
}
|
|
|
|
public static IResult GetUserById(string id, IUserService userService)
|
|
{
|
|
var user = userService.GetUserById(id);
|
|
if (user == null)
|
|
return Results.NotFound();
|
|
|
|
return Results.Ok(new UserDto { Id = user.Id, UserName = user.UserName });
|
|
}
|
|
}
|