add me point to load user data of current user

This commit is contained in:
Anika Raemer 2025-09-27 07:47:26 +02:00
parent fac606cf97
commit e5b5d7e67d
12 changed files with 215 additions and 67 deletions

View file

@ -2,14 +2,14 @@ import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { authBasicRoute } from "../endpoints/AuthPoint.js";
import { AuthPayload } from "../dtos/AuthPayload.js";
dotenv.config();
//@todo this seems to be clumsy... We need some propper session handling as we'll have multiple users accessing the app
declare global {
namespace Express {
interface Request {
currentUser?: string | jwt.JwtPayload;
currentUser?: AuthPayload;
}
}
}
@ -46,10 +46,10 @@ export const authentication = (
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
const decoded = jwt.verify(token, JWT_SECRET) as AuthPayload;
req.currentUser = decoded;
next();
} catch (err) {
} catch {
return res.status(401).json({ message: "Unauthorized" });
}
};

View file

@ -1,11 +1,35 @@
import { NextFunction, Request, Response } from "express";
// middleware/errorHandler.ts
import { Request, Response, NextFunction } from "express";
import { HttpError, InternalServerError } from "../errors/httpErrors.js";
export const errorHandler = (
error: Error,
/**
* Express global error-handling middleware.
*
* Responsibilities:
* - Catch and handle errors thrown in controllers or routes
* - Map known HttpError subclasses (ValidationError, UnauthorizedError, etc.)
* to the appropriate HTTP status code and JSON response
* - Fallback to InternalServerError for unexpected/unhandled errors
*
* Usage:
* 1. Register after all routes: `app.use(errorHandler);`
* 2. Throw `HttpError` subclasses in your controllers/services
* 3. Any other uncaught error is logged and returned as 500 Internal Server Error
*/
export function errorHandler(
err: any,
req: Request,
res: Response,
next: NextFunction
) => {
console.error(`Error: ${error.message}`);
return res.status(500).json({ message: "Internal server error" });
};
) {
if (err instanceof HttpError) {
return res.status(err.statusCode).json({ statusCode: err.statusCode, error: err.message });
}
console.error("Unexpected error:", err);
const internalError = new InternalServerError(
"An unexpected error occurred. Please try again later."
);
return res.status(internalError.statusCode).json({ error: internalError.message });
}