mirror of
https://github.com/GCMatters/hermes.git
synced 2026-02-04 13:40:13 +01:00
Add sign in backend
This commit is contained in:
9
WebApp/DTOs/LoginDto.cs
Normal file
9
WebApp/DTOs/LoginDto.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WebApp.DTOs;
|
||||
|
||||
public record class LoginDto
|
||||
(
|
||||
[Required] string Email,
|
||||
[Required] string Password
|
||||
);
|
||||
66
WebApp/Endpoints/AuthEndpoints.cs
Normal file
66
WebApp/Endpoints/AuthEndpoints.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user