sync/src/session.js

52 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-02-16 03:56:00 +00:00
var dbAccounts = require("./database/accounts");
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(":"));
2015-02-16 03:56:00 +00:00
};
exports.verifySession = function (input, cb) {
2015-02-20 02:30:35 +00:00
if (typeof input !== "string") {
return cb(new Error("Invalid auth string"));
2015-02-20 02:30:35 +00:00
}
2015-02-16 03:56:00 +00:00
var parts = input.split(":");
if (parts.length !== 4 && parts.length !== 5) {
return cb(new Error("Invalid auth string"));
2015-02-16 03:56:00 +00:00
}
2018-04-07 22:30:30 +00:00
const [name, expiration, salt, hash, _global_rank] = parts;
2015-02-16 03:56:00 +00:00
if (Date.now() > parseInt(expiration, 10)) {
return cb(new Error("Session expired"));
2015-02-16 03:56:00 +00:00
}
dbAccounts.getUser(name, function (err, account) {
if (err) {
if (!(err instanceof Error)) err = new Error(err);
2015-02-16 03:56:00 +00:00
return cb(err);
}
var hashInput = [account.name, account.password, expiration, salt].join(":");
if (sha256(hashInput) !== hash) {
return cb(new Error("Invalid auth string"));
2015-02-16 03:56:00 +00:00
}
cb(null, account);
});
};