refactor: change backend to typescript and update types and variables accordingly

This commit is contained in:
2026-07-08 10:54:07 +02:00
parent 36ec8da1a0
commit 84fa2e0ab0
24 changed files with 1911 additions and 615 deletions
+28 -17
View File
@@ -1,25 +1,36 @@
import {jwtVerify, SignJWT} from "jose";
import type {NextFunction, Request, Response} from "express";
import {type JWTPayload, jwtVerify, SignJWT} from "jose";
import env from "dotenv";
env.config();
const secret = new TextEncoder().encode(process.env.SECRET_KEY);
export async function generateToken(payload) {
return await new SignJWT(payload)
.setProtectedHeader({alg: "HS256"})
.setIssuedAt()
.setExpirationTime("24h") // Token valid for 24 hours
.sign(secret);
export type AuthTokenPayload = JWTPayload & {
username: string;
};
declare module "express-serve-static-core" {
interface Request {
user?: AuthTokenPayload;
}
}
export async function authenticate(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1]; // Bearer <token>
if (token == null) return res.sendStatus(401); // No token present
const { payload } = await jwtVerify(token, secret);
req.user = payload;
next();
export async function generateToken(payload: AuthTokenPayload) {
return await new SignJWT(payload)
.setProtectedHeader({alg: "HS256"})
.setIssuedAt()
.setExpirationTime("24h")
.sign(secret);
}
export async function authenticate(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
const {payload} = await jwtVerify<AuthTokenPayload>(token, secret);
req.user = payload;
next();
}