Spaces:
Runtime error
Runtime error
File size: 12,137 Bytes
f3abb0d b1ced28 add3ead f3abb0d add3ead f3abb0d add3ead f3abb0d b1ced28 f3abb0d add3ead f3abb0d add3ead f3abb0d b1ced28 f3abb0d add3ead f3abb0d b1ced28 f3abb0d b1ced28 f3abb0d b1ced28 f3abb0d | 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 | import {
Injectable,
UnauthorizedException,
ConflictException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { SuperAdmin, SESSION_STATUS } from '@prisma/client';
import { StringValue } from 'ms';
import { SuperAdminCoreService } from 'src/core/super-admin-core/super-admin-core.service';
import { SuperAdminCredentialCoreService } from 'src/core/super-admin-credential-core/super-admin-credential-core.service';
import { SuperAdminSessionCoreService } from 'src/core/super-admin-session-core/super-admin-session-core.service';
import { SuperAdminTwoFactorMethodCoreService } from 'src/core/super-admin-two-factor-method-core/super-admin-two-factor-method-core.service';
import { SuperAdminTrustedDeviceCoreService } from 'src/core/super-admin-trusted-device-core/super-admin-trusted-device-core.service';
import { CommonService } from 'src/shared/modules/common/common.service';
import { SuperAdminRegisterDto } from './dto/register.dto';
import { SuperAdminLoginDto } from './dto/login.dto';
import { SuperAdminRefreshTokenDto } from './dto/refresh-token.dto';
import { SuperAdminSessionType } from 'src/shared/types/super-admin-session.type';
import {
accessTokenSignSettings,
refreshTokenSignSettings,
refreshTokenVerifySettings,
TOKEN_TYPE,
TOKEN_USER_TYPE,
AuthMessages,
} from 'src/shared/keys/auth.keys';
@Injectable()
export class SuperAdminAuthService {
constructor(
private readonly jwtService: JwtService,
private readonly superAdminCoreService: SuperAdminCoreService,
private readonly superAdminCredentialCoreService: SuperAdminCredentialCoreService,
private readonly superAdminSessionCoreService: SuperAdminSessionCoreService,
private readonly twoFactorMethodCoreService: SuperAdminTwoFactorMethodCoreService,
private readonly trustedDeviceCoreService: SuperAdminTrustedDeviceCoreService,
private readonly commonService: CommonService,
) {}
async register(
registerDto: SuperAdminRegisterDto,
request: any,
): Promise<{
superAdmin: SuperAdmin;
accessToken: string;
refreshToken: string;
}> {
const { email, password, name, profileImage } = registerDto;
// Check if super admin already exists
const existingSuperAdmin = await this.superAdminCoreService
.findFirst({
where: { email, isDeleted: false },
})
.catch(() => null);
if (existingSuperAdmin) {
throw new ConflictException('Super admin with this email already exists');
}
// Create super admin
const superAdmin = await this.superAdminCoreService.create({
data: {
email,
name,
profileImage,
},
});
// Hash and store password
const hashedPassword = await this.commonService.hashPassword(password);
await this.superAdminCredentialCoreService.create({
data: {
superAdminId: superAdmin.id,
password: hashedPassword,
},
});
// Generate tokens
const { accessToken, refreshToken } = await this.getNewToken(superAdmin);
// Get client info
const clientInfo = this.commonService.getClientInfo(request);
// Create session
await this.superAdminSessionCoreService.create({
data: {
superAdminId: superAdmin.id,
accessToken,
refreshToken,
ipAddress: clientInfo.ipAddress,
userAgent: clientInfo.userAgent,
geoIpCountry: clientInfo.geoLocation?.country || '',
city: clientInfo.geoLocation?.city || '',
state: clientInfo.geoLocation?.region || '',
latitude: clientInfo.geoLocation?.ll?.[0] || null,
longitude: clientInfo.geoLocation?.ll?.[1] || null,
isFromAdmin: true,
status: SESSION_STATUS.CURRENT,
loginAt: new Date(),
},
});
return {
superAdmin,
accessToken,
refreshToken,
};
}
async login(
loginDto: SuperAdminLoginDto,
request: any,
): Promise<
| {
superAdmin: SuperAdmin;
accessToken: string;
refreshToken: string;
}
| {
requires2FA: true;
pending2faToken: string;
availableMethods: string[];
message: string;
}
> {
const { email, password, deviceId } = loginDto;
// Find super admin
const superAdmin = await this.superAdminCoreService
.findFirst({
where: { email, isDeleted: false },
})
.catch(() => null);
if (!superAdmin) {
throw new UnauthorizedException('Invalid credentials');
}
// Get super admin credential
const credential = await this.superAdminCredentialCoreService
.findFirst({
where: { superAdminId: superAdmin.id, isDeleted: false },
})
.catch(() => null);
if (!credential) {
throw new UnauthorizedException('Invalid credentials');
}
// Verify password
const isPasswordValid = await this.commonService.comparePassword(
password,
credential.password,
);
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid credentials');
}
// Check if 2FA is enabled
if (superAdmin.isTwoFactorEnabled) {
// Check if device is trusted (skip 2FA)
if (deviceId) {
const trustedDevice = await this.checkTrustedDevice(
superAdmin.id,
deviceId,
);
if (trustedDevice) {
// Device is trusted, proceed with normal login
return await this.completeLogin(superAdmin, request);
}
}
// Require 2FA verification
const enabledMethods = await this.getEnabled2FAMethods(superAdmin.id);
if (enabledMethods.length === 0) {
// No 2FA methods enabled, proceed with normal login
return await this.completeLogin(superAdmin, request);
}
// Generate pending 2FA token
const pending2FATokenSettings = {
secret: process.env.PENDING_2FA_TOKEN_SECRET,
expiresIn: (process.env.PENDING_2FA_TOKEN_EXPIRY ||
'10m') as StringValue,
};
const pending2faToken = await this.jwtService.signAsync(
{
superAdminId: superAdmin.id,
type: 'PENDING_2FA',
},
pending2FATokenSettings,
);
return {
requires2FA: true,
pending2faToken,
availableMethods: enabledMethods,
message:
'Two-factor authentication required. Please verify using one of the available methods.',
};
}
// 2FA not enabled, proceed with normal login
return await this.completeLogin(superAdmin, request);
}
private async completeLogin(
superAdmin: SuperAdmin,
request: any,
): Promise<{
superAdmin: SuperAdmin;
accessToken: string;
refreshToken: string;
}> {
// Generate tokens
const { accessToken, refreshToken } = await this.getNewToken(superAdmin);
// Get client info
const clientInfo = this.commonService.getClientInfo(request);
// Create session
await this.superAdminSessionCoreService.create({
data: {
superAdminId: superAdmin.id,
accessToken,
refreshToken,
ipAddress: clientInfo.ipAddress,
userAgent: clientInfo.userAgent,
geoIpCountry: clientInfo.geoLocation?.country || '',
city: clientInfo.geoLocation?.city || '',
state: clientInfo.geoLocation?.region || '',
latitude: clientInfo.geoLocation?.ll?.[0] || null,
longitude: clientInfo.geoLocation?.ll?.[1] || null,
isFromAdmin: true,
status: SESSION_STATUS.CURRENT,
loginAt: new Date(),
},
});
return {
superAdmin,
accessToken,
refreshToken,
};
}
private async checkTrustedDevice(
superAdminId: string,
deviceId: string,
): Promise<boolean> {
try {
const device = await this.trustedDeviceCoreService.findFirst({
where: {
deviceId,
superAdminId,
isDeleted: false,
},
});
if (!device) {
return false;
}
// Check if device is still valid (not expired)
const now = new Date();
if (device.expiresAt < now) {
return false;
}
// Update last used timestamp
await this.trustedDeviceCoreService.update({
where: { id: device.id },
data: { lastUsedAt: now },
});
return true;
} catch {
return false;
}
}
private async getEnabled2FAMethods(superAdminId: string): Promise<string[]> {
try {
const methods = await this.twoFactorMethodCoreService.findMany({
where: {
superAdminId,
isEnabled: true,
isDeleted: false,
},
});
return methods.map((method) => method.type);
} catch {
return [];
}
}
async logout(
sessionData: SuperAdminSessionType,
): Promise<{ message: string }> {
const { session } = sessionData;
// Update session to expired
await this.superAdminSessionCoreService.update({
where: { id: session.id },
data: {
status: SESSION_STATUS.EXPIRED,
expiredAt: new Date(),
},
});
return { message: AuthMessages.LOGOUT_SUCCESS };
}
async refreshToken(refreshTokenDto: SuperAdminRefreshTokenDto): Promise<{
accessToken: string;
refreshToken: string;
}> {
const { refreshToken } = refreshTokenDto;
let validateRefreshToken: any = null;
try {
validateRefreshToken = await this.jwtService.verifyAsync(
refreshToken,
refreshTokenVerifySettings,
);
} catch {
throw new UnauthorizedException('Invalid refresh token');
}
// Verify user type
if (validateRefreshToken.userType !== TOKEN_USER_TYPE.SUPER_ADMIN) {
throw new UnauthorizedException('Invalid token type');
}
const superAdmin = await this.superAdminCoreService.findUnique({
where: { id: validateRefreshToken.id, isDeleted: false },
});
if (!superAdmin) {
throw new UnauthorizedException('Super admin not found');
}
// Generate new tokens
const newTokens = await this.getNewToken(superAdmin);
// Update session with new tokens
await this.superAdminSessionCoreService.updateMany({
where: {
superAdminId: superAdmin.id,
refreshToken,
status: SESSION_STATUS.CURRENT,
},
data: {
accessToken: newTokens.accessToken,
refreshToken: newTokens.refreshToken,
},
});
return newTokens;
}
private async getNewToken(superAdmin: SuperAdmin): Promise<{
accessToken: string;
refreshToken: string;
}> {
const payload = {
id: superAdmin.id,
email: superAdmin.email,
userType: TOKEN_USER_TYPE.SUPER_ADMIN,
};
const accessToken = await this.jwtService.signAsync(
{ ...payload, type: TOKEN_TYPE.ACCESS },
accessTokenSignSettings,
);
const refreshToken = await this.jwtService.signAsync(
{ ...payload, type: TOKEN_TYPE.REFRESH },
refreshTokenSignSettings,
);
return { accessToken, refreshToken };
}
async performJWTStrategy({
request,
superAdmin,
}: {
request: Request & { headers: { authorization: string } };
superAdmin: SuperAdmin;
}): Promise<SuperAdminSessionType> {
const accessToken = request.headers.authorization?.replace('Bearer ', '');
if (!accessToken) {
throw new UnauthorizedException('Invalid token');
}
// Get full super admin object
const fullSuperAdmin = await this.superAdminCoreService.findUnique({
where: { id: superAdmin.id, isDeleted: false },
});
if (!fullSuperAdmin) {
throw new UnauthorizedException('Super admin not found');
}
// Find active session
const session = await this.superAdminSessionCoreService.findFirst({
where: {
superAdminId: superAdmin.id,
accessToken,
status: SESSION_STATUS.CURRENT,
isDeleted: false,
},
});
if (!session) {
throw new UnauthorizedException('Session not found or expired');
}
return {
superAdmin: fullSuperAdmin,
session,
};
}
}
|