Skip to content

Commit

Permalink
Merge pull request #13 from HeliosLive/rest-fa-13
Browse files Browse the repository at this point in the history
auth guard added
  • Loading branch information
HeliosLive authored Feb 8, 2020
2 parents 461213e + 77af396 commit f84505c
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 2 deletions.
3 changes: 3 additions & 0 deletions libs/decorators/role.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
62 changes: 62 additions & 0 deletions libs/guards/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
Injectable,
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Inject,
Module,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RoleModel } from 'tools/models/role.model';
import { GroupModel } from 'tools/models/group.model';
import { GroupService } from 'src/group/group.service';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
@Inject('GroupService') private readonly groupService: GroupService,
) {}

canActivate(context: ExecutionContext): boolean {
const allowedRoles = this.reflector.get<string[]>(
'roles',
context.getHandler(),
);
if (!allowedRoles) {
return true;
}

const request = context.switchToHttp().getRequest();
const user = request.user.user;
const allowed = this.isAllowed(allowedRoles, user.roles, user.groups);

if (!allowed) {
throw new HttpException('Forbidden Method!', HttpStatus.FORBIDDEN);
}

return true;
}

async isAllowed(
allowedRoles,
userRoles: RoleModel[],
userGroups: GroupModel[],
) {
const allUsersRoles = [];
userRoles.map(data => {
allUsersRoles.push(data.name);
});
await Promise.all(
userGroups.map(async data => {
const groupRoles = await this.groupService.findOne(data._id);
groupRoles[0].roles.map(resp => {
allUsersRoles.push(resp['name']);
});
}),
);
const hasRole = allUsersRoles.some(role => allowedRoles.includes(role));
return hasRole;
}
}
10 changes: 9 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { RoleModule } from './role/role.module';
import { TotalModule } from './total/total.module';
import { LoginModule } from './login/login.module';
import { TokenMiddleware } from 'libs/middlewares/token.middleware';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from 'libs/guards/auth.guard';

@Module({
imports: [
Expand All @@ -43,7 +45,13 @@ import { TokenMiddleware } from 'libs/middlewares/token.middleware';
MongooseModule.forRoot(environment.mongoUrl),
],
controllers: [AppController],
providers: [AppService],
providers: [
AppService,
{
provide: APP_GUARD,
useClass: AuthGuard,
},
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
Expand Down
1 change: 1 addition & 0 deletions src/group/group.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ import { GroupService } from './group.service';
],
controllers: [GroupController],
providers: [GroupService],
exports: [GroupService],
})
export class GroupModule {}
4 changes: 4 additions & 0 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ import { UserService } from './user.service';
import { UserCreateDto, UserUpdateDto } from 'tools/dtos/user.dto';
import { UserModel } from 'tools/models/user.model';
import { FilterModel } from 'tools/models/filter.model';
import { Roles } from 'libs/decorators/role.decorator';

@Controller('user')
export class UserController {
constructor(private userService: UserService) {}

@Post()
@Roles('Admin')
async createUser(@Body() body: UserCreateDto): Promise<UserModel> {
body.password = await this.userService.convertToHash(body.password);
return await this.userService.create(body);
Expand All @@ -30,11 +32,13 @@ export class UserController {
}

@Get(':id')
@Roles('Developer')
async getUser(@Param() params): Promise<UserModel> {
return await this.userService.findOne(params.id);
}

@Put(':id')
@Roles('Operator')
async updateUser(
@Param('id') id: string,
@Body() userUpdateDto: UserUpdateDto,
Expand Down
2 changes: 1 addition & 1 deletion tools/models/group.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AuditModel } from './audit.model';
import { RoleModel } from './role.model';

export class GroupModel {
id: string;
_id: string;
name: string;
description: string;
audit: AuditModel;
Expand Down

0 comments on commit f84505c

Please sign in to comment.