Add sign in backend

This commit is contained in:
AleksDw
2025-05-18 15:56:07 +02:00
parent d1117959cd
commit b70697abc3
3 changed files with 76 additions and 0 deletions

9
WebApp/DTOs/LoginDto.cs Normal file
View File

@@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;
namespace WebApp.DTOs;
public record class LoginDto
(
[Required] string Email,
[Required] string Password
);

View File

@@ -0,0 +1,66 @@
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using System.Text;
using WebApp.Data;
using WebApp.DTOs;
using WebApp.Entities;
namespace WebApp.Endpoints
{
public static class AuthEndpoints
{
public static RouteGroupBuilder MapAuthEndpoints(this WebApplication app)
{
var group = app.MapGroup("auth")
.WithParameterValidation();
group.MapPost("/login", async (LoginDto dto, ApplicationDbContext context) =>
{
var user = await context.WebUsers.FirstOrDefaultAsync(u => u.Email == dto.Email);
if (user == null)
{
return Results.Json(new {message = "Wrong email or password."}, statusCode: 401);
}
string hashedPassword = HashPasswordSHA512(dto.Password);
if(user.Password != hashedPassword)
{
return Results.Json(new { message = "Wrong email or password." }, statusCode: 401)
}
var token = new Token
{
UserId = user.UserId,
Value = "lah-" + Guid.NewGuid().ToString(),
ValidUntil = DateTime.UtcNow.AddDays(7),
};
//context.Tokens.Add(token);
//await context.SaveChangesAsync();
return Results.Ok(new
{
message = "Login successful.",
token = token.Value
});
});
return group;
}
static string HashPasswordSHA512(string password)
{
using (var sha512 = SHA512.Create())
{
byte[] bytes = Encoding.ASCII.GetBytes(password);
byte[] hash = sha512.ComputeHash(bytes);
string hashstring = BitConverter.ToString(hash).Replace("-", "").ToLower();
Console.WriteLine($"Hashed Password: {hashstring}");
return hashstring;
}
}
}
}

View File

@@ -52,5 +52,6 @@ app.UseRouting(); // Enables routing to match incoming request to endpoints
// Map Minimal API Endpoints
app.MapEventsEndpoints();
app.MapOrganizationsEndpoints();
app.MapAuthEndpoints();
app.Run();