Notes/src/services/auth.ts

167 lines
5.4 KiB
TypeScript
Raw Normal View History

import etapiTokenService from "./etapi_tokens.js";
import log from "./log.js";
import sqlInit from "./sql_init.js";
import { isElectron } from "./utils.js";
import passwordEncryptionService from "./encryption/password_encryption.js";
import config from "./config.js";
import passwordService from "./encryption/password.js";
2025-03-26 01:36:48 +01:00
import totp from "./totp.js";
2025-03-26 02:04:24 +01:00
import openID from "./open_id.js";
import options from "./options.js";
import attributes from "./attributes.js";
2025-01-09 18:07:02 +02:00
import type { NextFunction, Request, Response } from "express";
const noAuthentication = config.General && config.General.noAuthentication === true;
2017-10-25 22:39:21 -04:00
function checkAuth(req: Request, res: Response, next: NextFunction) {
2025-03-28 02:37:12 +01:00
if (!sqlInit.isDbInitialized()) {
res.redirect('setup');
}
2025-03-26 01:36:48 +01:00
const currentTotpStatus = totp.isTotpEnabled();
2025-03-26 02:04:24 +01:00
const currentSsoStatus = openID.isOpenIDEnabled();
2025-03-26 01:36:48 +01:00
const lastAuthState = req.session.lastAuthState || { totpEnabled: false, ssoEnabled: false };
2025-03-28 02:37:12 +01:00
if (isElectron) {
2025-03-26 10:58:14 +01:00
next();
return;
2025-03-26 01:36:48 +01:00
} else if (currentTotpStatus !== lastAuthState.totpEnabled || currentSsoStatus !== lastAuthState.ssoEnabled) {
req.session.destroy((err) => {
if (err) console.error('Error destroying session:', err);
res.redirect('login');
2025-03-26 01:36:48 +01:00
});
return;
} else if (currentSsoStatus) {
2025-03-26 02:39:29 +01:00
if (req.oidc?.isAuthenticated() && req.session.loggedIn) {
2024-09-07 10:21:41 -07:00
next();
2025-03-26 02:39:29 +01:00
return;
2024-09-07 10:21:41 -07:00
}
res.redirect('login');
2025-03-26 02:39:29 +01:00
return;
2025-03-26 10:58:14 +01:00
} else if (!req.session.loggedIn && !noAuthentication) {
// cannot use options.getOptionBool currently => it will throw an error on new installations
// TriliumNextTODO: look into potentially creating an getOptionBoolOrNull instead
const hasRedirectBareDomain = options.getOptionOrNull("redirectBareDomain") === "true";
if (hasRedirectBareDomain) {
// Check if any note has the #shareRoot label
const shareRootNotes = attributes.getNotesWithLabel("shareRoot");
if (shareRootNotes.length === 0) {
res.status(404).json({ message: "Share root not found. Please set up a note with #shareRoot label first." });
return;
}
}
res.redirect(hasRedirectBareDomain ? "share" : "login");
2024-09-07 10:21:41 -07:00
} else {
next();
}
}
2018-01-07 09:59:05 -05:00
// for electron things which need network stuff
2023-06-30 11:18:34 +02:00
// currently, we're doing that for file upload because handling form data seems to be difficult
function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction) {
if (!req.session.loggedIn && !isElectron && !noAuthentication) {
2021-04-05 22:37:12 +02:00
reject(req, res, "Logged in session not found");
2025-01-09 18:07:02 +02:00
} else {
2017-10-15 16:32:49 -04:00
next();
}
}
function checkApiAuth(req: Request, res: Response, next: NextFunction) {
if (!req.session.loggedIn && !noAuthentication) {
2021-04-05 22:37:12 +02:00
reject(req, res, "Logged in session not found");
2025-01-09 18:07:02 +02:00
} else {
next();
}
}
function checkAppInitialized(req: Request, res: Response, next: NextFunction) {
2020-06-20 12:31:38 +02:00
if (!sqlInit.isDbInitialized()) {
res.redirect("setup");
2025-01-09 18:07:02 +02:00
} else {
next();
}
}
function checkPasswordSet(req: Request, res: Response, next: NextFunction) {
if (!isElectron && !passwordService.isPasswordSet()) {
2021-12-29 23:37:12 +01:00
res.redirect("set-password");
2021-12-29 23:19:05 +01:00
} else {
next();
}
}
function checkPasswordNotSet(req: Request, res: Response, next: NextFunction) {
if (!isElectron && passwordService.isPasswordSet()) {
2022-01-12 19:32:23 +01:00
res.redirect("login");
} else {
next();
}
}
function checkAppNotInitialized(req: Request, res: Response, next: NextFunction) {
2020-06-20 12:31:38 +02:00
if (sqlInit.isDbInitialized()) {
2019-07-25 21:05:16 +02:00
reject(req, res, "App already initialized.");
2025-01-09 18:07:02 +02:00
} else {
2017-12-03 22:29:23 -05:00
next();
}
}
function checkEtapiToken(req: Request, res: Response, next: NextFunction) {
2022-01-10 17:09:20 +01:00
if (etapiTokenService.isValidAuthHeader(req.headers.authorization)) {
next();
2025-01-09 18:07:02 +02:00
} else {
2022-01-10 17:09:20 +01:00
reject(req, res, "Token not found");
}
}
function reject(req: Request, res: Response, message: string) {
2019-07-25 21:05:16 +02:00
log.info(`${req.method} ${req.path} rejected with 401 ${message}`);
2025-01-09 18:07:02 +02:00
res.setHeader("Content-Type", "text/plain").status(401).send(message);
2019-07-25 21:05:16 +02:00
}
function checkCredentials(req: Request, res: Response, next: NextFunction) {
if (!sqlInit.isDbInitialized()) {
2025-01-09 18:07:02 +02:00
res.setHeader("Content-Type", "text/plain").status(400).send("Database is not initialized yet.");
return;
}
if (!passwordService.isPasswordSet()) {
2025-01-09 18:07:02 +02:00
res.setHeader("Content-Type", "text/plain").status(400).send("Password has not been set yet. Please set a password and repeat the action");
return;
}
2025-01-09 18:07:02 +02:00
const header = req.headers["trilium-cred"] || "";
if (typeof header !== "string") {
2025-01-09 18:07:02 +02:00
res.setHeader("Content-Type", "text/plain").status(400).send("Invalid data type for trilium-cred.");
return;
}
2025-01-09 18:07:02 +02:00
const auth = Buffer.from(header, "base64").toString();
const colonIndex = auth.indexOf(":");
const password = colonIndex === -1 ? "" : auth.substr(colonIndex + 1);
2021-12-29 23:37:12 +01:00
// username is ignored
2021-12-29 23:37:12 +01:00
if (!passwordEncryptionService.verifyPassword(password)) {
2025-01-09 18:07:02 +02:00
res.setHeader("Content-Type", "text/plain").status(401).send("Incorrect password");
} else {
next();
}
}
export default {
2017-10-15 16:32:49 -04:00
checkAuth,
checkApiAuth,
checkAppInitialized,
2021-12-29 23:19:05 +01:00
checkPasswordSet,
2022-01-12 19:32:23 +01:00
checkPasswordNotSet,
2018-01-07 09:59:05 -05:00
checkAppNotInitialized,
checkApiAuthOrElectron,
2022-01-10 17:09:20 +01:00
checkEtapiToken,
checkCredentials
2020-06-20 12:31:38 +02:00
};