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

feat(backend): adding regen prompt tool and refactor auth #113

Merged
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
2 changes: 2 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { User } from './user/user.model';
import { AppResolver } from './app.resolver';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { LoggingInterceptor } from 'src/interceptor/LoggingInterceptor';
import { PromptToolModule } from './prompt-tool/prompt-tool.module';

@Module({
imports: [
Expand Down Expand Up @@ -41,6 +42,7 @@ import { LoggingInterceptor } from 'src/interceptor/LoggingInterceptor';
ProjectModule,
TokenModule,
ChatModule,
PromptToolModule,
TypeOrmModule.forFeature([User]),
],
providers: [
Expand Down
5 changes: 3 additions & 2 deletions backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { User } from 'src/user/user.model';
import { AuthResolver } from './auth.resolver';
import { JwtCacheService } from 'src/auth/jwt-cache.service';
import { JwtCacheModule } from 'src/jwt-cache/jwt-cache.module';

@Module({
imports: [
Expand All @@ -21,8 +21,9 @@ import { JwtCacheService } from 'src/auth/jwt-cache.service';
}),
inject: [ConfigService],
}),
JwtCacheModule,
],
providers: [AuthService, AuthResolver, JwtCacheService],
providers: [AuthService, AuthResolver],
exports: [AuthService, JwtModule],
})
export class AuthModule {}
2 changes: 1 addition & 1 deletion backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import { User } from 'src/user/user.model';
import { In, Repository } from 'typeorm';
import { CheckTokenInput } from './dto/check-token.input';
import { JwtCacheService } from 'src/auth/jwt-cache.service';
import { JwtCacheService } from 'src/jwt-cache/jwt-cache.service';
import { Menu } from './menu/menu.model';
import { Role } from './role/role.model';

Expand Down Expand Up @@ -92,7 +92,7 @@
Logger.log('logout token', token);
try {
await this.jwtService.verifyAsync(token);
} catch (error) {

Check warning on line 95 in backend/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / autofix

'error' is defined but never used
return false;
}

Expand Down
7 changes: 6 additions & 1 deletion backend/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import { ChatGuard } from '../guard/chat.guard';
import { AuthModule } from '../auth/auth.module';
import { UserService } from 'src/user/user.service';
import { PubSub } from 'graphql-subscriptions';
import { JwtCacheModule } from 'src/jwt-cache/jwt-cache.module';

@Module({
imports: [TypeOrmModule.forFeature([Chat, User, Message]), AuthModule],
imports: [
TypeOrmModule.forFeature([Chat, User, Message]),
AuthModule,
JwtCacheModule,
],
providers: [
ChatResolver,
ChatProxyService,
Expand Down
2 changes: 1 addition & 1 deletion backend/src/decorator/auth.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import { applyDecorators, UseGuards } from '@nestjs/common';
import { Roles } from './roles.decorator';
import { Menu } from './menu.decorator';
import { RolesGuard } from 'src/guard/roles.guard';
import { RolesGuard } from 'src/interceptor/roles.guard';
import { MenuGuard } from 'src/guard/menu.guard';

export function Auth() {
Expand Down
67 changes: 58 additions & 9 deletions backend/src/guard/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,82 @@
// guards/jwt-auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { JwtService } from '@nestjs/jwt';
import { JwtCacheService } from 'src/jwt-cache/jwt-cache.service';

@Injectable()
export class JWTAuthGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
private readonly logger = new Logger(JWTAuthGuard.name);

constructor(
private readonly jwtService: JwtService,
private readonly jwtCacheService: JwtCacheService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
this.logger.debug('Starting JWT authentication process');

const gqlContext = GqlExecutionContext.create(context);
const { req } = gqlContext.getContext();

try {
const token = this.extractTokenFromHeader(req);

const payload = await this.verifyToken(token);

const isTokenValid = await this.jwtCacheService.isTokenStored(token);
if (!isTokenValid) {
throw new UnauthorizedException('Token has been invalidated');
}

req.user = payload;

return true;
} catch (error) {
if (error instanceof UnauthorizedException) {
throw error;
}
this.logger.error('Authentication failed:', error);
throw new UnauthorizedException('Invalid authentication token');
}
}

private extractTokenFromHeader(req: any): string {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new UnauthorizedException('Authorization token is missing');

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

const [type, token] = authHeader.split(' ');

if (type !== 'Bearer') {
throw new UnauthorizedException('Invalid authorization header format');
}

const token = authHeader.split(' ')[1];
if (!token) {
throw new UnauthorizedException('Token is missing');
}

return token;
}

private async verifyToken(token: string): Promise<any> {
try {
const payload = this.jwtService.verify(token);
req.user = payload;
return true;
return await this.jwtService.verifyAsync(token);
} catch (error) {
throw new UnauthorizedException('Invalid token');
if (error.name === 'TokenExpiredError') {
throw new UnauthorizedException('Token has expired');
}
if (error.name === 'JsonWebTokenError') {
throw new UnauthorizedException('Invalid token');
}
throw error;
}
}
}
1 change: 0 additions & 1 deletion backend/src/guard/project.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { GqlExecutionContext } from '@nestjs/graphql';
import { JwtService } from '@nestjs/jwt';

import { ProjectService } from '../project/project.service';
import { Reflector } from '@nestjs/core';

@Injectable()
export class ProjectGuard implements CanActivate {
Expand Down
8 changes: 8 additions & 0 deletions backend/src/jwt-cache/jwt-cache.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { JwtCacheService } from './jwt-cache.service';

@Module({
exports: [JwtCacheService],
providers: [JwtCacheService],
})
export class JwtCacheModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,37 @@ import { Database } from 'sqlite3';
export class JwtCacheService implements OnModuleInit, OnModuleDestroy {
private db: Database;
private readonly logger = new Logger(JwtCacheService.name);
private cleanupInterval: NodeJS.Timeout;

constructor() {
this.db = new Database(':memory:');
this.logger.log('JwtCacheService instantiated');
this.logger.log('JwtCacheService instantiated with in-memory database');
}

async onModuleInit() {
this.logger.log('Initializing JwtCacheService');
await this.createTable();
await this.clearTable();
this.startCleanupTask();
this.logger.log('JwtCacheService initialized successfully');
}

async onModuleDestroy() {
this.logger.log('Destroying JwtCacheService');
await this.clearTable();
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
}
await this.closeDatabase();
this.logger.log('JwtCacheService destroyed successfully');
}

private createTable(): Promise<void> {
this.logger.debug('Creating jwt_cache table');
return new Promise((resolve, reject) => {
this.db.run(
`
CREATE TABLE IF NOT EXISTS jwt_cache (
`CREATE TABLE IF NOT EXISTS jwt_cache (
token TEXT PRIMARY KEY,
created_at INTEGER NOT NULL
)
`,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
)`,
(err) => {
if (err) {
this.logger.error('Failed to create jwt_cache table', err.stack);
Expand All @@ -53,23 +54,34 @@ export class JwtCacheService implements OnModuleInit, OnModuleDestroy {
});
}

private clearTable(): Promise<void> {
this.logger.debug('Clearing jwt_cache table');
private startCleanupTask() {
const CLEANUP_INTERVAL = 5 * 60 * 1000;
this.cleanupInterval = setInterval(() => {
this.cleanupExpiredTokens().catch((err) =>
this.logger.error('Failed to cleanup expired tokens', err),
);
}, CLEANUP_INTERVAL);
}

private cleanupExpiredTokens(): Promise<void> {
return new Promise((resolve, reject) => {
this.db.run('DELETE FROM jwt_cache', (err) => {
if (err) {
this.logger.error('Failed to clear jwt_cache table', err.stack);
reject(err);
} else {
this.logger.debug('jwt_cache table cleared successfully');
resolve();
}
});
const now = Date.now();
this.db.run(
'DELETE FROM jwt_cache WHERE expires_at < ?',
[now],
(err) => {
if (err) {
this.logger.error('Failed to cleanup expired tokens', err.stack);
reject(err);
} else {
resolve();
}
},
);
});
}

private closeDatabase(): Promise<void> {
this.logger.debug('Closing database connection');
return new Promise((resolve, reject) => {
this.db.close((err) => {
if (err) {
Expand All @@ -84,17 +96,18 @@ export class JwtCacheService implements OnModuleInit, OnModuleDestroy {
}

async storeToken(token: string): Promise<void> {
this.logger.debug(`Storing token: ${token.substring(0, 10)}...`);
const now = Date.now();
const expiresAt = now + 24 * 60 * 60 * 1000;

return new Promise((resolve, reject) => {
this.db.run(
'INSERT OR REPLACE INTO jwt_cache (token, created_at) VALUES (?, ?)',
[token, Date.now()],
'INSERT OR REPLACE INTO jwt_cache (token, created_at, expires_at) VALUES (?, ?, ?)',
[token, now, expiresAt],
(err) => {
if (err) {
this.logger.error('Failed to store token', err.stack);
reject(err);
} else {
this.logger.debug('Token stored successfully');
resolve();
}
},
Expand All @@ -103,21 +116,17 @@ export class JwtCacheService implements OnModuleInit, OnModuleDestroy {
}

async isTokenStored(token: string): Promise<boolean> {
this.logger.debug(
`Checking if token is stored: ${token.substring(0, 10)}...`,
);
return new Promise((resolve, reject) => {
const now = Date.now();
this.db.get(
'SELECT token FROM jwt_cache WHERE token = ?',
[token],
'SELECT token FROM jwt_cache WHERE token = ? AND expires_at > ?',
[token, now],
(err, row) => {
if (err) {
this.logger.error('Failed to check token', err.stack);
reject(err);
} else {
const isStored = !!row;
this.logger.debug(`Token ${isStored ? 'is' : 'is not'} stored`);
resolve(isStored);
resolve(!!row);
}
},
);
Expand All @@ -131,7 +140,6 @@ export class JwtCacheService implements OnModuleInit, OnModuleDestroy {
this.logger.error('Failed to remove token', err.stack);
reject(err);
} else {
this.logger.debug('Token removed successfully');
resolve();
}
});
Expand Down
2 changes: 0 additions & 2 deletions backend/src/project/dto/project.input.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// DTOs for Project APIs
import { InputType, Field, ID } from '@nestjs/graphql';
import { ProjectPackages } from '../project-packages.model';
import { Optional } from '@nestjs/common';

/**
* @deprecated We don't need project upsert
Expand Down
6 changes: 1 addition & 5 deletions backend/src/project/project.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { ProjectService } from './project.service';
import { Project } from './project.model';
import {
CreateProjectInput,
IsValidProjectInput,
UpsertProjectInput,
} from './dto/project.input';
import { CreateProjectInput, IsValidProjectInput } from './dto/project.input';
import { UseGuards } from '@nestjs/common';
import { ProjectGuard } from '../guard/project.guard';
import { GetUserIdFromToken } from '../decorator/get-auth-token.decorator';
Expand Down
12 changes: 12 additions & 0 deletions backend/src/prompt-tool/prompt-tool.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ProjectModule } from '../project/project.module';
import { PromptToolService } from './prompt-tool.service';
import { PromptToolResolver } from './prompt-tool.resolver';
import { AuthModule } from '../auth/auth.module';
import { JwtCacheModule } from 'src/jwt-cache/jwt-cache.module';

@Module({
imports: [ProjectModule, JwtCacheModule, AuthModule],
providers: [PromptToolResolver, PromptToolService],
})
export class PromptToolModule {}
14 changes: 14 additions & 0 deletions backend/src/prompt-tool/prompt-tool.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Resolver, Mutation, Args } from '@nestjs/graphql';
import { JWTAuth } from '../decorator/jwt-auth.decorator';
import { PromptToolService } from './prompt-tool.service';

@Resolver()
export class PromptToolResolver {
constructor(private readonly promptService: PromptToolService) {}

@Mutation(() => String)
@JWTAuth()
async regenerateDescription(@Args('input') input: string): Promise<string> {
return this.promptService.regenerateDescription(input);
}
}
Loading
Loading