Hey folks! I need to build a reusable delete guard which will basically don't allow anyone but admin or an author of a specific document to delete that document. This is how my guard looks like for a note:
@Injectable()
export class DeleteGuard implements CanActivate {
constructor(
private readonly notesService: NotesService,
private readonly i18n: I18nService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const { user } = request;
// If user is an admin, they can delete all notes
if (user.role === 'ADMIN') {
return true;
}
// If user is not an admin, we have to fetch the note to determine if they can delete it
const note = await this.notesService.findOne(request.params.id);
// Users can delete their own notes
if (user.id === note.author.id) {
return true;
}
throw new UnauthorizedException('You cannot delete this note');
}
}
Now, I need the same thing for all other kinds of documents in my app (there's like 20 of them). How would you make that guard reusable considering that for each kind of document I'd need to call a method from a service specific to that document type in order to determine who the author of the document is? Thank you upfront!