feat(api): add auth guards
This commit is contained in:
1 parent
3a86676a12
commit
d4b790fd86
16 files changed
+592
No files matched your search
@@ -0,0 +1,62 @@
|
||||
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';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user