Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exntity studio authtoken added #34

Merged
merged 2 commits into from
Feb 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 3 additions & 14 deletions src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { EdvModule } from 'src/edv/edv.module';
import { EdvService } from 'src/edv/services/edv.service';
import { AppAuthSecretService } from './services/app-auth-passord.service';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './strategy/jwt.strategy';
import { JwtStrategy, JwtStrategyApp } from './strategy/jwt.strategy';
import { AppAuthApiKeyService } from './services/app-auth-apikey.service';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
@Module({
Expand All @@ -37,24 +37,13 @@ import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
EdvService,
AppAuthSecretService,
JwtStrategy,
JwtStrategyApp,
AppAuthApiKeyService

],
controllers: [AppAuthController,AppOAuthController],

exports: [AppAuthService, AppRepository],
})
export class AppAuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
//// Appy middleware on all routes
consumer
.apply(ValidateHeadersMiddleware, WhitelistMiddleware)
.forRoutes(AppAuthController);
export class AppAuthModule{}

//// or Apply on specific routes
// consumer.apply(ValidateHeadersMiddleware).forRoutes({
// path: '/app-auth/register',
// method: RequestMethod.POST,
// })
}
}
55 changes: 28 additions & 27 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
HttpCode,
UseFilters,
Query,
UseGuards,
Req,
} from '@nestjs/common';
import { User } from '../decorator/user.decorator';
import { CreateAppDto } from 'src/app-auth/dtos/create-app.dto';
Expand All @@ -23,6 +25,7 @@ import {
import { AppAuthService } from 'src/app-auth/services/app-auth.service';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiCreatedResponse,
ApiHeader,
ApiNotFoundResponse,
Expand All @@ -40,22 +43,21 @@ import { AppError } from '../dtos/fetch-app.dto';
import { PaginationDto } from 'src/utils/pagination.dto';
import { AppSecretHeader } from '../decorator/app-sercret.decorator';
import { AppAuthApiKeyService } from '../services/app-auth-apikey.service';
import { AuthGuard } from '@nestjs/passport';

@UseFilters(AllExceptionsFilter)
@ApiTags('App')
@Controller('app')
@ApiBearerAuth('Authorization')
@UseGuards(AuthGuard('jwtApp'))
export class AppAuthController {
constructor(private readonly appAuthService: AppAuthService) {}
@UseInterceptors(
MongooseClassSerializerInterceptor(App, {
excludePrefixes: ['apiKeySecret','apiKeyPrefix', '_', '__'],
}),
)
@ApiHeader({
name: 'userId',
description:
'Provide userId to get list of all the apps created by the userId',
})

@UsePipes(new ValidationPipe({ transform: true }))
@Get()
@ApiResponse({
Expand All @@ -79,9 +81,11 @@ export class AppAuthController {
required: false,
})
async getApps(
@User() userId,
@Req() req:any,
@Query() pageOption: PaginationDto,
): Promise<App[]> {
const userId=req.user.userId

const appList = await this.appAuthService.getAllApps(userId, pageOption);
if (appList.length === 0) {
throw new AppNotFoundException();
Expand All @@ -93,10 +97,7 @@ export class AppAuthController {
excludePrefixes: ['apiKeySecret','apiKeyPrefix', '_', '__'],
}),
)
@ApiHeader({
name: 'userId',
description: 'Provide userId to get app details',
})

@Get(':appId')
@ApiResponse({
status: 200,
Expand All @@ -109,18 +110,18 @@ export class AppAuthController {
type: AppError,
})
async getAppById(
@User() userId,
@Req() req:any,

@Param('appId') appId: string,
): Promise<App> {
const userId=req.user.userId

const app = await this.appAuthService.getAppById(appId, userId);
if (app) return app;
else throw new AppNotFoundException(); // Custom Exception handling
}

@ApiHeader({
name: 'userId',
description: 'Provide UserId to create a App',
})

@Post()
@UseInterceptors(
MongooseClassSerializerInterceptor(createAppResponse, {
Expand All @@ -137,9 +138,11 @@ export class AppAuthController {
})
@UsePipes(ValidationPipe)
register(
@User() userId,
@Req() req:any,
@Body() createAppDto: CreateAppDto,
): Promise<createAppResponse> {
const userId=req.user.userId

return this.appAuthService.createAnApp(createAppDto, userId);
}

Expand All @@ -148,10 +151,7 @@ export class AppAuthController {
excludePrefixes: ['apiKeySecret','apiKeyPrefix', '_', '__'],
}),
)
@ApiHeader({
name: 'userId',
description: 'Provide userId to get app details',
})

@Put(':appId')
@ApiResponse({
status: 200,
Expand All @@ -164,10 +164,12 @@ export class AppAuthController {
})
@UsePipes(ValidationPipe)
async update(
@User() userId,
@Req() req:any,
@Param('appId') appId: string,
@Body() updateAppDto: UpdateAppDto,
): Promise<App> {
const userId=req.user.userId

const app = await this.appAuthService.getAppById(appId, userId);
if (app) {
return this.appAuthService.updateAnApp(appId, updateAppDto, userId);
Expand All @@ -176,10 +178,7 @@ export class AppAuthController {



@ApiHeader({
name: 'userId',
description: 'Provide userId to get app details',
})

@Post(':appId/secret/new')
@HttpCode(200)
@ApiResponse({
Expand All @@ -192,9 +191,11 @@ export class AppAuthController {
type: AppError,
})
async reGenerateAppSecretKey(
@User() userId,
@Param('appId') appId: string,
@Req() req:any,
@Param('appId') appId: string,
){
const userId=req.user.userId

const app = await this.appAuthService.getAppById(appId, userId);
if (!app) {throw new AppNotFoundException()}
return this.appAuthService.reGenerateAppSecretKey(app,userId)
Expand Down
26 changes: 26 additions & 0 deletions src/app-auth/strategy/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,29 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
return appDetail;
}
}




@Injectable()
export class JwtStrategyApp extends PassportStrategy(Strategy, 'jwtApp') {
constructor(
private readonly config: ConfigService,
private readonly appRepository: AppRepository,
private readonly appAuthSecretService: AppAuthSecretService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get('JWT_SECRET_HYPERSIGN'),
});
}
async validate(payload) {
payload.userId=payload.email
return payload
}


}