fix: use new token with scope

This commit is contained in:
arc-alex
2025-08-18 15:29:18 +02:00
committed by Carlos Valente
parent 5a4494ba85
commit 3b38756dda
+33 -4
View File
@@ -54,10 +54,18 @@ export function makeAuthenticateMiddleware(prefix: string) {
} }
function authenticate(req: Request, res: Response, next: NextFunction) { function authenticate(req: Request, res: Response, next: NextFunction) {
const token = req.query.token || req.cookies?.token; if (req.query.token) {
if (token && token === hashedPassword) { if (req.query.token === hashedPassword) {
return next(); return next();
} }
}
if (req.cookies?.token) {
const tokenFromCookie = getTokenFromCookie(req.cookies.token);
if (tokenFromCookie === hashedPassword) {
return next();
}
}
res.status(401).send('Unauthorized'); res.status(401).send('Unauthorized');
} }
@@ -74,9 +82,12 @@ export function makeAuthenticateMiddleware(prefix: string) {
} }
// we expect the token to be in the cookies // we expect the token to be in the cookies
if (req.cookies?.token === hashedPassword) { if (req.cookies?.token) {
const tokenFromCookie = getTokenFromCookie(req.cookies.token);
if (tokenFromCookie === hashedPassword) {
return next(); return next();
} }
}
// we use query params for generating authenticated URLs and for clients like the companion module // we use query params for generating authenticated URLs and for clients like the companion module
// if the user gives is a token in the query params, we set the cookie to be used in further requests // if the user gives is a token in the query params, we set the cookie to be used in further requests
@@ -105,10 +116,13 @@ export function authenticateSocket(_ws: WebSocket, req: IncomingMessage, next: (
const cookieString = req.headers.cookie; const cookieString = req.headers.cookie;
if (typeof cookieString === 'string') { if (typeof cookieString === 'string') {
const cookies = parseCookie(cookieString); const cookies = parseCookie(cookieString);
if (cookies.token === hashedPassword) { if (cookies.token) {
const token = getTokenFromCookie(cookies.token);
if (token === hashedPassword) {
return next(); return next();
} }
} }
}
// check if token is in the params // check if token is in the params
const url = new URL(req.url || '', `http://${req.headers.host}`); const url = new URL(req.url || '', `http://${req.headers.host}`);
@@ -133,3 +147,18 @@ function setSessionCookie(res: Response, token: string) {
sameSite: 'none', // allow cookies to be sent in cross-origin requests (e.g., iframes) sameSite: 'none', // allow cookies to be sent in cross-origin requests (e.g., iframes)
}); });
} }
/**
* When calling this function we already know a cookie called 'token' exists
* And want to extract its value
*/
function getTokenFromCookie(cookieContents: string): string | undefined {
try {
const cookie = JSON.parse(cookieContents);
if (cookie && typeof cookie.token === 'string') {
return cookie.token;
}
} catch (_) {
// no error handling to do here
}
}