|
@@ -2,13 +2,19 @@ import crypto from 'node:crypto';
|
|
|
|
|
|
|
|
const COOKIE_NAME = 'ppai_session';
|
|
const COOKIE_NAME = 'ppai_session';
|
|
|
const DEFAULT_MAX_AGE = 12;
|
|
const DEFAULT_MAX_AGE = 12;
|
|
|
|
|
+const DEFAULT_REFRESH_THRESHOLD = 2;
|
|
|
|
|
|
|
|
-const getConfig = () => ({
|
|
|
|
|
- username: process.env.PPAI_AUTH_USER || 'admin',
|
|
|
|
|
- password: process.env.PPAI_AUTH_PASSWORD || 'admin123',
|
|
|
|
|
- secret: process.env.PPAI_AUTH_SECRET || 'ppai-dev-secret',
|
|
|
|
|
- maxAge: Number(process.env.PPAI_AUTH_MAX_AGE || DEFAULT_MAX_AGE) * 60 * 60 * 1000,
|
|
|
|
|
-});
|
|
|
|
|
|
|
+const getConfig = () => {
|
|
|
|
|
+ const maxAge = Number(process.env.PPAI_AUTH_MAX_AGE || DEFAULT_MAX_AGE) * 60 * 60 * 1000;
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ username: process.env.PPAI_AUTH_USER || 'admin',
|
|
|
|
|
+ password: process.env.PPAI_AUTH_PASSWORD || 'admin123',
|
|
|
|
|
+ secret: process.env.PPAI_AUTH_SECRET || 'ppai-dev-secret',
|
|
|
|
|
+ maxAge,
|
|
|
|
|
+ refreshThreshold: Number(process.env.PPAI_AUTH_REFRESH_THRESHOLD || DEFAULT_REFRESH_THRESHOLD),
|
|
|
|
|
+ };
|
|
|
|
|
+};
|
|
|
|
|
|
|
|
const base64UrlEncode = (value) => Buffer.from(value).toString('base64url');
|
|
const base64UrlEncode = (value) => Buffer.from(value).toString('base64url');
|
|
|
const base64UrlDecode = (value) => Buffer.from(value, 'base64url').toString();
|
|
const base64UrlDecode = (value) => Buffer.from(value, 'base64url').toString();
|
|
@@ -56,6 +62,22 @@ export const createSession = (username) => {
|
|
|
return `${payload}.${signature}`;
|
|
return `${payload}.${signature}`;
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
|
|
+export const refreshSessionIfNeeded = (res, session) => {
|
|
|
|
|
+ if (!session?.username || !session?.exp) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const { refreshThreshold } = getConfig();
|
|
|
|
|
+ const remainingTime = session.exp - Date.now();
|
|
|
|
|
+
|
|
|
|
|
+ if (remainingTime > refreshThreshold) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ res.cookie(authCookieName, createSession(session.username), cookieOptions());
|
|
|
|
|
+ return true;
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
export const verifySession = (token) => {
|
|
export const verifySession = (token) => {
|
|
|
if (!token || typeof token !== 'string') {
|
|
if (!token || typeof token !== 'string') {
|
|
|
return null;
|
|
return null;
|
|
@@ -77,7 +99,7 @@ export const verifySession = (token) => {
|
|
|
if (!session?.username || !session?.exp || Date.now() > session.exp) {
|
|
if (!session?.username || !session?.exp || Date.now() > session.exp) {
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
- return { username: session.username };
|
|
|
|
|
|
|
+ return { username: session.username, exp: session.exp };
|
|
|
}
|
|
}
|
|
|
catch {
|
|
catch {
|
|
|
return null;
|
|
return null;
|