trilium/src/services/auth.js

101 lines
2.5 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
const sql = require('./sql');
2019-07-26 03:05:16 +08:00
const log = require('./log');
const sqlInit = require('./sql_init');
const utils = require('./utils');
const passwordEncryptionService = require('./password_encryption');
const optionService = require('./options');
2017-10-26 10:39:21 +08:00
async function checkAuth(req, res, next) {
if (!await sqlInit.isDbInitialized()) {
2017-12-04 11:29:23 +08:00
res.redirect("setup");
}
else if (!req.session.loggedIn && !utils.isElectron()) {
2017-10-16 04:32:49 +08:00
res.redirect("login");
2017-10-26 10:39:21 +08:00
}
else {
next();
}
}
2018-01-07 22:59:05 +08:00
// for electron things which need network stuff
// currently we're doing that for file upload because handling form data seems to be difficult
async function checkApiAuthOrElectron(req, res, next) {
if (!req.session.loggedIn && !utils.isElectron()) {
2019-07-26 03:05:16 +08:00
reject(req, res, "Not authorized");
2018-01-07 22:59:05 +08:00
}
else {
2017-10-16 04:32:49 +08:00
next();
}
}
async function checkApiAuth(req, res, next) {
if (!req.session.loggedIn) {
2019-07-26 03:05:16 +08:00
reject(req, res, "Not authorized");
}
else {
next();
}
}
async function checkAppInitialized(req, res, next) {
if (!await sqlInit.isDbInitialized()) {
res.redirect("setup");
}
else {
next();
}
}
2017-12-04 11:29:23 +08:00
async function checkAppNotInitialized(req, res, next) {
if (await sqlInit.isDbInitialized()) {
2019-07-26 03:05:16 +08:00
reject(req, res, "App already initialized.");
2017-12-04 11:29:23 +08:00
}
else {
next();
}
}
async function checkToken(req, res, next) {
const token = req.headers.authorization;
if (await sql.getValue("SELECT COUNT(*) FROM api_tokens WHERE isDeleted = 0 AND token = ?", [token]) === 0) {
2019-07-26 03:05:16 +08:00
reject(req, res, "Not authorized");
}
else {
next();
}
}
2019-07-26 03:05:16 +08:00
function reject(req, res, message) {
log.info(`${req.method} ${req.path} rejected with 401 ${message}`);
res.status(401).send(message);
}
async function checkBasicAuth(req, res, next) {
const header = req.headers.authorization || '';
const token = header.split(/\s+/).pop() || '';
const auth = new Buffer.from(token, 'base64').toString();
const [username, password] = auth.split(/:/);
const dbUsername = await optionService.getOption('username');
if (dbUsername !== username || !await passwordEncryptionService.verifyPassword(password)) {
res.status(401).send("Not authorized");
}
else {
next();
}
}
2017-10-16 04:32:49 +08:00
module.exports = {
checkAuth,
checkApiAuth,
checkAppInitialized,
2018-01-07 22:59:05 +08:00
checkAppNotInitialized,
checkApiAuthOrElectron,
checkToken,
checkBasicAuth
2017-10-16 04:32:49 +08:00
};