2024-07-18 21:37:45 +03:00
import session from "express-session" ;
2024-07-18 22:59:39 +03:00
import sessionFileStore from "session-file-store" ;
2024-07-18 21:35:17 +03:00
import sessionSecret from "../services/session_secret.js" ;
import dataDir from "../services/data_dir.js" ;
2025-02-10 08:35:01 +01:00
import config from "../services/config.js" ;
2025-03-26 00:04:55 +01:00
import totp from "../services/totp.js" ;
import open_id from "../services/open_id.js" ;
import type { Request , Response , NextFunction } from "express" ;
2024-07-18 22:59:39 +03:00
const FileStore = sessionFileStore ( session ) ;
2023-05-07 15:23:46 +02:00
const sessionParser = session ( {
secret : sessionSecret ,
resave : false , // true forces the session to be saved back to the session store, even if the session was never modified during the request.
saveUninitialized : false , // true forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
cookie : {
2025-02-10 19:07:21 +01:00
path : config.Session.cookiePath ,
2023-05-07 15:23:46 +02:00
httpOnly : true ,
2025-02-13 09:07:25 +01:00
maxAge : config.Session.cookieMaxAge * 1000 // needs value in milliseconds
2023-05-07 15:23:46 +02:00
} ,
2025-01-09 18:07:02 +02:00
name : "trilium.sid" ,
2023-05-07 15:23:46 +02:00
store : new FileStore ( {
2025-02-13 08:39:02 +01:00
ttl : config.Session.cookieMaxAge ,
2023-05-07 15:23:46 +02:00
path : ` ${ dataDir . TRILIUM_DATA_DIR } /sessions `
} )
} ) ;
2025-03-26 00:04:55 +01:00
const checkAuthState = ( req : Request , res : Response , next : NextFunction ) = > {
if ( ! req . session . loggedIn || req . path === '/login' ) {
return next ( ) ;
}
const currentTotpStatus = totp . isTotpEnabled ( ) ;
const currentSsoStatus = open_id . isOpenIDEnabled ( ) ;
const lastAuthState = req . session . lastAuthState || {
totpEnabled : false ,
ssoEnabled : false
} ;
if ( lastAuthState . totpEnabled !== currentTotpStatus ||
lastAuthState . ssoEnabled !== currentSsoStatus ) {
req . session . destroy ( ( err ) = > {
if ( err ) {
console . error ( 'Error destroying session:' , err ) ;
}
res . redirect ( '/login' ) ;
} ) ;
return ;
}
next ( ) ;
} ;
export default function ( req : Request , res : Response , next : NextFunction ) {
sessionParser ( req , res , ( ) = > {
checkAuthState ( req , res , next ) ;
} ) ;
}