All files / src/interfaces/web-api/company-admin identity.controller.ts

0% Statements 0/104
0% Branches 0/36
0% Functions 0/36
0% Lines 0/92

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import {
  Controller,
  Post,
  Get,
  Delete,
  Put,
  Body,
  Param,
  Req,
  UseGuards,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { IdentityService } from '../../../platform/identity/identity.service';
import { MfaService } from '../../../platform/identity/mfa/mfa.service';
import { DeviceTrustService } from '../../../platform/identity/device-trust/device-trust.service';
import { SessionService } from '../../../platform/identity/sessions/session.service';
import { JwtAuthGuard } from '../../../platform/auth/jwt-auth.guard';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
 
// ============================================================
// DTOs
// ============================================================
 
class SocialLoginDto {
  idToken: string;
  firstName?: string; // Apple only (first auth)
  lastName?: string; // Apple only (first auth)
  fingerprint?: any; // Device fingerprint for trust
}
 
class LinkSocialDto {
  idToken: string;
  firstName?: string;
  lastName?: string;
}
 
class MfaEnrollTotpVerifyDto {
  code: string;
}
 
class MfaVerifyChallengeDto {
  challengeId: string;
  code: string;
}
 
class MfaCreateChallengeDto {
  method: 'totp' | 'email_otp' | 'backup_code';
}
 
class UpdateMfaPolicyDto {
  isEnabled?: boolean;
  isEnforcedForAll?: boolean;
  enforcedRoles?: string[];
  allowedMethods?: string[];
  gracePeriodDays?: number;
  backupCodeCount?: number;
}
 
class PasswordResetInitDto {
  email: string;
}
 
class PasswordResetCompleteDto {
  token: string;
  newPassword: string;
}
 
class EmailVerifyCompleteDto {
  token: string;
}
 
// ============================================================
// SOCIAL AUTH CONTROLLER (Public — no JWT required)
// ============================================================
 
@Controller('api/v1/auth')
@ApiTags('IdentityAuth')
export class IdentityAuthController {
  constructor(private readonly identityService: IdentityService) {}
 
  @Post('google')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Login with google operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async loginWithGoogle(@Body() body: SocialLoginDto, @Req() req: any) {
    const tenantId = req.headers['x-tenant-id'] || '';
    return this.identityService.loginWithGoogle(body.idToken, tenantId, {
      ipAddress: req.ip,
      userAgent: req.headers['user-agent'],
      fingerprint: body.fingerprint,
    });
  }
 
  @Post('apple')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Login with apple operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async loginWithApple(@Body() body: SocialLoginDto, @Req() req: any) {
    const tenantId = req.headers['x-tenant-id'] || '';
    return this.identityService.loginWithApple(
      body.idToken,
      tenantId,
      { firstName: body.firstName, lastName: body.lastName },
      {
        ipAddress: req.ip,
        userAgent: req.headers['user-agent'],
        fingerprint: body.fingerprint,
      },
    );
  }
 
  @Post('password-reset/initiate')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Initiate password reset operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async initiatePasswordReset(
    @Body() body: PasswordResetInitDto,
    @Req() req: any,
  ) {
    const tenantId = req.headers['x-tenant-id'] || '';
    return this.identityService.initiatePasswordReset(
      body.email,
      tenantId,
      req.ip,
    );
  }
 
  @Post('password-reset/complete')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Complete password reset operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async completePasswordReset(
    @Body() body: PasswordResetCompleteDto,
    @Req() req: any,
  ) {
    return this.identityService.completePasswordReset(
      body.token,
      body.newPassword,
      req.ip,
    );
  }
 
  @Post('email-verify')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Verify email operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async verifyEmail(@Body() body: EmailVerifyCompleteDto) {
    return this.identityService.completeEmailVerification(body.token);
  }
}
 
// ============================================================
// MFA CONTROLLER (Authenticated routes)
// ============================================================
 
@Controller('api/v1/identity/mfa')
@UseGuards(JwtAuthGuard)
@ApiTags('Mfa')
export class MfaController {
  constructor(
    private readonly mfaService: MfaService,
    private readonly identityService: IdentityService,
  ) {}
 
  @Get('methods')
  @ApiOperation({ summary: 'Get methods operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getMethods(@Req() req: any) {
    return this.mfaService.getEnrolledMethods(
      req.user.userId,
      req.user.tenantId,
    );
  }
 
  @Get('status')
  @ApiOperation({ summary: 'Get mfa status operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getMfaStatus(@Req() req: any) {
    const [isEnabled, isRequired, methods] = await Promise.all([
      this.mfaService.isMfaEnabled(req.user.userId, req.user.tenantId),
      this.mfaService.isMfaRequired(req.user.tenantId, req.user.roles || []),
      this.mfaService.getEnrolledMethods(req.user.userId, req.user.tenantId),
    ]);
    const remainingCodes = await this.mfaService.getRemainingRecoveryCodeCount(
      req.user.userId,
      req.user.tenantId,
    );
 
    return {
      isEnabled,
      isRequired,
      methods,
      remainingRecoveryCodes: remainingCodes,
    };
  }
 
  // TOTP enrollment
  @Post('totp/enroll')
  @ApiOperation({ summary: 'Enroll totp operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async enrollTotp(@Req() req: any) {
    return this.mfaService.enrollTotp(
      req.user.userId,
      req.user.tenantId,
      req.user.email,
    );
  }
 
  @Post('totp/verify')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Verify totp enrollment operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async verifyTotpEnrollment(
    @Body() body: MfaEnrollTotpVerifyDto,
    @Req() req: any,
  ) {
    return this.mfaService.verifyTotpEnrollment(
      req.user.userId,
      req.user.tenantId,
      body.code,
    );
  }
 
  // Email OTP enrollment
  @Post('email-otp/enroll')
  @ApiOperation({ summary: 'Enroll email otp operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async enrollEmailOtp(@Req() req: any) {
    return this.mfaService.enrollEmailOtp(req.user.userId, req.user.tenantId);
  }
 
  // Challenge flow (used during login when MFA is required)
  @Post('challenge')
  @ApiOperation({ summary: 'Create challenge operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async createChallenge(@Body() body: MfaCreateChallengeDto, @Req() req: any) {
    return this.mfaService.createChallenge(
      req.user.userId,
      req.user.tenantId,
      body.method,
      { ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    );
  }
 
  @Post('challenge/verify')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Verify challenge operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async verifyChallenge(@Body() body: MfaVerifyChallengeDto, @Req() req: any) {
    return this.mfaService.verifyChallenge(
      req.user.userId,
      req.user.tenantId,
      body.challengeId,
      body.code,
      { ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    );
  }
 
  // Recovery codes
  @Post('recovery-codes/generate')
  @ApiOperation({ summary: 'Generate recovery codes operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async generateRecoveryCodes(@Req() req: any) {
    return this.mfaService.generateRecoveryCodes(
      req.user.userId,
      req.user.tenantId,
    );
  }
 
  @Get('recovery-codes/count')
  @ApiOperation({ summary: 'Get recovery code count operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getRecoveryCodeCount(@Req() req: any) {
    const count = await this.mfaService.getRemainingRecoveryCodeCount(
      req.user.userId,
      req.user.tenantId,
    );
    return { remaining: count };
  }
 
  // Disable MFA method
  @Delete('methods/:type')
  @ApiOperation({ summary: 'Disable method operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async disableMethod(@Param('type') type: string, @Req() req: any) {
    await this.mfaService.disableMethod(
      req.user.userId,
      req.user.tenantId,
      type,
    );
    return { disabled: true };
  }
}
 
// ============================================================
// MFA POLICY CONTROLLER (Admin only)
// ============================================================
 
@Controller('api/v1/identity/mfa/policy')
@UseGuards(JwtAuthGuard)
@ApiTags('MfaPolicy')
export class MfaPolicyController {
  constructor(private readonly mfaService: MfaService) {}
 
  @Get()
  @ApiOperation({ summary: 'Get policy operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getPolicy(@Req() req: any) {
    return this.mfaService.getPolicy(req.user.tenantId);
  }
 
  @Put()
  @ApiOperation({ summary: 'Update policy operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async updatePolicy(@Body() body: UpdateMfaPolicyDto, @Req() req: any) {
    return this.mfaService.updatePolicy(
      req.user.tenantId,
      body,
      req.user.userId,
    );
  }
}
 
// ============================================================
// DEVICE TRUST CONTROLLER
// ============================================================
 
@Controller('api/v1/identity/devices')
@UseGuards(JwtAuthGuard)
@ApiTags('DeviceTrust')
export class DeviceTrustController {
  constructor(private readonly deviceTrust: DeviceTrustService) {}
 
  @Get()
  @ApiOperation({ summary: 'List devices operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async listDevices(@Req() req: any) {
    return this.deviceTrust.getUserDevices(req.user.userId, req.user.tenantId);
  }
 
  @Delete(':deviceId')
  @ApiOperation({ summary: 'Revoke device operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async revokeDevice(@Param('deviceId') deviceId: string, @Req() req: any) {
    await this.deviceTrust.revokeDevice(
      req.user.userId,
      req.user.tenantId,
      deviceId,
      req.user.userId,
    );
    return { revoked: true };
  }
 
  @Delete()
  @ApiOperation({ summary: 'Revoke all devices operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async revokeAllDevices(@Req() req: any) {
    const count = await this.deviceTrust.revokeAllDevices(
      req.user.userId,
      req.user.tenantId,
      'User revoked all devices',
    );
    return { revokedCount: count };
  }
 
  @Get('risk-events')
  @ApiOperation({ summary: 'Get risk events operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getRiskEvents(@Req() req: any) {
    return this.deviceTrust.getRiskEvents(req.user.userId, req.user.tenantId);
  }
}
 
// ============================================================
// SESSION CONTROLLER
// ============================================================
 
@Controller('api/v1/identity/sessions')
@UseGuards(JwtAuthGuard)
@ApiTags('Session')
export class SessionController {
  constructor(private readonly sessionService: SessionService) {}
 
  @Get()
  @ApiOperation({ summary: 'List sessions operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async listSessions(@Req() req: any) {
    return this.sessionService.getUserSessions(
      req.user.userId,
      req.user.tenantId,
      req.user.sessionId,
    );
  }
 
  @Delete(':sessionId')
  @ApiOperation({ summary: 'Revoke session operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async revokeSession(@Param('sessionId') sessionId: string, @Req() req: any) {
    await this.sessionService.revokeSession(
      sessionId,
      req.user.userId,
      'User revoked session',
    );
    return { revoked: true };
  }
 
  @Post('revoke-others')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Revoke other sessions operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async revokeOtherSessions(@Req() req: any) {
    const count = await this.sessionService.revokeOtherSessions(
      req.user.userId,
      req.user.tenantId,
      req.user.sessionId,
    );
    return { revokedCount: count };
  }
 
  @Get(':sessionId/activity')
  @ApiOperation({ summary: 'Get session activity operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getSessionActivity(@Param('sessionId') sessionId: string) {
    return this.sessionService.getSessionActivity(sessionId);
  }
}
 
// ============================================================
// IDENTITY LINKING CONTROLLER
// ============================================================
 
@Controller('api/v1/identity/social')
@UseGuards(JwtAuthGuard)
@ApiTags('IdentityLink')
export class IdentityLinkController {
  constructor(private readonly identityService: IdentityService) {}
 
  @Get()
  @ApiOperation({ summary: 'Get linked identities operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getLinkedIdentities(@Req() req: any) {
    return this.identityService.getLinkedIdentities(
      req.user.userId,
      req.user.tenantId,
    );
  }
 
  @Post('google/link')
  @ApiOperation({ summary: 'Link google operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async linkGoogle(@Body() body: LinkSocialDto, @Req() req: any) {
    return this.identityService.linkSocialIdentity(
      req.user.userId,
      req.user.tenantId,
      'google',
      body.idToken,
      undefined,
      { ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    );
  }
 
  @Post('apple/link')
  @ApiOperation({ summary: 'Link apple operation' })
  @ApiResponse({ status: 201, description: 'Operation successful' })
  async linkApple(@Body() body: LinkSocialDto, @Req() req: any) {
    return this.identityService.linkSocialIdentity(
      req.user.userId,
      req.user.tenantId,
      'apple',
      body.idToken,
      { firstName: body.firstName, lastName: body.lastName },
      { ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    );
  }
 
  @Delete(':provider/unlink')
  @ApiOperation({ summary: 'Unlink provider operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async unlinkProvider(
    @Param('provider') provider: 'google' | 'apple',
    @Req() req: any,
  ) {
    await this.identityService.unlinkSocialIdentity(
      req.user.userId,
      req.user.tenantId,
      provider,
      { ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    );
    return { unlinked: true };
  }
 
  @Get('login-history')
  @ApiOperation({ summary: 'Get login history operation' })
  @ApiResponse({ status: 200, description: 'Operation successful' })
  async getLoginHistory(@Req() req: any) {
    return this.identityService.getLoginHistory(
      req.user.userId,
      req.user.tenantId,
    );
  }
}