ai-wpa/lib/session.ts

56 lines
1.5 KiB
TypeScript

import session from 'express-session'
import { RedisStore } from 'connect-redis'
import { redisClient } from './redis'
// Extend the session interface to include our custom properties
declare module 'express-session' {
interface SessionData {
userId?: string
user?: {
id: string
email: string
name: string
role: string
avatar?: string
}
accessToken?: string
refreshToken?: string
}
}
// Create session config - use Redis if available, otherwise use memory store
const createSessionConfig = () => {
const baseConfig = {
secret: process.env.SESSION_SECRET || 'your-super-secret-session-key-change-in-production',
resave: false,
saveUninitialized: false,
rolling: true, // Reset expiry on each request
cookie: {
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: 'lax' as const,
},
name: 'sessionId', // Don't use default session name
}
// Only use Redis store if Redis client is available
if (redisClient) {
console.log('Using Redis store for sessions')
return {
...baseConfig,
store: new RedisStore({
client: redisClient,
prefix: 'sess:',
}),
}
} else {
console.warn('Using memory store for sessions - sessions will not persist across server restarts')
return baseConfig
}
}
export const sessionConfig = createSessionConfig()
export const sessionMiddleware = session(sessionConfig)