trilium/src/routes/api/login.js

79 lines
2.4 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');
2018-04-03 08:46:46 +08:00
const dateUtils = require('../../services/date_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');
const eventService = require('../../services/events');
const cls = require('../../services/cls');
const sqlInit = require('../../services/sql_init');
async function loginSync(req) {
if (!await sqlInit.schemaExists()) {
return [400, { message: "DB schema does not exist, can't sync." }];
}
2017-12-11 04:45:17 +08:00
const timestampStr = req.body.timestamp;
2018-04-03 08:46:46 +08:00
const timestamp = dateUtils.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
}
const syncVersion = req.body.syncVersion;
2017-10-29 10:17:00 +08:00
if (syncVersion !== appInfo.syncVersion) {
return [400, { message: 'Non-matching sync versions, local is version ' + appInfo.syncVersion }];
2017-10-29 10:17:00 +08:00
}
2018-04-03 09:47:46 +08:00
const documentSecret = await options.getOption('documentSecret');
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(decryptedDataKey);
2018-04-22 00:23:35 +08:00
// this is set here so that event handlers have access to the protected session
cls.namespace.set('protectedSessionId', protectedSessionId);
eventService.emit(eventService.ENTER_PROTECTED_SESSION);
return {
success: true,
protectedSessionId: protectedSessionId
};
}
module.exports = {
loginSync,
loginToProtectedSession
};