Add auto-load guest data on login

This commit is contained in:
steinhelge
2025-11-24 06:25:56 +01:00
parent 0312a150c1
commit f7f31b58c1
4 changed files with 147 additions and 77 deletions
@@ -52,4 +52,19 @@ public class AuthController : ControllerBase
return Ok(userInfo);
}
[HttpGet("me/person")]
[Authorize]
public async Task<ActionResult> GetCurrentUserPerson()
{
var email = User.FindFirstValue(ClaimTypes.Email);
if (email == null)
return Unauthorized();
var person = await _authService.GetUserPersonAsync(email);
if (person == null)
return NotFound(new { message = "Your account is not linked to a person. Please contact an administrator." });
return Ok(person);
}
}
@@ -4,7 +4,9 @@ using System.Text;
using Hospitality.Backend.Configuration;
using Hospitality.Backend.DTOs;
using Hospitality.Domain.Entities;
using Hospitality.Infrastructure.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
@@ -15,15 +17,18 @@ public class AuthService : IAuthService
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly JwtSettings _jwtSettings;
private readonly HospitalityDbContext _context;
public AuthService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IOptions<JwtSettings> jwtSettings)
IOptions<JwtSettings> jwtSettings,
HospitalityDbContext context)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtSettings = jwtSettings.Value;
_context = context;
}
public async Task<LoginResponse?> LoginAsync(LoginRequest request)
@@ -68,6 +73,37 @@ public class AuthService : IAuthService
return new UserInfoResponse(user.Email!, roles.ToArray());
}
public async Task<object?> GetUserPersonAsync(string email)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null || user.PersonId == null)
return null;
var person = await _context.People
.Include(p => p.Quotas)
.ThenInclude(q => q.Product)
.FirstOrDefaultAsync(p => p.Id == user.PersonId.Value);
if (person == null)
return null;
return new
{
name = person.Name,
email = person.Email,
qrCode = person.QrCode.ToString(),
quotas = person.Quotas.Select(q => new
{
productName = q.Product.Name,
productType = q.Product.Type.ToString(),
initialAmount = q.InitialAmount,
usedAmount = q.UsedAmount,
remainingAmount = q.RemainingAmount
}).ToList()
};
}
private string GenerateJwtToken(ApplicationUser user, string[] roles)
{
var claims = new List<Claim>
@@ -7,4 +7,5 @@ public interface IAuthService
Task<LoginResponse?> LoginAsync(LoginRequest request);
Task<bool> RegisterAsync(RegisterRequest request);
Task<UserInfoResponse?> GetUserInfoAsync(string email);
Task<object?> GetUserPersonAsync(string email);
}