Spaces:
Running
Running
Okay now add nitro as ssr and add an express backend with a simple login and authentication system that creates session id and stores session id as http only cookie and in the ssr middleware for all routes we do have a check for the http only cookie to check if is present or expired to redirect to home page or to login page
d502d70 verified | ```typescript | |
| import { eventHandler, readBody, setCookie, createError } from 'h3' | |
| import { sessionStore, sessionDuration } from '../middleware/auth' | |
| // Mock user database (use a real database in production) | |
| const users = [ | |
| { id: 1, email: 'admin@vite.com', password: 'admin123', name: 'Admin User' }, | |
| { id: 2, email: 'user@vite.com', password: 'user123', name: 'Regular User' } | |
| ] | |
| export default eventHandler(async (event) => { | |
| const body = await readBody(event) | |
| const { email, password } = body | |
| // Validate input | |
| if (!email || !password) { | |
| throw createError({ | |
| statusCode: 400, | |
| message: 'Email and password are required' | |
| }) | |
| } | |
| // Find user | |
| const user = users.find(u => u.email === email && u.password === password) | |
| if (!user) { | |
| throw createError({ | |
| statusCode: 401, | |
| message: 'Invalid email or password' | |
| }) | |
| } | |
| // Generate session ID | |
| const sessionId = Buffer.from(`${user.id}-${Date.now()}-${Math.random()}`).toString('base64') | |
| // Store session | |
| sessionStore.set(sessionId, { | |
| userId: user.id, | |
| email: user.email, | |
| createdAt: Date.now() | |
| }) | |
| // Set HTTP-only cookie | |
| const cookieOptions = { | |
| httpOnly: true, | |
| secure: process.env.NODE_ENV === 'production', | |
| sameSite: 'lax' as const, | |
| maxAge: sessionDuration / 1000, | |
| path: '/' | |
| } | |
| setCookie(event, 'session_id', sessionId, cookieOptions) | |
| return { | |
| success: true, | |
| user: { | |
| id: user.id, | |
| email: user.email, | |
| name: user.name | |
| } | |
| } | |
| }) | |
| ``` |