Refactor: the project is now divided into a more clear structure, with **Infrastructure** and **Application** layers added. Refactor: configurations are split into sections for different layers. Fix: now EF Core related operations, such as migration, should be invoked in `OptixServe.Infrastructure`, with config file and data dir passed into `dotnet ef` command. See `OptixServe.Infrastructure/Utilites/DesignTimeDbContextFactory.cs` for details. Fix: EF migrations are ignored in gitignore on purpose in early development.
61 lines
2.0 KiB
C#
61 lines
2.0 KiB
C#
using System.Text.Json.Serialization;
|
|
using OptixServe.Application.Services;
|
|
using OptixServe.Api.Dtos;
|
|
using OptixServe.Api.Services;
|
|
|
|
namespace OptixServe.Api.Endpoints;
|
|
|
|
|
|
[JsonSerializable(typeof(UserDto))]
|
|
[JsonSerializable(typeof(IEnumerable<UserDto>))]
|
|
[JsonSerializable(typeof(LoginRequestDto))]
|
|
[JsonSerializable(typeof(LoginResponseDto))]
|
|
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 });
|
|
}
|
|
}
|