1 var dbAccounts = require("./database/accounts");
2 var crypto = require("crypto");
4 function sha256(input) {
5 var hash = crypto.createHash("sha256");
7 return hash.digest("base64");
10 exports.genSession = function (account, expiration, cb) {
11 if (expiration instanceof Date) {
12 expiration = Date.parse(expiration);
15 var salt = crypto.pseudoRandomBytes(24).toString("base64");
16 var hashInput = [account.name, account.password, expiration, salt].join(":");
17 var hash = sha256(hashInput);
19 cb(null, [account.name, expiration, salt, hash, account.global_rank].join(":"));
22 exports.verifySession = function (input, cb) {
23 if (typeof input !== "string") {
24 return cb(new Error("Invalid auth string"));
27 var parts = input.split(":");
28 if (parts.length !== 4 && parts.length !== 5) {
29 return cb(new Error("Invalid auth string"));
32 const [name, expiration, salt, hash, _global_rank] = parts;
34 if (Date.now() > parseInt(expiration, 10)) {
35 return cb(new Error("Session expired"));
38 dbAccounts.getUser(name, function (err, account) {
40 if (!(err instanceof Error)) err = new Error(err);
44 var hashInput = [account.name, account.password, expiration, salt].join(":");
45 if (sha256(hashInput) !== hash) {
46 return cb(new Error("Invalid auth string"));