mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-07-07 09:51:37 +00:00
Commit middlewear to read login (cookie/JWT) and sets req.user, and requireAuth blocks anyone not logged in with a 401 error.
This commit is contained in:
parent
3a1482c721
commit
649f40ff37
2 changed files with 62 additions and 0 deletions
13
server/middleware/requireAuth.js
Normal file
13
server/middleware/requireAuth.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
// server/middleware/requireAuth.js
|
||||
//
|
||||
// Tiny guard that ensures req.user is present AFTER sessionOrJwt has run.
|
||||
// Sends a clean 401 instead of leaking as a 500.
|
||||
module.exports = (auth) => {
|
||||
return (req, res, next) => {
|
||||
// If Auth added a user (via cookie session or Bearer) we proceed.
|
||||
if (req.user && req.user.id) return next()
|
||||
|
||||
// Otherwise make it explicit that this route requires auth.
|
||||
res.status(401).send('Unauthorized')
|
||||
}
|
||||
}
|
||||
49
server/middleware/sessionOrJwt.js
Normal file
49
server/middleware/sessionOrJwt.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// server/middleware/sessionOrJwt.js
|
||||
let AchievementManager = null;
|
||||
try {
|
||||
// If you actually have an achievements manager, require it here.
|
||||
// Otherwise keep this try/catch and we'll simply no-op below.
|
||||
AchievementManager = require('../managers/AchievementManager');
|
||||
} catch (_) {
|
||||
// optional; safely ignored when absent
|
||||
}
|
||||
|
||||
function fireLoginEvent(req) {
|
||||
try {
|
||||
// Only call if the module exists AND exposes applyEvent
|
||||
if (!AchievementManager || typeof AchievementManager.applyEvent !== 'function') return;
|
||||
if (req._absLoginEventSent) return;
|
||||
|
||||
const user = req.user;
|
||||
const uid = user && (user.id || user.userId);
|
||||
if (!uid) return;
|
||||
|
||||
req._absLoginEventSent = true;
|
||||
AchievementManager.applyEvent(String(uid), 'userLoggedIn').catch(() => {});
|
||||
} catch (_) {
|
||||
// never break auth flow
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (auth) => {
|
||||
if (!auth || typeof auth.isAuthenticated !== 'function') {
|
||||
throw new Error('[sessionOrJwt] auth.isAuthenticated missing');
|
||||
}
|
||||
return (req, res, next) => {
|
||||
// If something upstream already attached req.user, fire and continue.
|
||||
if (req.user && (req.user.id || req.user.userId)) {
|
||||
fireLoginEvent(req);
|
||||
return next();
|
||||
}
|
||||
|
||||
auth.isAuthenticated(req, res, (err) => {
|
||||
if (err) return next(err);
|
||||
if (req.user && (req.user.id || req.user.userId)) {
|
||||
fireLoginEvent(req);
|
||||
return next();
|
||||
}
|
||||
// IMPORTANT: 401 here (not 500) when no credentials
|
||||
return res.status(401).send('Unauthorized');
|
||||
});
|
||||
};
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue