Skip full user auth for most page renders
Previously, the user's session cookie was being checked against the
database for all non-static requests. However, this is not really
needed and wastes resources (and is slow).
For most page views (e.g. index, channel page), just parsing the value
of the cookie is sufficient:
* The cookies are already HMAC signed, so tampering with them ought to
be for all reasonable purposes, impossible.
* Assuming the worst case, all a nefarious user could manage to do is
change the text of the "Welcome, {user}" and cause a (non-functional)
ACP link to appear clientside, both of which are already possible by
using the Inspect Element tool.
For authenticated pages (currently, the ACP, and anything under
/account/), the full database check is still performed (for now).
This commit is contained in:
parent
0118a6fb15
commit
6043647cb7
8 changed files with 154 additions and 88 deletions
|
|
@ -1,19 +1,62 @@
|
|||
import { setAuthCookie } from '../webserver';
|
||||
const STATIC_RESOURCE = /\..+$/;
|
||||
|
||||
export default function initialize(app, session) {
|
||||
app.use((req, res, next) => {
|
||||
app.use(async (req, res, next) => {
|
||||
if (STATIC_RESOURCE.test(req.path)) {
|
||||
return next();
|
||||
} else if (!req.signedCookies || !req.signedCookies.auth) {
|
||||
return next();
|
||||
} else {
|
||||
session.verifySession(req.signedCookies.auth, (err, account) => {
|
||||
if (!err) {
|
||||
req.user = res.user = account;
|
||||
}
|
||||
const [
|
||||
name, expiration, salt, hash, global_rank
|
||||
] = req.signedCookies.auth.split(':');
|
||||
|
||||
next();
|
||||
});
|
||||
if (!name || !expiration || !salt || !hash) {
|
||||
// Invalid auth cookie
|
||||
return next();
|
||||
}
|
||||
|
||||
let rank;
|
||||
if (!global_rank) {
|
||||
rank = await backfillRankIntoAuthCookie(
|
||||
session,
|
||||
new Date(parseInt(expiration, 10)),
|
||||
req,
|
||||
res
|
||||
);
|
||||
} else {
|
||||
rank = parseInt(global_rank, 10);
|
||||
}
|
||||
|
||||
res.locals.loggedIn = true;
|
||||
res.locals.loginName = name;
|
||||
res.locals.superadmin = rank >= 255;
|
||||
next();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function backfillRankIntoAuthCookie(session, expiration, req, res) {
|
||||
return new Promise((resolve, reject) => {
|
||||
session.verifySession(req.signedCookies.auth, (err, account) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
session.genSession(account, expiration, (err2, auth) => {
|
||||
if (err2) {
|
||||
// genSession never returns an error, but it still
|
||||
// has a callback parameter for one, so just in case...
|
||||
reject(new Error('This should never happen: ' + err2));
|
||||
return;
|
||||
}
|
||||
|
||||
setAuthCookie(req, res, expiration, auth);
|
||||
|
||||
resolve(parseInt(auth.split(':')[4], 10));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue