Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Use local scope guards (https://stackoverflow.com/a/50801832/1656944)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Oct 23, 2020
1 parent 97621a7 commit 6a31e88
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/modules/auth/scope.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { SetMetadata } from '@nestjs/common';

export const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes);
14 changes: 10 additions & 4 deletions src/modules/auth/scope.guard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AccessTokenParsed } from './auth.interface';
import { AccessTokenParsed, UserRequest } from './auth.interface';
import minimatch from 'minimatch';

@Injectable()
Expand All @@ -9,10 +9,16 @@ export class ScopesGuard implements CanActivate {

canActivate(context: ExecutionContext): boolean {
const scopes = this.reflector.get<string[]>('scopes', context.getHandler());
console.log(scopes);
if (!scopes) return true;
const request = context.switchToHttp().getRequest();
const request = context.switchToHttp().getRequest<UserRequest>();
const user: AccessTokenParsed = request.user;
// return user.scopes.includes(scopes);
let authorized = false;
for (const userScope of user.scopes) {
for (const scope of scopes) {
authorized = authorized || minimatch(scope, userScope);
if (authorized) return true;
}
}
return authorized;
}
}
4 changes: 4 additions & 0 deletions src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { OrderByPipe } from 'src/pipes/order-by.pipe';
import { WherePipe } from 'src/pipes/where.pipe';
import { UserRequest } from '../auth/auth.interface';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Scopes } from '../auth/scope.decorator';
import { ScopesGuard } from '../auth/scope.guard';
import { UpdateUserDto } from './user.dto';
import { UsersService } from './user.service';

Expand All @@ -38,6 +40,8 @@ export class UserController {
}

@Get(':id')
@UseGuards(ScopesGuard)
@Scopes('user3:read')
async get(
@Req() req: UserRequest,
@Param('id', ParseIntPipe) id: number,
Expand Down

0 comments on commit 6a31e88

Please sign in to comment.