Introduce repository pattern across multiple services, including `favorites`, `tags`, `sessions`, `reports`, `auth`, and more. Decouple crypto functionalities into modular services like `HashingService`, `JwtService`, and `EncryptionService`. Improve testability and maintainability by simplifying dependencies and consolidating utility logic.
38 lines
1.0 KiB
TypeScript
38 lines
1.0 KiB
TypeScript
import { Injectable, Logger } from "@nestjs/common";
|
|
import { ConfigService } from "@nestjs/config";
|
|
import * as jose from "jose";
|
|
|
|
@Injectable()
|
|
export class JwtService {
|
|
private readonly logger = new Logger(JwtService.name);
|
|
private readonly jwtSecret: Uint8Array;
|
|
|
|
constructor(private configService: ConfigService) {
|
|
const secret = this.configService.get<string>("JWT_SECRET");
|
|
if (!secret) {
|
|
this.logger.warn(
|
|
"JWT_SECRET is not defined, using a default insecure secret for development",
|
|
);
|
|
}
|
|
this.jwtSecret = new TextEncoder().encode(
|
|
secret || "default-secret-change-me-in-production",
|
|
);
|
|
}
|
|
|
|
async generateJwt(
|
|
payload: jose.JWTPayload,
|
|
expiresIn = "2h",
|
|
): Promise<string> {
|
|
return new jose.SignJWT(payload)
|
|
.setProtectedHeader({ alg: "HS256" })
|
|
.setIssuedAt()
|
|
.setExpirationTime(expiresIn)
|
|
.sign(this.jwtSecret);
|
|
}
|
|
|
|
async verifyJwt<T extends jose.JWTPayload>(token: string): Promise<T> {
|
|
const { payload } = await jose.jwtVerify(token, this.jwtSecret);
|
|
return payload as T;
|
|
}
|
|
}
|