ShoppingApp/Weifer.ShoppingApp.API/RestApi/AuthenticationApiController.cs

79 lines
2.3 KiB
C#
Raw Permalink Normal View History

using Microsoft.AspNetCore.Mvc;
2024-03-01 20:37:36 +01:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;
using Weifer.Database.EF;
using Weifer.ShoppingApp.API.Controllers;
using Weifer.ShoppingApp.API.Models;
namespace Weifer.ShoppingApp.API.RestApi;
[ApiController]
[Route("api/[controller]")]
public class AuthenticationApiController : ControllerBase
2024-02-25 13:22:48 +01:00
{
public readonly DatabaseContext dbContext;
public readonly AuthenticationController authenticationController;
public AuthenticationApiController()
2024-02-25 13:22:48 +01:00
{
dbContext = new DatabaseContext();
authenticationController = new AuthenticationController();
}
[HttpPost("login")]
public async Task<IActionResult> CustomerLogin([FromBody] CustomerCredentials credentials)
{
if (credentials == null)
{
return Unauthorized();
}
var hashedPassword = dbContext.Customers.Where(cu => cu.Email == credentials.Email).Select(x => x.PasswordHash).FirstOrDefault();
if (hashedPassword == null)
{
return Unauthorized();
}
if (authenticationController.VerifyPassword(credentials.Password, hashedPassword))
{
2024-03-01 20:37:36 +01:00
var customer = await dbContext.Customers.Where(cu => cu.Email == credentials.Email).FirstOrDefaultAsync();
var token = authenticationController.GenerateJwtToken();
if (customer != null)
{
customer.SessionToken = token;
await dbContext.SaveChangesAsync();
}
2024-03-01 20:37:36 +01:00
return Ok(new
{
token = token, // Token Information
customer = new CustomerDto
{
2024-03-01 20:37:36 +01:00
CustomerId = customer.CustomerId,
FirstName = customer.FirstName,
LastName = customer.LastName,
Email = credentials.Email
2024-03-01 20:37:36 +01:00
}
});
}
return Unauthorized();
2024-02-25 13:22:48 +01:00
}
[HttpGet("validateToken")]
public async Task<IActionResult> ValidateToken()
{
var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var user = await dbContext.Customers.FirstOrDefaultAsync(x => x.SessionToken == token);
if (user != null)
{
return Ok();
}
return Unauthorized();
}
2024-02-25 13:22:48 +01:00
}