using FluentValidation; using NTP.Application.Abstractions; using NTP.Application.Common; namespace NTP.Application.Auth; public interface IAuthService { Task LoginAsync(LoginRequest request, ClientInfo client, CancellationToken ct); Task SetLanguageAsync(SetLanguageRequest request, CancellationToken ct); Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken ct); Task SignOutAsync(ClientInfo client, CancellationToken ct); /// Application.cfc: user still active with the same role code. Task IsUserStillActiveAsync(string login, string roleCode, CancellationToken ct); } /// Port of NTP_LIVE components/signon.cfc (checkLogin, assignUserVariables, changePass, signOut). public sealed class AuthService( IAuthRepository repository, ITokenIssuer tokenIssuer, ICurrentUser currentUser, IValidator loginValidator, IValidator changePasswordValidator, IValidator languageValidator) : IAuthService { // Legacy messages (kept verbatim). public const string InvalidLoginMessage = "معلومات الدخول خاطئة ... حاول مرة أخرى"; private const string NoActiveBoothMessage = "لا يمكنك الدخول, يرجى مراجعة رئيس الشفت"; private const string OldPasswordWrongMessage = "الرجاء التأكد من كلمة السر القديمة"; private const string PasswordChangedMessage = "تم تغيير كلمة السر بنجاح"; // GateEventsFactory.CheckAuthorization roles that need an active booth (UTT row). private static readonly string[] BoothRoles = ["GINOP", "GOTOP", "THOP", "GOP", "YOTOP", "GOPTS"]; // checkLogin: roles whose login IP is compared with LOCATIONS_IPS. private static readonly string[] IpCheckedRoles = ["GOP", "OPOFF", "GOPTS", "ONO", "YO"]; private const int LogSignIn = 1; private const int LogSignOut = 2; private const long StaffCompanyId = 15; public async Task LoginAsync(LoginRequest request, ClientInfo client, CancellationToken ct) { await loginValidator.ValidateAndThrowAsync(request, ct); var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (parts.Length != 2) throw Invalid(); var domain = parts[0]; var login = parts[1].ToLowerInvariant(); var candidates = PasswordHasher.Candidates(domain, login, request.Password); var found = await repository.FindActiveUserByPasswordAsync(login, domain, candidates, requireActiveCompany: PasswordHasher.IsAseza(domain), ct) ?? throw Invalid(); var roleCode = found.RoleCode ?? string.Empty; if (BoothRoles.Contains(roleCode, StringComparer.OrdinalIgnoreCase) && !await repository.HasActiveBoothAsync(login, ct)) throw new AuthenticationFailedException("NO_ACTIVE_BOOTH", NoActiveBoothMessage); // ---- assignUserVariables ---- var profile = await repository.GetProfileAsync(login, domain, ct); if (profile is null || string.IsNullOrEmpty(profile.RoleCode)) throw Invalid(); var hierarchy = await repository.GetHierarchyAsync(profile.Id, ct); LocationRow? location = null; if (profile.LocationId is { } locId) { // Legacy: for YDADM/YOCC/GOP at location 5 the lookup is restricted to domain ASEZA. var restrict = locId == 5 && new[] { "YDADM", "YOCC", "GOP" }.Contains(profile.RoleCode, StringComparer.OrdinalIgnoreCase); location = await repository.GetLocationAsync(locId, restrict ? "ASEZA" : null, ct); } var roleName = await repository.GetRoleNameAsync(profile.RoleCode, ct); if (roleName is null) throw new AuthenticationFailedException("NO_PRIVILEGES", $"{login} - لا توجد لديك صلاحيات"); var user = new AuthenticatedUser( Id: profile.Id, UserId: login.ToUpperInvariant(), Name: profile.Name ?? string.Empty, RoleCode: profile.RoleCode, RoleName: roleName, Domain: profile.DomainName ?? domain, LocationId: profile.LocationId, LocationName: location?.Name ?? string.Empty, StkId: hierarchy?.StakeholderId, CompId: hierarchy?.CompanyId, CompanyId: profile.CompanyId, CompanyName: profile.CompanyName ?? string.Empty, CompanyCode: profile.CompanyCode ?? string.Empty, EmpNo: profile.EmpNo ?? string.Empty, Lang: "AR", IsStaff: profile.CompanyId == StaffCompanyId); // Logging (addlog 1) - legacy swallows logging errors. await TryAsync(() => repository.InsertLogAsync( new AuditLogEntry(user.UserId, client.IpAddress, user.RoleCode, LogSignIn, user.Name, client.UserAgent), ct)); await TryAsync(() => LogInvalidAccessAsync(user, profile, client, ct)); var (token, expires) = tokenIssuer.Issue(user); return new LoginResponse(token, "Bearer", expires, CurrentUserDto.From(user), IsTruthy(profile.ResetPassword)); } public async Task SetLanguageAsync(SetLanguageRequest request, CancellationToken ct) { await languageValidator.ValidateAndThrowAsync(request, ct); var user = FromCurrent() with { Lang = request.Lang.ToUpperInvariant() }; var (token, expires) = tokenIssuer.Issue(user); return new TokenResponse(token, "Bearer", expires, CurrentUserDto.From(user)); } public async Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken ct) { await changePasswordValidator.ValidateAndThrowAsync(request, ct); var login = currentUser.UserId; var domain = currentUser.Domain; var old = await repository.FindActiveUserByPasswordAsync(login, domain, PasswordHasher.Candidates(domain, login, request.OldPassword), requireActiveCompany: false, ct); if (old is null) throw new BusinessException("OLD_PASSWORD_WRONG", OldPasswordWrongMessage); // Gap: for ASEZA legacy writes EncryptPwd.doEncryption(new); we write the SHA-1 form, which login also accepts. await repository.UpdatePasswordAsync(login, domain, PasswordHasher.Sha1Hex(login, request.NewPassword), login, ct); return new MessageResponse("PASSWORD_CHANGED", PasswordChangedMessage); } public Task SignOutAsync(ClientInfo client, CancellationToken ct) => TryAsync(() => repository.InsertLogAsync( new AuditLogEntry(currentUser.UserId, client.IpAddress, currentUser.RoleCode, LogSignOut, currentUser.Name, client.UserAgent), ct)); public Task IsUserStillActiveAsync(string login, string roleCode, CancellationToken ct) => repository.IsActiveWithRoleAsync(login, roleCode, ct); // ---- helpers ---- private async Task LogInvalidAccessAsync(AuthenticatedUser user, UserProfileRow profile, ClientInfo client, CancellationToken ct) { var ip = client.IpAddress ?? string.Empty; var locationId = user.LocationId?.ToString(); if (IpCheckedRoles.Contains(user.RoleCode, StringComparer.OrdinalIgnoreCase)) { if (locationId is null) return; var allowed = await repository.GetLocationIpsAsync(locationId, ct); if (allowed.Count > 0 && !string.IsNullOrEmpty(allowed[0]) && !allowed.Contains(ip, StringComparer.OrdinalIgnoreCase)) { var ipLocation = await repository.GetLocationForIpAsync(ip, ct); // reason 2: login from another NAFITH location, 1: from outside. await repository.InsertInvalidAccessLogAsync(new InvalidAccessEntry( profile.Id, user.LocationId, user.RoleCode, string.Join(',', allowed), ip, ipLocation, client.UserAgent, string.IsNullOrEmpty(ipLocation) ? 1 : 2), ct); } } else if (string.Equals(user.RoleCode, "DISP", StringComparison.OrdinalIgnoreCase)) { // Legacy: a dispatcher logging in from inside a NAFITH location is logged with reason 3. var ipLocation = await repository.GetLocationForIpAsync(ip, ct); if (!string.IsNullOrEmpty(ipLocation)) await repository.InsertInvalidAccessLogAsync(new InvalidAccessEntry( profile.Id, user.LocationId, "DISP", ip, ip, ipLocation, client.UserAgent, 3), ct); } } private AuthenticatedUser FromCurrent() => new( currentUser.Id, currentUser.UserId, currentUser.Name, currentUser.RoleCode, currentUser.RoleName, currentUser.Domain, currentUser.LocationId, currentUser.LocationName, currentUser.StkId, currentUser.CompId, currentUser.CompanyId, currentUser.CompanyName, currentUser.CompanyCode, currentUser.EmpNo, currentUser.Lang, currentUser.IsStaff); private static AuthenticationFailedException Invalid() => new("INVALID_CREDENTIALS", InvalidLoginMessage); private static bool IsTruthy(string? v) => v is not null && (v == "1" || v.Equals("Y", StringComparison.OrdinalIgnoreCase) || v.Equals("true", StringComparison.OrdinalIgnoreCase)); private static async Task TryAsync(Func action) { try { await action(); } catch { /* legacy swallows audit-log failures; they must never block sign-in/out */ } } }