feat: bootstrap codexdash app
This commit is contained in:
13
apps/api/src/app.controller.ts
Normal file
13
apps/api/src/app.controller.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
@Get('health')
|
||||
health() {
|
||||
return {
|
||||
ok: true,
|
||||
service: 'codexdash-api',
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
18
apps/api/src/app.module.ts
Normal file
18
apps/api/src/app.module.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AppController } from './app.controller';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CodexModule } from './codex/codex.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
CodexModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
30
apps/api/src/auth/auth.controller.ts
Normal file
30
apps/api/src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
CurrentUser,
|
||||
type AuthenticatedUser,
|
||||
} from '../common/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('register')
|
||||
register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
login(@Body() dto: LoginDto) {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('me')
|
||||
me(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.authService.me(user.sub);
|
||||
}
|
||||
}
|
||||
23
apps/api/src/auth/auth.module.ts
Normal file
23
apps/api/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
JwtModule.registerAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('JWT_SECRET') ?? 'change-me',
|
||||
signOptions: { expiresIn: '30d' },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard],
|
||||
exports: [JwtModule, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
84
apps/api/src/auth/auth.service.ts
Normal file
84
apps/api/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as argon2 from 'argon2';
|
||||
import { AuthResponse, UserProfile } from '@codexdash/shared-types';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async register(dto: RegisterDto): Promise<AuthResponse> {
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw new ConflictException('Email already registered');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.create({
|
||||
data: {
|
||||
email: dto.email.toLowerCase(),
|
||||
name: dto.name.trim(),
|
||||
passwordHash: await argon2.hash(dto.password),
|
||||
},
|
||||
});
|
||||
|
||||
return this.toAuthResponse(user);
|
||||
}
|
||||
|
||||
async login(dto: LoginDto): Promise<AuthResponse> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (!user || !(await argon2.verify(user.passwordHash, dto.password))) {
|
||||
throw new UnauthorizedException('Invalid email or password');
|
||||
}
|
||||
|
||||
return this.toAuthResponse(user);
|
||||
}
|
||||
|
||||
async me(userId: string): Promise<UserProfile> {
|
||||
const user = await this.prisma.user.findUniqueOrThrow({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async toAuthResponse(user: {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
createdAt: Date;
|
||||
}): Promise<AuthResponse> {
|
||||
return {
|
||||
token: await this.jwtService.signAsync({
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
}),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
11
apps/api/src/auth/dto/login.dto.ts
Normal file
11
apps/api/src/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { LoginInput } from '@codexdash/shared-types';
|
||||
|
||||
export class LoginDto implements LoginInput {
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
}
|
||||
15
apps/api/src/auth/dto/register.dto.ts
Normal file
15
apps/api/src/auth/dto/register.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { RegisterInput } from '@codexdash/shared-types';
|
||||
|
||||
export class RegisterDto implements RegisterInput {
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
name!: string;
|
||||
}
|
||||
52
apps/api/src/codex/codex.controller.ts
Normal file
52
apps/api/src/codex/codex.controller.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
CurrentUser,
|
||||
type AuthenticatedUser,
|
||||
} from '../common/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
import { CodexService } from './codex.service';
|
||||
import { ConnectAccountDto } from './dto/connect-account.dto';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('codex')
|
||||
export class CodexController {
|
||||
constructor(private readonly codexService: CodexService) {}
|
||||
|
||||
@Get('accounts')
|
||||
listAccounts(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.codexService.listAccounts(user.sub);
|
||||
}
|
||||
|
||||
@Post('accounts')
|
||||
connectAccount(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Body() dto: ConnectAccountDto,
|
||||
) {
|
||||
return this.codexService.connectAccount(user.sub, dto);
|
||||
}
|
||||
|
||||
@Delete('accounts/:accountId')
|
||||
deleteAccount(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Param('accountId') accountId: string,
|
||||
) {
|
||||
return this.codexService.deleteAccount(user.sub, accountId);
|
||||
}
|
||||
|
||||
@Get('usage-summary')
|
||||
getUsageSummary(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Query('refresh') refresh?: string,
|
||||
) {
|
||||
return this.codexService.getUsageSummary(user.sub, refresh !== 'false');
|
||||
}
|
||||
}
|
||||
11
apps/api/src/codex/codex.module.ts
Normal file
11
apps/api/src/codex/codex.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { CodexController } from './codex.controller';
|
||||
import { CodexService } from './codex.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [CodexController],
|
||||
providers: [CodexService],
|
||||
})
|
||||
export class CodexModule {}
|
||||
172
apps/api/src/codex/codex.service.ts
Normal file
172
apps/api/src/codex/codex.service.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ConnectedAccount, UsageSummary } from '@codexdash/shared-types';
|
||||
import { decryptString, encryptString } from '../common/crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ConnectAccountDto } from './dto/connect-account.dto';
|
||||
import { aggregateUsagePayloads } from './usage-aggregator';
|
||||
|
||||
type UsageApiResponse = Record<string, unknown>;
|
||||
|
||||
@Injectable()
|
||||
export class CodexService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async connectAccount(
|
||||
userId: string,
|
||||
dto: ConnectAccountDto,
|
||||
): Promise<ConnectedAccount> {
|
||||
const usage = await this.fetchUsage(dto.cookieHeader);
|
||||
const account = await this.prisma.openAiAccount.create({
|
||||
data: {
|
||||
userId,
|
||||
label: dto.label.trim(),
|
||||
emailHint: dto.emailHint?.trim() || null,
|
||||
encryptedCookie: encryptString(
|
||||
dto.cookieHeader,
|
||||
this.getEncryptionSecret(),
|
||||
),
|
||||
lastUsageJson: usage as Prisma.InputJsonValue,
|
||||
lastSyncedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return this.toAccountView(account);
|
||||
}
|
||||
|
||||
async listAccounts(userId: string) {
|
||||
const accounts = await this.prisma.openAiAccount.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return accounts.map((account) => this.toAccountView(account));
|
||||
}
|
||||
|
||||
async deleteAccount(userId: string, accountId: string) {
|
||||
const account = await this.prisma.openAiAccount.findFirst({
|
||||
where: { id: accountId, userId },
|
||||
});
|
||||
if (!account) {
|
||||
throw new NotFoundException('Connected account not found');
|
||||
}
|
||||
|
||||
await this.prisma.openAiAccount.delete({ where: { id: accountId } });
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async getUsageSummary(userId: string, refresh = true): Promise<UsageSummary> {
|
||||
const accounts = await this.prisma.openAiAccount.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const resolvedAccounts = await Promise.all(
|
||||
accounts.map(async (account) => {
|
||||
if (!refresh) {
|
||||
return account;
|
||||
}
|
||||
|
||||
try {
|
||||
const usage = await this.fetchUsage(
|
||||
decryptString(account.encryptedCookie, this.getEncryptionSecret()),
|
||||
);
|
||||
return this.prisma.openAiAccount.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
lastUsageJson: usage as Prisma.InputJsonValue,
|
||||
lastSyncedAt: new Date(),
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return this.prisma.openAiAccount.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
lastError:
|
||||
error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const accountViews = resolvedAccounts.map((account) =>
|
||||
this.toAccountView(account),
|
||||
);
|
||||
|
||||
return {
|
||||
aggregatedUsage: aggregateUsagePayloads(
|
||||
accountViews.map((account) => account.usage),
|
||||
),
|
||||
accounts: accountViews,
|
||||
totals: {
|
||||
totalAccounts: accountViews.length,
|
||||
activeAccounts: accountViews.filter(
|
||||
(account) => account.status === 'active',
|
||||
).length,
|
||||
erroredAccounts: accountViews.filter(
|
||||
(account) => account.status === 'error',
|
||||
).length,
|
||||
},
|
||||
refreshedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUsage(cookieHeader: string): Promise<UsageApiResponse> {
|
||||
const response = await fetch(
|
||||
'https://chatgpt.com/backend-api/api/codex/usage',
|
||||
{
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
cookie: cookieHeader,
|
||||
'user-agent': 'CodexDash/0.1 (+https://example.invalid)',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new BadRequestException(
|
||||
`Codex usage request failed with status ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
return (await response.json()) as UsageApiResponse;
|
||||
}
|
||||
|
||||
private getEncryptionSecret() {
|
||||
return (
|
||||
this.configService.get<string>('ENCRYPTION_SECRET') ??
|
||||
'change-me-32-characters-minimum'
|
||||
);
|
||||
}
|
||||
|
||||
private toAccountView(account: {
|
||||
id: string;
|
||||
label: string;
|
||||
emailHint: string | null;
|
||||
lastUsageJson: unknown;
|
||||
lastSyncedAt: Date | null;
|
||||
lastError: string | null;
|
||||
createdAt: Date;
|
||||
}): ConnectedAccount {
|
||||
return {
|
||||
id: account.id,
|
||||
label: account.label,
|
||||
emailHint: account.emailHint,
|
||||
status: account.lastError ? 'error' : 'active',
|
||||
lastSyncedAt: account.lastSyncedAt?.toISOString() ?? null,
|
||||
lastError: account.lastError,
|
||||
usage: (account.lastUsageJson as Record<string, unknown> | null) ?? null,
|
||||
createdAt: account.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
16
apps/api/src/codex/dto/connect-account.dto.ts
Normal file
16
apps/api/src/codex/dto/connect-account.dto.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { IsOptional, IsString, MinLength } from 'class-validator';
|
||||
import { ConnectAccountInput } from '@codexdash/shared-types';
|
||||
|
||||
export class ConnectAccountDto implements ConnectAccountInput {
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
label!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
emailHint?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(20)
|
||||
cookieHeader!: string;
|
||||
}
|
||||
24
apps/api/src/codex/usage-aggregator.spec.ts
Normal file
24
apps/api/src/codex/usage-aggregator.spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { aggregateUsagePayloads } from './usage-aggregator';
|
||||
|
||||
describe('aggregateUsagePayloads', () => {
|
||||
it('sums nested numeric values while preserving useful metadata', () => {
|
||||
const result = aggregateUsagePayloads([
|
||||
{
|
||||
limit: { used: 10, remaining: 90, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 2 }, { used: 3 }],
|
||||
},
|
||||
{
|
||||
limit: { used: 25, remaining: 75, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 4 }, { used: 1 }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual({
|
||||
limit: { used: 35, remaining: 165, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 6 }, { used: 4 }],
|
||||
});
|
||||
});
|
||||
});
|
||||
60
apps/api/src/codex/usage-aggregator.ts
Normal file
60
apps/api/src/codex/usage-aggregator.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
type JsonValue =
|
||||
| null
|
||||
| boolean
|
||||
| number
|
||||
| string
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
const isObject = (value: JsonValue): value is { [key: string]: JsonValue } =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
function mergeValues(values: JsonValue[]): JsonValue {
|
||||
const filtered = values.filter((value) => value !== null);
|
||||
if (filtered.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (filtered.every((value) => typeof value === 'number')) {
|
||||
return filtered.reduce((sum, value) => sum + value, 0);
|
||||
}
|
||||
|
||||
if (filtered.every((value) => Array.isArray(value))) {
|
||||
const arrays = filtered as JsonValue[][];
|
||||
const maxLength = Math.max(...arrays.map((array) => array.length));
|
||||
return Array.from({ length: maxLength }, (_, index) =>
|
||||
mergeValues(arrays.map((array) => array[index] ?? null)),
|
||||
);
|
||||
}
|
||||
|
||||
if (filtered.every((value) => isObject(value))) {
|
||||
const keys = [...new Set(filtered.flatMap((value) => Object.keys(value)))];
|
||||
return Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
mergeValues(
|
||||
filtered.map(
|
||||
(value) => (value as Record<string, JsonValue>)[key] ?? null,
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const unique = [
|
||||
...new Set(filtered.map((value) => JSON.stringify(value))),
|
||||
].map((value) => JSON.parse(value) as JsonValue);
|
||||
return unique.length === 1 ? unique[0] : unique[0];
|
||||
}
|
||||
|
||||
export function aggregateUsagePayloads(
|
||||
payloads: Array<Record<string, unknown> | null | undefined>,
|
||||
) {
|
||||
const normalized = payloads.filter(Boolean) as Array<Record<string, unknown>>;
|
||||
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mergeValues(normalized as JsonValue[]) as Record<string, unknown>;
|
||||
}
|
||||
37
apps/api/src/common/crypto.ts
Normal file
37
apps/api/src/common/crypto.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
randomBytes,
|
||||
} from 'node:crypto';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
|
||||
function getKey(secret: string) {
|
||||
return createHash('sha256').update(secret).digest();
|
||||
}
|
||||
|
||||
export function encryptString(value: string, secret: string) {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv(ALGORITHM, getKey(secret), iv);
|
||||
const encrypted = Buffer.concat([
|
||||
cipher.update(value, 'utf8'),
|
||||
cipher.final(),
|
||||
]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
return Buffer.concat([iv, tag, encrypted]).toString('base64url');
|
||||
}
|
||||
|
||||
export function decryptString(value: string, secret: string) {
|
||||
const buffer = Buffer.from(value, 'base64url');
|
||||
const iv = buffer.subarray(0, 12);
|
||||
const tag = buffer.subarray(12, 28);
|
||||
const encrypted = buffer.subarray(28);
|
||||
const decipher = createDecipheriv(ALGORITHM, getKey(secret), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
16
apps/api/src/common/current-user.decorator.ts
Normal file
16
apps/api/src/common/current-user.decorator.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
export type AuthenticatedUser = {
|
||||
sub: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
type RequestWithUser = Request & { user?: AuthenticatedUser };
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_: unknown, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest<RequestWithUser>();
|
||||
return request.user as AuthenticatedUser;
|
||||
},
|
||||
);
|
||||
42
apps/api/src/common/jwt-auth.guard.ts
Normal file
42
apps/api/src/common/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { Request } from 'express';
|
||||
import type { AuthenticatedUser } from './current-user.decorator';
|
||||
|
||||
type RequestWithUser = Request & { user?: AuthenticatedUser };
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const authorization = request.headers.authorization;
|
||||
|
||||
if (!authorization?.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('Missing bearer token');
|
||||
}
|
||||
|
||||
try {
|
||||
const token = authorization.slice('Bearer '.length);
|
||||
request.user = await this.jwtService.verifyAsync<AuthenticatedUser>(
|
||||
token,
|
||||
{
|
||||
secret: this.configService.get<string>('JWT_SECRET') ?? 'change-me',
|
||||
},
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
}
|
||||
}
|
||||
18
apps/api/src/main.ts
Normal file
18
apps/api/src/main.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.enableCors({ origin: true, credentials: true });
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.listen(process.env.PORT ?? 3001);
|
||||
}
|
||||
void bootstrap();
|
||||
9
apps/api/src/prisma/prisma.module.ts
Normal file
9
apps/api/src/prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
16
apps/api/src/prisma/prisma.service.ts
Normal file
16
apps/api/src/prisma/prisma.service.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user