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

Commit

Permalink
✨ Add scope authorization in Guard
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Oct 23, 2020
1 parent 6a31e88 commit d1e9e25
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 9 deletions.
6 changes: 4 additions & 2 deletions src/modules/auth/auth.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Request } from '@nestjs/common';
import { Request as ExpressRequest } from 'express';
import { Request as NestRequest } from '@nestjs/common';

export interface AccessTokenClaims {
sub: string;
Expand All @@ -10,6 +11,7 @@ export interface AccessTokenParsed {
scopes: string[];
}

export interface UserRequest extends Request {
type CombinedRequest = ExpressRequest & typeof NestRequest;
export interface UserRequest extends CombinedRequest {
user: AccessTokenParsed;
}
6 changes: 4 additions & 2 deletions src/modules/auth/scope.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ export class ScopesGuard implements CanActivate {

canActivate(context: ExecutionContext): boolean {
const scopes = this.reflector.get<string[]>('scopes', context.getHandler());
if (!scopes) return true;
const request = context.switchToHttp().getRequest<UserRequest>();
if (!scopes) return true;
const user: AccessTokenParsed = request.user;
let authorized = false;
for (const userScope of user.scopes) {
for (const scope of scopes) {
for (let scope of scopes) {
for (const key in request.params)
scope = scope.replace(`{${key}}`, request.params[key]);
authorized = authorized || minimatch(scope, userScope);
if (authorized) return true;
}
Expand Down
6 changes: 1 addition & 5 deletions src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
ParseIntPipe,
Patch,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import { users } from '@prisma/client';
Expand All @@ -16,7 +15,6 @@ import { CursorPipe } from 'src/pipes/cursor.pipe';
import { OptionalIntPipe } from 'src/pipes/optional-int.pipe';
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';
Expand All @@ -41,12 +39,10 @@ export class UserController {

@Get(':id')
@UseGuards(ScopesGuard)
@Scopes('user3:read')
@Scopes('user{id}:read')
async get(
@Req() req: UserRequest,
@Param('id', ParseIntPipe) id: number,
): Promise<OmitSecrets<users>> {
console.log(req.user);
return this.usersService.user({ id: Number(id) });
}

Expand Down

0 comments on commit d1e9e25

Please sign in to comment.