Skip to content

Commit

Permalink
Merge pull request #34 from xeptagondev/mw-backend
Browse files Browse the repository at this point in the history
Mw backend
  • Loading branch information
palindaa authored Dec 3, 2024
2 parents 86f8840 + 1537b68 commit 2411526
Show file tree
Hide file tree
Showing 17 changed files with 270 additions and 9 deletions.
50 changes: 50 additions & 0 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,56 @@
}
}
}
},
"libs-auth": {
"projectType": "library",
"root": "libs/libs/auth",
"sourceRoot": "libs/libs/auth/src",
"prefix": "iverify",
"architect": {
"test": {
"builder": "@nrwl/jest:jest",
"outputs": ["coverage/libs/libs/auth"],
"options": {
"jestConfig": "libs/libs/auth/jest.config.js",
"passWithNoTests": true
}
},
"lint": {
"builder": "@nrwl/linter:eslint",
"options": {
"lintFilePatterns": [
"libs/libs/auth/src/**/*.ts",
"libs/libs/auth/src/**/*.html"
]
}
}
}
},
"auth": {
"projectType": "library",
"root": "libs/auth",
"sourceRoot": "libs/auth/src",
"prefix": "iverify",
"architect": {
"test": {
"builder": "@nrwl/jest:jest",
"outputs": ["coverage/libs/auth"],
"options": {
"jestConfig": "libs/auth/jest.config.js",
"passWithNoTests": true
}
},
"lint": {
"builder": "@nrwl/linter:eslint",
"options": {
"lintFilePatterns": [
"libs/auth/src/**/*.ts",
"libs/auth/src/**/*.html"
]
}
}
}
}
}
}
22 changes: 16 additions & 6 deletions apps/triage/src/app/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Body, Controller, Get, HttpException, HttpStatus, Post, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { Body, Controller, Get, HttpException, HttpStatus, Post, UploadedFiles, UseGuards, UseInterceptors } from '@nestjs/common';
import {
ApiBody,
ApiTags,
ApiProperty
} from '@nestjs/swagger';
import { AppService } from './app.service';
import { FilesInterceptor } from '@nestjs/platform-express';
import { AuthService } from '@iverify/auth/src/lib/auth.service';
import { JwtAuthGuard } from '@iverify/auth/src/lib/guard/JwtAuthGuard.guard';

class SubmitStoryDto {
@ApiProperty()
Expand All @@ -15,7 +17,7 @@ class SubmitStoryDto {
content: string;

@ApiProperty()
secret: string;
secret?: string;

@ApiProperty({
type: 'array',
Expand All @@ -33,23 +35,31 @@ class SubmitStoryDto {

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
constructor(private readonly appService: AppService , private authService : AuthService) {}

@Post('submit-story')
@ApiTags('Submit story')
@UseGuards(JwtAuthGuard)
@ApiBody({ type: SubmitStoryDto })
@UseInterceptors(FilesInterceptor('files'))
async submitStory(@Body() body, @UploadedFiles() files: any){
const {url, content, secret , email} = body;
const {url, content,email} = body;
console.log('Submit story', body)
const secretEnv = process.env.SECRET_ENV || '1v3r1fy';
if(secret !== secretEnv ) return new HttpException('Not authorized.', 403);
// const secretEnv = process.env.SECRET_ENV || '1v3r1fy';
// if(secret !== secretEnv ) return new HttpException('Not authorized.', 403);
try {
return await this.appService.createItemFromWp(url, content ,files , email)
}catch(e){
return new HttpException(e.message, 500)
}
}

@Get('get-token')
@ApiTags('Get Submit Story Token')
async generateToken() {
const token = await this.authService.createSubmitStoryToken();
return { token };
}
// test end point for UW
// @Get('radio-messages')
// @ApiTags('Radio Messages')
Expand Down
7 changes: 5 additions & 2 deletions apps/triage/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { PerspectiveClientModule } from '@iverify/perspective-client/src';
import { UnitedwaveClientModule } from '@iverify/unitedwave-client';
import { ApiClientModule, ApiClientService } from '@iverify/api-client/src';
import { TranslateService } from './TranslateService/TranslateService';
import { AuthModule } from '@iverify/auth';
import { AuthService } from '@iverify/auth/src/lib/auth.service';
@Module({
imports: [
HttpModule,
Expand All @@ -22,9 +24,10 @@ import { TranslateService } from './TranslateService/TranslateService';
MeedanCheckClientModule,
UnitedwaveClientModule,
ApiClientModule,
ScheduleModule.forRoot()
ScheduleModule.forRoot(),
AuthModule
],
controllers: [AppController],
providers: [AppService, TriageConfig, CronService, TranslateService],
providers: [AppService, TriageConfig, CronService, TranslateService, AuthService],
})
export class AppModule {}
2 changes: 2 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ module.exports = {
'<rootDir>/libs/unitedwave-client',
'<rootDir>/libs/libs/s3',
'<rootDir>/libs/s3',
'<rootDir>/libs/libs/auth',
'<rootDir>/libs/auth',
],
};
29 changes: 29 additions & 0 deletions libs/auth/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"extends": [
"plugin:@nrwl/nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
],
"parserOptions": { "project": ["libs/auth/tsconfig.*?.json"] },
"rules": {
"@angular-eslint/directive-selector": [
"error",
{ "type": "attribute", "prefix": "iverify", "style": "camelCase" }
],
"@angular-eslint/component-selector": [
"error",
{ "type": "element", "prefix": "iverify", "style": "kebab-case" }
]
}
},
{
"files": ["*.html"],
"extends": ["plugin:@nrwl/nx/angular-template"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# auth

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test auth` to execute the unit tests.
23 changes: 23 additions & 0 deletions libs/auth/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = {
displayName: 'auth',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
],
},
},
},
coverageDirectory: '../../coverage/libs/auth',
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};
1 change: 1 addition & 0 deletions libs/auth/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/auth.module';
16 changes: 16 additions & 0 deletions libs/auth/src/lib/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtAuthGuard } from './guard/JwtAuthGuard.guard';

@Module({
imports: [
JwtModule.register({
secret: process.env.SECRET_ENV,
signOptions: { expiresIn: '30m' }, // Token expiration time
}),
],
providers: [AuthService, JwtAuthGuard],
exports: [AuthService, JwtModule],
})
export class AuthModule {}
39 changes: 39 additions & 0 deletions libs/auth/src/lib/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as jwt from 'jsonwebtoken';
import {
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private readonly jwtService: JwtService) {}
async createSubmitStoryToken() {
const payload = {
timestamp: Date.now(),
};
const accessToken = this.jwtService.sign(payload);
return accessToken;
}

async validateSubmitStoryToken(token: string): Promise<any> {
try {
// Decode and verify the token
const decoded:any = this.jwtService.verify(token);

// Optional: Check timestamp for specific requirements
const currentTime = Date.now();
const tokenTime = decoded.timestamp;
const timeDifference = currentTime - tokenTime;

if (timeDifference > 30 * 60 * 1000) {
// 30 minutes in milliseconds
return false
}

// Process form data here as token is valid
return true;
} catch (error) {
throw new UnauthorizedException('Invalid or expired token');
}
}
}
24 changes: 24 additions & 0 deletions libs/auth/src/lib/guard/JwtAuthGuard.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';

@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const authorization = request.headers.authorization;

if (!authorization) {
throw new UnauthorizedException('Authorization header is missing');
}

const token = authorization.replace('Bearer ', '');

try {
return await this.authService.validateSubmitStoryToken(token);
} catch (error) {
throw new UnauthorizedException('Invalid or expired token');
}
}
}
1 change: 1 addition & 0 deletions libs/auth/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'jest-preset-angular/setup-jest';
24 changes: 24 additions & 0 deletions libs/auth/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"compilerOptions": {
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
14 changes: 14 additions & 0 deletions libs/auth/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"target": "es2015",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": [],
"lib": ["dom", "es2018"]
},
"exclude": ["src/test-setup.ts", "**/*.spec.ts"],
"include": ["**/*.ts"]
}
10 changes: 10 additions & 0 deletions libs/auth/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
6 changes: 6 additions & 0 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@
},
"s3": {
"tags": []
},
"libs-auth": {
"tags": []
},
"auth": {
"tags": []
}
}
}
4 changes: 3 additions & 1 deletion tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@
"@iverify/common": ["libs/common/src/index.ts"],
"@iverify/unitedwave-client": ["libs/unitedwave-client/src/index.ts"],
"@iverify/libs/s3": ["libs/libs/s3/src/index.ts"],
"@iverify/s3": ["libs/s3/src/index.ts"]
"@iverify/s3": ["libs/s3/src/index.ts"],
"@iverify/libs/auth": ["libs/libs/auth/src/index.ts"],
"@iverify/auth": ["libs/auth/src/index.ts"]
}
},
"exclude": ["node_modules", "tmp"]
Expand Down

0 comments on commit 2411526

Please sign in to comment.