All files / src/platform/identity identity.service.ts

0% Statements 0/182
0% Branches 0/144
0% Functions 0/17
0% Lines 0/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import {
  Injectable,
  Logger,
  UnauthorizedException,
  BadRequestException,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import * as crypto from 'crypto';
import * as bcrypt from 'bcrypt';
import {
  SocialIdentity,
  LoginAttempt,
  AccountRecoveryRequest,
  IdentityLinkHistory,
} from './schemas/identity.schema';
import { User } from '../user/schemas/user.schema';
import { RefreshToken } from '../auth/schemas/refresh-token.schema';
import {
  GoogleAuthProvider,
  GoogleAuthResult,
} from './social-auth/google-auth.provider';
import {
  AppleAuthProvider,
  AppleAuthResult,
  AppleUserInfo,
} from './social-auth/apple-auth.provider';
import { MfaService } from './mfa/mfa.service';
import {
  DeviceTrustService,
  DeviceFingerprintInput,
} from './device-trust/device-trust.service';
import { SessionService } from './sessions/session.service';
import { EventBusService } from '../events/event-bus.service';
import { AuditLogService } from '../audit/audit-log.service';
 
/**
 * Identity Service — Unified orchestrator for all identity operations.
 *
 * Coordinates:
 * - Social authentication (Google, Apple)
 * - MFA challenge flow
 * - Device trust registration
 * - Session creation
 * - Login attempt tracking
 * - Account recovery (password reset, email verification)
 *
 * Does NOT replace existing AuthService for email/password flows.
 * Extends the auth system with social login, MFA, and device trust layers.
 */
 
@Injectable()
export class IdentityService {
  private readonly logger = new Logger(IdentityService.name);
 
  constructor(
    @InjectModel(SocialIdentity.name)
    private readonly socialIdentityModel: Model<SocialIdentity>,
    @InjectModel(LoginAttempt.name)
    private readonly loginAttemptModel: Model<LoginAttempt>,
    @InjectModel(AccountRecoveryRequest.name)
    private readonly recoveryModel: Model<AccountRecoveryRequest>,
    @InjectModel(IdentityLinkHistory.name)
    private readonly linkHistoryModel: Model<IdentityLinkHistory>,
    @InjectModel(User.name) private readonly userModel: Model<User>,
    @InjectModel(RefreshToken.name)
    private readonly refreshTokenModel: Model<RefreshToken>,
    private readonly googleAuth: GoogleAuthProvider,
    private readonly appleAuth: AppleAuthProvider,
    private readonly mfaService: MfaService,
    private readonly deviceTrust: DeviceTrustService,
    private readonly sessionService: SessionService,
    private readonly eventBus: EventBusService,
    private readonly auditLog: AuditLogService,
  ) {}
 
  // ============================================================
  // SOCIAL LOGIN — Google
  // ============================================================
 
  /**
   * Authenticates or registers a user via Google Sign-In.
   *
   * Flow:
   * 1. Verify Google ID token
   * 2. Look up existing social identity or user by email
   * 3. Link identity / create user as needed
   * 4. Check MFA requirement
   * 5. Register device, create session, issue tokens
   */
  async loginWithGoogle(
    idToken: string,
    tenantId: string,
    context: {
      ipAddress?: string;
      userAgent?: string;
      fingerprint?: DeviceFingerprintInput;
    },
  ): Promise<{
    user: any;
    accessToken?: string;
    refreshToken?: string;
    sessionId?: string;
    mfaRequired?: boolean;
    mfaChallengeId?: string;
    mfaMethods?: string[];
    isNewUser: boolean;
  }> {
    // 1. Verify the Google ID token
    const googleResult = await this.googleAuth.verifyIdToken(idToken);
 
    // 2. Record login attempt
    const attemptData: Partial<LoginAttempt> = {
      email: googleResult.email,
      tenantId,
      method: 'google',
      ipAddress: context.ipAddress,
      userAgent: context.userAgent,
    };
 
    try {
      return await this.processSocialLogin(
        'google',
        googleResult,
        tenantId,
        context,
        attemptData,
      );
    } catch (error) {
      await this.recordLoginAttempt({
        ...attemptData,
        result: 'failed',
        failureReason: error.message,
      });
      throw error;
    }
  }
 
  // ============================================================
  // SOCIAL LOGIN — Apple
  // ============================================================
 
  /**
   * Authenticates or registers a user via Apple Sign-In.
   */
  async loginWithApple(
    idToken: string,
    tenantId: string,
    userInfo?: AppleUserInfo,
    context?: {
      ipAddress?: string;
      userAgent?: string;
      fingerprint?: DeviceFingerprintInput;
    },
  ): Promise<{
    user: any;
    accessToken?: string;
    refreshToken?: string;
    sessionId?: string;
    mfaRequired?: boolean;
    mfaChallengeId?: string;
    mfaMethods?: string[];
    isNewUser: boolean;
  }> {
    const appleResult = await this.appleAuth.verifyIdToken(idToken, userInfo);
 
    const attemptData: Partial<LoginAttempt> = {
      email: appleResult.email || 'private-relay@apple',
      tenantId,
      method: 'apple',
      ipAddress: context?.ipAddress,
      userAgent: context?.userAgent,
    };
 
    try {
      return await this.processSocialLogin(
        'apple',
        appleResult,
        tenantId,
        context || {},
        attemptData,
      );
    } catch (error) {
      await this.recordLoginAttempt({
        ...attemptData,
        result: 'failed',
        failureReason: error.message,
      });
      throw error;
    }
  }
 
  // ============================================================
  // IDENTITY LINKING
  // ============================================================
 
  /**
   * Links a social identity to an existing user account.
   * User must be authenticated (e.g., via email/password) before linking.
   */
  async linkSocialIdentity(
    userId: string,
    tenantId: string,
    provider: 'google' | 'apple',
    idToken: string,
    userInfo?: AppleUserInfo,
    context?: { ipAddress?: string; userAgent?: string },
  ): Promise<{ linked: boolean; provider: string }> {
    let providerUserId: string;
    let email: string | null;
    let displayName: string;
    let avatarUrl: string | null;
    let rawProfile: any;
 
    if (provider === 'google') {
      const result = await this.googleAuth.verifyIdToken(idToken);
      providerUserId = result.providerUserId;
      email = result.email;
      displayName = result.displayName;
      avatarUrl = result.avatarUrl;
      rawProfile = result.rawProfile;
    } else {
      const result = await this.appleAuth.verifyIdToken(idToken, userInfo);
      providerUserId = result.providerUserId;
      email = result.email;
      displayName = result.displayName;
      avatarUrl = null;
      rawProfile = result.rawProfile;
    }
 
    // Check if this social identity is already linked to another user
    const existingLink = await this.socialIdentityModel
      .findOne({
        provider,
        providerUserId,
      })
      .exec();
 
    if (existingLink && existingLink.userId !== userId) {
      throw new ConflictException(
        `This ${provider} account is already linked to another user`,
      );
    }
 
    if (existingLink && existingLink.userId === userId) {
      throw new BadRequestException(
        `This ${provider} account is already linked to your account`,
      );
    }
 
    // Create the link
    await this.socialIdentityModel.create({
      userId,
      tenantId,
      provider,
      providerUserId,
      email,
      displayName,
      avatarUrl,
      rawProfile,
      lastUsedAt: new Date(),
    });
 
    // Record in link history
    await this.linkHistoryModel.create({
      userId,
      tenantId,
      provider,
      providerUserId,
      action: 'linked',
      performedBy: userId,
      ipAddress: context?.ipAddress,
      userAgent: context?.userAgent,
    });
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'identity.social.linked',
      resource: 'SocialIdentity',
      metadata: { provider, providerUserId },
    });
 
    return { linked: true, provider };
  }
 
  /**
   * Unlinks a social identity from a user account.
   */
  async unlinkSocialIdentity(
    userId: string,
    tenantId: string,
    provider: 'google' | 'apple',
    context?: { ipAddress?: string; userAgent?: string },
  ): Promise<void> {
    const identity = await this.socialIdentityModel
      .findOne({
        userId,
        tenantId,
        provider,
        isRevoked: false,
      })
      .exec();
 
    if (!identity) {
      throw new NotFoundException(
        `No ${provider} identity linked to this account`,
      );
    }
 
    // Don't allow unlinking if it's the only auth method and no password is set
    const user = await this.userModel.findOne({ _id: userId }).exec();
    if (user && !user.password) {
      const otherIdentities = await this.socialIdentityModel
        .countDocuments({
          userId,
          tenantId,
          isRevoked: false,
          provider: { $ne: provider },
        })
        .exec();
 
      if (otherIdentities === 0) {
        throw new BadRequestException(
          'Cannot unlink the only authentication method. Set a password first.',
        );
      }
    }
 
    identity.isRevoked = true;
    await identity.save();
 
    await this.linkHistoryModel.create({
      userId,
      tenantId,
      provider,
      providerUserId: identity.providerUserId,
      action: 'unlinked',
      performedBy: userId,
      ipAddress: context?.ipAddress,
      userAgent: context?.userAgent,
    });
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'identity.social.unlinked',
      resource: 'SocialIdentity',
      metadata: { provider },
    });
  }
 
  /**
   * Gets all linked social identities for a user.
   */
  async getLinkedIdentities(userId: string, tenantId: string): Promise<any[]> {
    const identities = await this.socialIdentityModel
      .find({
        userId,
        tenantId,
        isRevoked: false,
      })
      .lean()
      .exec();
 
    return identities.map((i) => ({
      id: (i as any)._id.toString(),
      provider: i.provider,
      email: i.email,
      displayName: i.displayName,
      avatarUrl: i.avatarUrl,
      lastUsedAt: i.lastUsedAt,
      createdAt: i.createdAt,
    }));
  }
 
  // ============================================================
  // ACCOUNT RECOVERY
  // ============================================================
 
  /**
   * Initiates a password reset by generating a token and dispatching an email.
   */
  async initiatePasswordReset(
    email: string,
    tenantId: string,
    ipAddress?: string,
  ): Promise<{ initiated: boolean }> {
    const user = await this.userModel
      .findOne({ email: email.toLowerCase(), tenantId })
      .exec();
 
    // Always return success (don't leak user existence)
    if (!user) {
      this.logger.debug(
        `Password reset requested for non-existent email: ${email}`,
      );
      return { initiated: true };
    }
 
    // Invalidate any existing tokens
    await this.recoveryModel
      .updateMany(
        {
          userId: (user as any)._id.toString(),
          tenantId,
          type: 'password_reset',
          isUsed: false,
        },
        { isUsed: true },
      )
      .exec();
 
    const token = crypto.randomBytes(32).toString('hex');
    const expiresAt = new Date(Date.now() + 3600000); // 1 hour
 
    await this.recoveryModel.create({
      userId: (user as any)._id.toString(),
      tenantId,
      type: 'password_reset',
      token,
      expiresAt,
      ipAddress,
    });
 
    await this.eventBus.publish(
      'platform.identity.password_reset.requested.v1',
      {
        userId: (user as any)._id.toString(),
        tenantId,
        email: user.email,
        token,
        expiresAt,
      },
      tenantId,
    );
 
    return { initiated: true };
  }
 
  /**
   * Completes a password reset by verifying the token and updating the password.
   */
  async completePasswordReset(
    token: string,
    newPassword: string,
    ipAddress?: string,
  ): Promise<{ success: boolean }> {
    const request = await this.recoveryModel
      .findOne({
        token,
        type: 'password_reset',
        isUsed: false,
      })
      .exec();
 
    if (!request) {
      throw new BadRequestException('Invalid or expired password reset token');
    }
 
    if (request.expiresAt < new Date()) {
      throw new BadRequestException('Password reset token has expired');
    }
 
    // Hash the new password
    const passwordHash = await bcrypt.hash(newPassword, 12);
 
    // Update user password
    await this.userModel
      .findByIdAndUpdate(request.userId, {
        password: passwordHash,
      })
      .exec();
 
    // Mark token as used
    request.isUsed = true;
    request.usedAt = new Date();
    request.ipAddress = ipAddress ?? '';
    await request.save();
 
    // Revoke all sessions (security measure)
    await this.sessionService.revokeAllSessions(
      request.userId,
      request.tenantId,
      'Password reset',
    );
 
    await this.eventBus.publish(
      'platform.identity.password_reset.completed.v1',
      {
        userId: request.userId,
        tenantId: request.tenantId,
      },
      request.tenantId,
    );
 
    return { success: true };
  }
 
  /**
   * Initiates email verification.
   */
  async initiateEmailVerification(
    userId: string,
    tenantId: string,
    email: string,
  ): Promise<{ initiated: boolean }> {
    const token = crypto.randomBytes(32).toString('hex');
    const expiresAt = new Date(Date.now() + 86400000); // 24 hours
 
    await this.recoveryModel.create({
      userId,
      tenantId,
      type: 'email_verification',
      token,
      expiresAt,
    });
 
    await this.eventBus.publish(
      'platform.identity.email_verification.requested.v1',
      {
        userId,
        tenantId,
        email,
        token,
        expiresAt,
      },
      tenantId,
    );
 
    return { initiated: true };
  }
 
  /**
   * Completes email verification.
   */
  async completeEmailVerification(
    token: string,
  ): Promise<{ verified: boolean }> {
    const request = await this.recoveryModel
      .findOne({
        token,
        type: 'email_verification',
        isUsed: false,
      })
      .exec();
 
    if (!request || request.expiresAt < new Date()) {
      throw new BadRequestException(
        'Invalid or expired email verification token',
      );
    }
 
    await this.userModel
      .findByIdAndUpdate(request.userId, {
        isEmailVerified: true,
      })
      .exec();
 
    request.isUsed = true;
    request.usedAt = new Date();
    await request.save();
 
    await this.eventBus.publish(
      'platform.identity.email.verified.v1',
      {
        userId: request.userId,
        tenantId: request.tenantId,
      },
      request.tenantId,
    );
 
    return { verified: true };
  }
 
  // ============================================================
  // LOGIN ATTEMPT TRACKING
  // ============================================================
 
  /**
   * Gets recent login attempts for a user.
   */
  async getLoginHistory(
    userId: string,
    tenantId: string,
    limit = 20,
  ): Promise<any[]> {
    return this.loginAttemptModel
      .find({ userId, tenantId })
      .sort({ createdAt: -1 })
      .limit(limit)
      .lean()
      .exec();
  }
 
  // ============================================================
  // PRIVATE HELPERS
  // ============================================================
 
  /**
   * Core social login processing shared by Google and Apple.
   */
  private async processSocialLogin(
    provider: 'google' | 'apple',
    authResult: GoogleAuthResult | AppleAuthResult,
    tenantId: string,
    context: {
      ipAddress?: string;
      userAgent?: string;
      fingerprint?: DeviceFingerprintInput;
    },
    attemptData: Partial<LoginAttempt>,
  ): Promise<any> {
    // Look up existing social identity
    let socialIdentity = await this.socialIdentityModel
      .findOne({
        provider,
        providerUserId: authResult.providerUserId,
        tenantId,
        isRevoked: false,
      })
      .exec();
 
    let user: User | null = null;
    const isNewUser = false;
 
    if (socialIdentity) {
      // Existing social identity — fetch the linked user
      user = await this.userModel.findById(socialIdentity.userId).exec();
      if (!user) {
        throw new UnauthorizedException('User account not found');
      }
 
      // Update social identity usage
      socialIdentity.lastUsedAt = new Date();
      if ('avatarUrl' in authResult && authResult.avatarUrl) {
        socialIdentity.avatarUrl = authResult.avatarUrl;
      }
      await socialIdentity.save();
    } else if (authResult.email) {
      // No social identity — try to find user by email
      user = await this.userModel
        .findOne({
          email: authResult.email.toLowerCase(),
          tenantId,
        })
        .exec();
 
      if (user) {
        // User exists — auto-link the social identity
        socialIdentity = await this.socialIdentityModel.create({
          userId: (user as any)._id.toString(),
          tenantId,
          provider,
          providerUserId: authResult.providerUserId,
          email: authResult.email,
          displayName: authResult.displayName,
          avatarUrl: 'avatarUrl' in authResult ? authResult.avatarUrl : null,
          rawProfile: authResult.rawProfile,
          lastUsedAt: new Date(),
        });
 
        await this.linkHistoryModel.create({
          userId: (user as any)._id.toString(),
          tenantId,
          provider,
          providerUserId: authResult.providerUserId,
          action: 'linked',
          performedBy: (user as any)._id.toString(),
          reason: 'Auto-linked on social login',
        });
      } else {
        // No user — create new user via social registration
        // NOTE: For multi-tenant systems, the tenant must exist and allow registration.
        // This creates a basic user; tenant setup (roles, subscription) is handled
        // by the existing AuthService registration flow or a dedicated onboarding flow.
        throw new BadRequestException(
          `No account found for ${authResult.email} in this organization. ` +
            'Please register first or contact your administrator.',
        );
      }
    } else {
      throw new UnauthorizedException(
        'Unable to identify user from social login',
      );
    }
 
    if (!user || !user.isActive) {
      throw new UnauthorizedException('Account is disabled');
    }
 
    const userId = (user as any)._id.toString();
 
    // Check MFA requirement
    const mfaEnabled = await this.mfaService.isMfaEnabled(userId, tenantId);
    const mfaRequired = await this.mfaService.isMfaRequired(
      tenantId,
      user.roles || [],
    );
 
    if (mfaEnabled || mfaRequired) {
      const methods = await this.mfaService.getEnrolledMethods(
        userId,
        tenantId,
      );
      const primaryMethod = methods.find((m) => m.isPrimary) || methods[0];
 
      if (primaryMethod) {
        const challenge = await this.mfaService.createChallenge(
          userId,
          tenantId,
          primaryMethod.type,
          { ipAddress: context.ipAddress, userAgent: context.userAgent },
        );
 
        await this.recordLoginAttempt({
          ...attemptData,
          userId,
          result: 'mfa_required',
        });
 
        return {
          user: { id: userId, email: user.email },
          mfaRequired: true,
          mfaChallengeId: challenge.challengeId,
          mfaMethods: methods.map((m) => m.type),
          isNewUser: false,
        };
      }
    }
 
    // No MFA required — proceed to session creation
    await this.recordLoginAttempt({
      ...attemptData,
      userId,
      result: 'success',
    });
 
    // Register device if fingerprint provided
    if (context.fingerprint) {
      const deviceResult = await this.deviceTrust.registerDevice(
        userId,
        tenantId,
        context.fingerprint,
        { ipAddress: context.ipAddress, userAgent: context.userAgent },
      );
 
      // Auto-trust device on social login (already verified by provider)
      if (deviceResult.isNew || !deviceResult.isTrusted) {
        await this.deviceTrust.trustDevice(
          userId,
          tenantId,
          deviceResult.deviceId,
          90,
        );
      }
    }
 
    // Update user's last login
    user.lastLoginAt = new Date();
    if ('avatarUrl' in authResult && authResult.avatarUrl && !user.avatar) {
      user.avatar = authResult.avatarUrl;
    }
    await user.save();
 
    // Create session (tokens will be generated by the auth controller)
    const refreshToken = crypto.randomBytes(64).toString('hex');
    const refreshTokenHash = crypto
      .createHash('sha256')
      .update(refreshToken)
      .digest('hex');
    const expiresAt = new Date(Date.now() + 7 * 86400000); // 7 days
 
    const session = await this.sessionService.createSession({
      userId,
      tenantId,
      refreshTokenHash,
      deviceId: context.fingerprint
        ? this.deviceTrust.generateDeviceId(context.fingerprint)
        : undefined,
      browser: context.userAgent
        ? this.extractBrowser(context.userAgent)
        : undefined,
      ipAddress: context.ipAddress,
      loginMethod: provider,
      expiresAt,
    });
 
    // Store the refresh token for existing auth flow compatibility
    await this.refreshTokenModel.create({
      token: refreshToken,
      userId,
      expiresAt,
      isRevoked: false,
    });
 
    await this.eventBus.publish(
      'platform.identity.social_login.success.v1',
      {
        userId,
        tenantId,
        provider,
        isNewUser,
      },
      tenantId,
    );
 
    return {
      user: {
        id: userId,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        avatar: user.avatar,
        roles: user.roles,
      },
      refreshToken,
      sessionId: session.sessionId,
      mfaRequired: false,
      isNewUser,
    };
  }
 
  /**
   * Records a login attempt.
   */
  private async recordLoginAttempt(data: Partial<LoginAttempt>): Promise<void> {
    try {
      await this.loginAttemptModel.create(data);
    } catch (err) {
      this.logger.error(`Failed to record login attempt: ${err.message}`);
    }
  }
 
  private extractBrowser(userAgent?: string): string | undefined {
    if (!userAgent) return undefined;
    if (userAgent.includes('Chrome') && !userAgent.includes('Edg'))
      return 'Chrome';
    if (userAgent.includes('Safari') && !userAgent.includes('Chrome'))
      return 'Safari';
    if (userAgent.includes('Firefox')) return 'Firefox';
    if (userAgent.includes('Edg')) return 'Edge';
    return 'Other';
  }
}