trilium/src/routes/api/login.js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

"use strict";
2017-11-03 08:48:02 +08:00
const options = require('../../services/options');
2017-10-29 10:17:00 +08:00
const utils = require('../../services/utils');
const sourceIdService = require('../../services/source_id');
const passwordEncryptionService = require('../../services/password_encryption');
const protectedSessionService = require('../../services/protected_session');
const appInfo = require('../../services/app_info');
async function loginSync(req) {
2017-12-11 04:45:17 +08:00
const timestampStr = req.body.timestamp;
const timestamp = utils.parseDateTime(timestampStr);
2017-12-11 04:45:17 +08:00
const now = new Date();
if (Math.abs(timestamp.getTime() - now.getTime()) > 5000) {
return [400, { message: 'Auth request time is out of sync' }];
2017-10-29 10:17:00 +08:00
}
2017-10-30 02:55:48 +08:00
const dbVersion = req.body.dbVersion;
2017-10-29 10:17:00 +08:00
if (dbVersion !== appInfo.db_version) {
return [400, { message: 'Non-matching db versions, local is version ' + appInfo.db_version }];
2017-10-29 10:17:00 +08:00
}
2017-11-03 08:48:02 +08:00
const documentSecret = await options.getOption('document_secret');
2017-12-11 04:45:17 +08:00
const expectedHash = utils.hmac(documentSecret, timestampStr);
2017-10-29 10:17:00 +08:00
const givenHash = req.body.hash;
if (expectedHash !== givenHash) {
return [400, { message: "Sync login hash doesn't match" }];
2017-10-29 10:17:00 +08:00
}
req.session.loggedIn = true;
return {
sourceId: sourceIdService.getCurrentSourceId()
};
}
async function loginToProtectedSession(req) {
const password = req.body.password;
if (!await passwordEncryptionService.verifyPassword(password)) {
return {
success: false,
message: "Given current password doesn't match hash"
};
}
const decryptedDataKey = await passwordEncryptionService.getDataKey(password);
const protectedSessionId = protectedSessionService.setDataKey(req, decryptedDataKey);
return {
success: true,
protectedSessionId: protectedSessionId
};
}
module.exports = {
loginSync,
loginToProtectedSession
};