27 lines
767 B
TypeScript
27 lines
767 B
TypeScript
|
import { OAuth2AccessToken } from '@icynet/oauth2-provider';
|
||
|
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||
|
import { Reflector } from '@nestjs/core';
|
||
|
|
||
|
/**
|
||
|
* Validates OAuth2 scopes.
|
||
|
*/
|
||
|
@Injectable()
|
||
|
export class ScopesGuard implements CanActivate {
|
||
|
constructor(private reflector: Reflector) {}
|
||
|
|
||
|
canActivate(context: ExecutionContext): boolean {
|
||
|
const scopes = this.reflector.get<string[]>('scopes', context.getHandler());
|
||
|
if (!scopes) {
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
const response = context.switchToHttp().getResponse();
|
||
|
const accessToken = response.locals.accessToken as OAuth2AccessToken;
|
||
|
if (!accessToken) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
return scopes.every((scope) => accessToken.scope.includes(scope));
|
||
|
}
|
||
|
}
|