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,33 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class UserResolverGuard implements CanActivate {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const communityId = request.params?.communityId;
|
||||
|
||||
if (
|
||||
request.user ||
|
||||
!request.identity ||
|
||||
typeof communityId !== 'string' ||
|
||||
!mongoose.isValidObjectId(communityId)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findOne({
|
||||
communityId: new mongoose.Types.ObjectId(communityId),
|
||||
identityId: request.identity._id,
|
||||
}).exec();
|
||||
|
||||
if (user) request.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user