34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
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;
|
|
}
|
|
}
|