/
afanasevn
/
MaxSystems
Обзор
Документация
Войти
/
afanasevn
/
MaxSystems
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/MaxSystems.Infrastructure/Services/AuthService.cs
68 строк
2 KB
IBS\NAfanasev
Integration Event Bus
22 июн 2026, 17:01
22 июн 2026, 17:01
83907da
Код
Авторство
О чём код?
using MaxSystems.Application.Abstractions; using MaxSystems.Application.Contracts.Auth; using MaxSystems.Domain.Entities; using MaxSystems.Infrastructure.Audit; using MaxSystems.Infrastructure.Auth; using MaxSystems.Infrastructure.Data; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace MaxSystems.Infrastructure.Services; /// <summary>Аутентификация пользователей и выдача JWT.</summary> public sealed class AuthService( AppDbContext db, JwtTokenService jwtTokenService, IAuditService audit) : IAuthService { private static readonly PasswordHasher<User> PasswordHasher = new(); /// <summary>Проверяет email и пароль, пишет audit и возвращает JWT с профилем.</summary> public async Task<LoginResponse?> LoginAsync( string email, string password, CancellationToken ct = default) { var normalizedEmail = email.Trim().ToLowerInvariant(); var user = await db.Users .FirstOrDefaultAsync( x => x.Email.ToLower() == normalizedEmail && x.Active, ct); if (user is null || string.IsNullOrEmpty(user.PasswordHash)) return null; var result = PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, password); if (result == PasswordVerificationResult.Failed) return null; audit.Log( user.Id, "LOGIN", "User", user.Id, AuditMessages.Login(user.Name, user.Email)); await db.SaveChangesAsync(ct); return new LoginResponse( jwtTokenService.CreateToken(user), MapProfile(user)); } /// <summary>Профиль активного пользователя по идентификатору из JWT.</summary> public async Task<UserProfileDto?> GetProfileAsync( Guid userId, CancellationToken ct = default) { var user = await db.Users .AsNoTracking() .FirstOrDefaultAsync(x => x.Id == userId && x.Active, ct); return user is null ? null : MapProfile(user); } /// <summary>Маппинг сущности пользователя в DTO профиля.</summary> private static UserProfileDto MapProfile(User user) => new(user.Id, user.Email, user.Name, user.Role.ToString()); }