This commit is contained in:
seb
2026-09-30 09:47:59 +02:00
parent 1de802fbaa
commit 82cc138ba6
15 changed files with 624 additions and 11 deletions

View File

@@ -0,0 +1,66 @@
import chalk from 'chalk';
import * as db from '../../db/posterminal.js';
export function extractPosToken(req) {
const authHeader = req.headers.authorization;
if (typeof authHeader === 'string' && authHeader.trim()) {
const trimmed = authHeader.trim();
if (/^Bearer\s+/i.test(trimmed)) {
return trimmed.replace(/^Bearer\s+/i, '').trim();
}
if (/^Basic\s+/i.test(trimmed)) {
const b64 = trimmed.replace(/^Basic\s+/i, '').trim();
try {
const decoded = Buffer.from(b64, 'base64').toString('utf8');
const parts = decoded.split(':');
return (parts[1] || parts[0] || '').trim();
} catch {
return b64;
}
}
return trimmed;
}
for (const key of ['x-auth-token', 'authtoken', 'auth-token', 'token', 'x-token']) {
const val = req.headers[key];
if (typeof val === 'string' && val.trim()) {
return val.trim();
}
}
const queryToken = req.query?.authToken || req.query?.token;
if (typeof queryToken === 'string' && queryToken.trim()) {
return queryToken.trim();
}
return '';
}
/**
* Verifies the POS terminal token from the Authorization header and attaches
* `req.posterminal`.
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
export async function posAuthMiddleware(req, res, next) {
const token = extractPosToken(req);
if (!token) {
console.log(chalk.yellow(' [posAuth] No token found in headers:'), req.headers);
return res.status(401).json({ Message: 'Authorization has been denied for this request.' });
}
try {
const terminal = await db.findByToken(token);
if (!terminal) {
console.log(chalk.yellow(` [posAuth] Unknown token "${token}", headers:`), req.headers);
return res.status(401).json({ Message: 'Authorization has been denied for this request.' });
}
req.posterminal = terminal;
next();
} catch (err) {
console.error('POS auth error:', err);
return res.status(500).json({ Message: 'Internal server error' });
}
}