Skip to content

Commit

Permalink
Merge pull request #10 from arati-tekdi/main
Browse files Browse the repository at this point in the history
Task #227662: Changes in middleware to remove duplicate code
  • Loading branch information
rushi-tekdi authored Sep 26, 2024
2 parents a1f53fb + a466609 commit 0e8b894
Show file tree
Hide file tree
Showing 5 changed files with 375 additions and 565 deletions.
74 changes: 40 additions & 34 deletions src/common/guards/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import {
Inject,
BadRequestException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PermissionsService } from '../service/permissions.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { MiddlewareLogger } from '../loggers/logger.service';
import { UserPrivilegeRoleDto } from '../service/dto/user-privileges';
import APIResponse from '../response/response';
import { Response } from 'express';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
Expand All @@ -31,42 +34,45 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
async validate(request: any, payload: any) {
let userPrivileges;
const ttl = this.configService.get('TTL');
try {
const tenantId = request.headers['tenantid'];
if (!tenantId?.trim()) {
throw new BadRequestException('Tenant id not found');
}
request.userId = payload.sub;
const requiredPermissions = request.requiredPermissions;
//try {
const tenantId = request.headers['tenantid'];
if (!tenantId?.trim()) {
throw new BadRequestException('Tenant id not found');
}
request.userId = payload.sub;
const requiredPermissions = request.requiredPermissions;

const cachedData : UserPrivilegeRoleDto = await this.cacheService.get(payload.sub);
if (!cachedData) {
const userPrivilegesAndRoles: any = await this.permissionService.getUserPrivilegesAndRoles(
const cachedData: UserPrivilegeRoleDto = await this.cacheService.get(
payload.sub,
);
if (!cachedData) {
const userPrivilegesAndRoles: any =
await this.permissionService.getUserPrivilegesAndRoles(
payload.sub,
tenantId,
);
if (userPrivilegesAndRoles.length == 0) {
throw new UnauthorizedException(
'User does not have any privileges in the Tenant',
);
if (userPrivilegesAndRoles.length == 0) {
throw new UnauthorizedException('User does not have any privileges in the Tenant');
}
userPrivileges = userPrivilegesAndRoles['privileges'][tenantId] ? userPrivilegesAndRoles['privileges'][tenantId] : []
this.cacheService.set(payload.sub, userPrivilegesAndRoles, ttl);
} else {
userPrivileges = cachedData.privileges[tenantId] ? cachedData.privileges[tenantId] : []
}
if (!userPrivileges && userPrivileges.length == 0) {
throw new UnauthorizedException('User does not have any privileges in the Tenant');
}
this.middlewareLogger.log(
`user : ${payload.sub - payload.username} userPrivileges: ${userPrivileges}`,
);
return true;
} catch (error) {
console.log('strategy', error)
this.middlewareLogger.error(
`user : ${payload.sub - payload.username} userPrivileges: ${userPrivileges}`,
JSON.stringify(error),
userPrivileges = userPrivilegesAndRoles['privileges'][tenantId]
? userPrivilegesAndRoles['privileges'][tenantId]
: [];
this.cacheService.set(payload.sub, userPrivilegesAndRoles, ttl);
} else {
userPrivileges = cachedData.privileges[tenantId]
? cachedData.privileges[tenantId]
: [];
}
if (!userPrivileges && userPrivileges.length == 0) {
throw new UnauthorizedException(
'User does not have any privileges in the Tenant',
);
let res: Response;
return APIResponse.error(res, 'api.middleware', null, error.message,error.response?.status || 401);
}
this.middlewareLogger.log(
`user : ${payload.sub - payload.username} userPrivileges: ${userPrivileges}`,
);
return true;
}
}
Loading

0 comments on commit 0e8b894

Please sign in to comment.