trilium/routes/api/login.js

72 lines
2.1 KiB
JavaScript
Raw Normal View History

"use strict";
const express = require('express');
const router = express.Router();
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 source_id = require('../../services/source_id');
const auth = require('../../services/auth');
const password_encryption = require('../../services/password_encryption');
const protected_session = require('../../services/protected_session');
2017-12-04 11:29:23 +08:00
const app_info = require('../../services/app_info');
router.post('/sync', async (req, res, next) => {
2017-12-11 04:45:17 +08:00
const timestampStr = req.body.timestamp;
2017-12-11 04:45:17 +08:00
const timestamp = utils.parseDate(timestampStr);
const now = new Date();
if (Math.abs(timestamp.getTime() - now.getTime()) > 5000) {
2017-10-29 10:17:00 +08:00
res.status(400);
res.send({ message: 'Auth request time is out of sync' });
}
2017-10-30 02:55:48 +08:00
const dbVersion = req.body.dbVersion;
2017-10-29 10:17:00 +08:00
2017-12-04 11:29:23 +08:00
if (dbVersion !== app_info.db_version) {
2017-10-29 10:17:00 +08:00
res.status(400);
2017-12-04 11:29:23 +08:00
res.send({ message: 'Non-matching db versions, local is version ' + app_info.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) {
res.status(400);
2017-12-11 04:45:17 +08:00
res.send({ message: "Sync login hash doesn't match" });
2017-10-29 10:17:00 +08:00
}
req.session.loggedIn = true;
res.send({
sourceId: source_id.currentSourceId
});
});
// this is for entering protected mode so user has to be already logged-in (that's the reason we don't require username)
2017-11-11 11:55:19 +08:00
router.post('/protected', auth.checkApiAuth, async (req, res, next) => {
const password = req.body.password;
if (!await password_encryption.verifyPassword(password)) {
2017-11-11 11:55:19 +08:00
res.send({
success: false,
message: "Given current password doesn't match hash"
2017-11-11 11:55:19 +08:00
});
return;
}
const decryptedDataKey = await password_encryption.getDataKey(password);
const protectedSessionId = protected_session.setDataKey(req, decryptedDataKey);
res.send({
success: true,
protectedSessionId: protectedSessionId
});
});
module.exports = router;