mirror of
https://github.com/Spengreb/sync.git
synced 2026-05-14 03:32:06 +00:00
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).
52 lines
1.5 KiB
JavaScript
52 lines
1.5 KiB
JavaScript
var dbAccounts = require("./database/accounts");
|
|
var util = require("./utilities");
|
|
var crypto = require("crypto");
|
|
|
|
function sha256(input) {
|
|
var hash = crypto.createHash("sha256");
|
|
hash.update(input);
|
|
return hash.digest("base64");
|
|
}
|
|
|
|
exports.genSession = function (account, expiration, cb) {
|
|
if (expiration instanceof Date) {
|
|
expiration = Date.parse(expiration);
|
|
}
|
|
|
|
var salt = crypto.pseudoRandomBytes(24).toString("base64");
|
|
var hashInput = [account.name, account.password, expiration, salt].join(":");
|
|
var hash = sha256(hashInput);
|
|
|
|
cb(null, [account.name, expiration, salt, hash, account.global_rank].join(":"));
|
|
};
|
|
|
|
exports.verifySession = function (input, cb) {
|
|
if (typeof input !== "string") {
|
|
return cb(new Error("Invalid auth string"));
|
|
}
|
|
|
|
var parts = input.split(":");
|
|
if (parts.length !== 4 && parts.length !== 5) {
|
|
return cb(new Error("Invalid auth string"));
|
|
}
|
|
|
|
const [name, expiration, salt, hash, global_rank] = parts;
|
|
|
|
if (Date.now() > parseInt(expiration, 10)) {
|
|
return cb(new Error("Session expired"));
|
|
}
|
|
|
|
dbAccounts.getUser(name, function (err, account) {
|
|
if (err) {
|
|
if (!(err instanceof Error)) err = new Error(err);
|
|
return cb(err);
|
|
}
|
|
|
|
var hashInput = [account.name, account.password, expiration, salt].join(":");
|
|
if (sha256(hashInput) !== hash) {
|
|
return cb(new Error("Invalid auth string"));
|
|
}
|
|
|
|
cb(null, account);
|
|
});
|
|
};
|