Skip to content

Commit

Permalink
seperating out app oauth module from app module
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwas1 committed Nov 7, 2023
1 parent e330adc commit 44508aa
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 60 deletions.
12 changes: 3 additions & 9 deletions src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import {
} from '@nestjs/common';

import { AppAuthService } from './services/app-auth.service';
import {
AppAuthController,
AppOAuthController,
} from './controllers/app-auth.controller';
import { AppAuthController } from './controllers/app-auth.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { App, AppSchema } from './schemas/app.schema';

Expand Down Expand Up @@ -40,15 +37,12 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
JwtStrategyApp,
AppAuthApiKeyService,
],
controllers: [AppAuthController, AppOAuthController],
controllers: [AppAuthController],

exports: [AppAuthService, AppRepository, AppAuthApiKeyService],
exports: [AppAuthService, AppRepository, AppAuthApiKeyService, AppAuthModule],
})
export class AppAuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(WhitelistAppCorsMiddleware)
.forRoutes(AppAuthController, AppOAuthController);
consumer
.apply(TrimMiddleware)
.exclude(
Expand Down
52 changes: 6 additions & 46 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import { AppAuthService } from 'src/app-auth/services/app-auth.service';
import {
ApiBadRequestResponse,
ApiBasicAuth,
ApiBearerAuth,
ApiCreatedResponse,
ApiExcludeController,
Expand All @@ -49,12 +50,14 @@ import {
} from '../decorator/app-sercret.decorator';
import { TransformResponseInterceptor } from '../interceptors/transformResponse.interseptor';
import { JwtGuard } from '../guard/jwt.guard';
import { BasicAuthVerificationGuard } from '../guard/basic-auth-verification.guard';

@UseFilters(AllExceptionsFilter)
@Controller('app')
@ApiExcludeController()
@ApiBearerAuth('Authorization')
@UseGuards(JwtGuard)
// @ApiExcludeController()
// @ApiBearerAuth('Authorization')
@ApiBasicAuth('Basic Auth')
@UseGuards(BasicAuthVerificationGuard)
export class AppAuthController {
constructor(private readonly appAuthService: AppAuthService) {}
@UseInterceptors(
Expand Down Expand Up @@ -243,46 +246,3 @@ export class AppAuthController {
return this.appAuthService.reGenerateAppSecretKey(app, userId);
}
}

@UseFilters(AllExceptionsFilter)
@ApiTags('App')
@Controller('app')
export class AppOAuthController {
constructor(private readonly appAuthService: AppAuthService) {}

@ApiHeader({
name: 'X-Api-Secret-Key',
description: 'Provide Api Secret key to get access token',
required: true,
})
@ApiHeader({
name: 'Origin',
description: 'Origin as you set in application cors',
required: false,
})
@ApiBadRequestResponse({
status: 400,
description: 'Error occured at the time of generating access token',
type: AppError,
})
@Post('oauth')
@HttpCode(200)
@ApiResponse({
status: 200,
description: 'AccessToken generated',
type: GenerateTokenResponse,
})
@ApiUnauthorizedResponse({
description: 'Unauthorized',
type: GenerateTokenError,
})
@UsePipes(ValidationPipe)
generateAccessToken(
@Headers('X-Api-Secret-Key') apiSectretKey: string,
@AppSecretHeader() appSecreatKey,
@AppSubdomainHeader() appSubdomain,
): Promise<{ access_token; expiresIn; tokenType }> {
Logger.log('reGenerateAppSecretKey() method: starts', 'AppOAuthController');
return this.appAuthService.generateAccessToken(appSecreatKey, appSubdomain);
}
}
19 changes: 19 additions & 0 deletions src/app-oauth/app-oauth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppOauthController } from './app-oauth.controller';

describe('AppOauthController', () => {
let controller: AppOauthController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AppOauthController],
providers: [],
}).compile();

controller = module.get<AppOauthController>(AppOauthController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
72 changes: 72 additions & 0 deletions src/app-oauth/app-oauth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import {
Controller,
ValidationPipe,
Post,
UsePipes,
HttpCode,
UseFilters,
Headers,
Logger,
} from '@nestjs/common';

import { AppAuthService } from 'src/app-auth/services/app-auth.service';
import {
ApiBadRequestResponse,
ApiHeader,
ApiResponse,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { AllExceptionsFilter } from 'src/utils/utils';
import {
AppSecretHeader,
AppSubdomainHeader,
} from './dtos/app-sercret.decorator';
import {
GenerateTokenError,
GenerateTokenResponse,
AppError,
} from './dtos/generate-token.dto';

@UseFilters(AllExceptionsFilter)
@ApiTags('App')
@Controller('app')
export class AppOauthController {
constructor(private readonly appAuthService: AppAuthService) {}

@ApiHeader({
name: 'X-Api-Secret-Key',
description: 'Provide Api Secret key to get access token',
required: true,
})
@ApiHeader({
name: 'Origin',
description: 'Origin as you set in application cors',
required: false,
})
@ApiBadRequestResponse({
status: 400,
description: 'Error occured at the time of generating access token',
type: AppError,
})
@Post('oauth')
@HttpCode(200)
@ApiResponse({
status: 200,
description: 'AccessToken generated',
type: GenerateTokenResponse,
})
@ApiUnauthorizedResponse({
description: 'Unauthorized',
type: GenerateTokenError,
})
@UsePipes(ValidationPipe)
generateAccessToken(
@Headers('X-Api-Secret-Key') apiSectretKey: string,
@AppSecretHeader() appSecreatKey,
@AppSubdomainHeader() appSubdomain,
): Promise<{ access_token; expiresIn; tokenType }> {
Logger.log('reGenerateAppSecretKey() method: starts', 'AppOAuthController');
return this.appAuthService.generateAccessToken(appSecreatKey, appSubdomain);
}
}
14 changes: 14 additions & 0 deletions src/app-oauth/app-oauth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppOauthController } from './app-oauth.controller';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
@Module({
imports: [AppAuthModule],
controllers: [AppOauthController],
providers: [],
})
export class AppOauthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(AppOauthController);
}
}
31 changes: 31 additions & 0 deletions src/app-oauth/dtos/app-sercret.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
createParamDecorator,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';

export const AppSecretHeader = createParamDecorator(
(_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
if (
!request.headers['x-api-secret-key'] ||
request.headers['x-api-secret-key'] == undefined
) {
throw new UnauthorizedException(['x-api-secret-key header is missing']);
}
return request.headers['x-api-secret-key'];
},
);

export const AppSubdomainHeader = createParamDecorator(
(_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
if (
!request.headers['x-subdomain'] ||
request.headers['x-subdomain'] == undefined
) {
throw new UnauthorizedException(['x-subdomain header is missing']);
}
return request.headers['x-subdomain'];
},
);
82 changes: 82 additions & 0 deletions src/app-oauth/dtos/generate-token.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { IsNotEmpty, IsString, IsNumber } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class GenerateTokenError {
@ApiProperty({
description: 'statusCode',
example: 401,
})
@IsNumber()
statusCode: number;

@ApiProperty({
description: 'message',
example: ['access_denied'],
})
@IsString()
message: string;

@ApiProperty({
description: 'Unauthorized',
example: 'Unauthorized',
})
@IsString()
error: 'Unauthorized';
}
export class GenerateTokenResponse {
@ApiProperty({
description: 'accessToken',
example:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6IjRkNjhmMjNmLTcwZjQtNDFhZC1hMGViLTU3MjA4YTZlOTcxMSIsImFwcFNlY3JldCI6IjNjN2NiNTY1LTZmNWQtNGY2MC1hMjQ2LTZhOGFjYWVhMmY0MyIsImdyYW50VHlwZSI6ImNsaWVudF9jcmVkZW50aWFscyIsImlhdCI6MTY3NDAyMDY3NCwiZXhwIjoxNjc0MDM1MDc0fQ.P-AbheTJMxQNGLTkGWOsnct4M0nKCd-7oUFGqMCpIDM',
})
@IsNotEmpty()
@IsString()
access_token: string;

@ApiProperty({
description: 'Type of token',
example: 'Bearer',
})
@IsNotEmpty()
@IsString()
tokenType: string;

@ApiProperty({
description: 'Token expiry time',
example: 14400,
})
@IsNotEmpty()
@IsNumber()
expiresIn: number;
}

export class RegenrateAppApiSecretResponse {
@ApiProperty({
description: 'apiSecretKey for getting access token',
example: 'xyz.ert34nbhjf48959',
})
apiSecretKey: string;
}

export class AppError {
@ApiProperty({
description: 'statusCode',
example: 400,
})
@IsNumber()
statusCode: number;

@ApiProperty({
description: 'message',
example: ['error message 1', 'error message 2'],
})
@IsString()
message: Array<string>;

@ApiProperty({
description: 'error',
example: 'Bad Request',
})
@IsString()
error: string;
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { DidModule } from './did/did.module';
import { SchemaModule } from './schema/schema.module';
import { CredentialModule } from './credential/credential.module';
import { PresentationModule } from './presentation/presentation.module';
import { AppOauthModule } from './app-oauth/app-oauth.module';

@Module({
imports: [
Expand All @@ -21,6 +22,7 @@ import { PresentationModule } from './presentation/presentation.module';
}),
MongooseModule.forRoot(process.env.DATABASE_CONNECTION_PATH),
EdvModule,
AppOauthModule,
DidModule,
SchemaModule,
CredentialModule,
Expand Down
Loading

0 comments on commit 44508aa

Please sign in to comment.