60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import type { Request } from 'express';
|
|
import mongoose from 'mongoose';
|
|
import { ConnectionService } from '../global/database/connection.service';
|
|
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
|
import { SecretService } from '../global/secret/secret.service';
|
|
import './auth-request';
|
|
|
|
interface DevFallbackResult {
|
|
user: UserDocument;
|
|
identity?: IdentityDocument;
|
|
}
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private readonly connectionService: ConnectionService,
|
|
private readonly secretService: SecretService,
|
|
) {}
|
|
|
|
public async resolveDevFallbackFromRequest(
|
|
req: Request,
|
|
): Promise<DevFallbackResult | null> {
|
|
if (!(await this.isDevHeaderEnabled())) return null;
|
|
const header = req.headers['x-auth-user-id'];
|
|
const userId = Array.isArray(header) ? header[0] : header;
|
|
return this.resolveDevUserById(userId);
|
|
}
|
|
|
|
public async resolveDevUserById(
|
|
userId: unknown,
|
|
): Promise<DevFallbackResult | null> {
|
|
if (!(await this.isDevHeaderEnabled())) return null;
|
|
if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) {
|
|
return null;
|
|
}
|
|
|
|
const UserModel = await this.connectionService.getModel('user');
|
|
const user = await UserModel.findById(userId).exec();
|
|
if (!user) return null;
|
|
|
|
const result: DevFallbackResult = { user };
|
|
if (user.identityId) {
|
|
const IdentityModel = await this.connectionService.getModel('identity');
|
|
const identity = await IdentityModel.findById(user.identityId).exec();
|
|
if (identity) result.identity = identity;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private async isDevHeaderEnabled(): Promise<boolean> {
|
|
if (process.env.NODE_ENV === 'prod') return false;
|
|
const value = await this.secretService.get<string>(
|
|
'AUTH_DEV_HEADER_ENABLED',
|
|
process.env.AUTH_DEV_HEADER_ENABLED ?? 'false',
|
|
);
|
|
return value === 'true';
|
|
}
|
|
}
|