ShoppingApp/Weifer.ShoppingApp.API/RestApi/AuthenticationApiController.cs
2024-03-01 20:37:36 +01:00

58 lines
1.8 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
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();
return Ok(new
{
token = token, // Token Information
customer = new CustomerDto
{ // Kundeninformationen
CustomerId = customer.CustomerId,
FirstName = customer.FirstName,
LastName = customer.LastName,
Email = credentials.Email
}
});
}
return Unauthorized();
}
}