ShoppingApp/Weifer.ShoppingApp.API/RestApi/AuthenticationApiController.cs
2024-03-04 23:00:10 +01:00

79 lines
2.3 KiB
C#

using Microsoft.AspNetCore.Mvc;
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
{
public readonly DatabaseContext dbContext;
public readonly AuthenticationController authenticationController;
public AuthenticationApiController()
{
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))
{
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();
}
return Ok(new
{
token = token, // Token Information
customer = new CustomerDto
{
CustomerId = customer.CustomerId,
FirstName = customer.FirstName,
LastName = customer.LastName,
Email = credentials.Email
}
});
}
return Unauthorized();
}
[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();
}
}