import { Router } from 'express'; import crypto from 'crypto'; import { registerToken } from '../middleware/auth.js'; const router = Router(); let simplePassword = null; export function initAuth() { if (process.env.USE_KEYCLOAK === 'true') { console.log('Auth mode: Keycloak'); return; } simplePassword = crypto.randomBytes(16).toString('hex'); console.log('\n========================================'); console.log('ADMIN PASSWORD (save this - shown once):'); console.log(simplePassword); console.log('========================================\n'); } export function getAuthMode() { return process.env.USE_KEYCLOAK === 'true' ? 'keycloak' : 'simple'; } export function getKeycloakConfig() { return { url: process.env.KEYCLOAK_URL || '', realm: process.env.KEYCLOAK_REALM || '', clientId: process.env.KEYCLOAK_CLIENT_ID || '', }; } /** * @openapi * /auth/config: * get: * summary: Get authentication configuration * tags: [Auth] * responses: * 200: * description: Auth configuration * content: * application/json: * schema: * type: object * properties: * mode: * type: string * keycloak: * type: object */ router.get('/config', (req, res) => { res.json({ mode: getAuthMode(), keycloak: getKeycloakConfig(), }); }); /** * @openapi * /auth/login: * post: * summary: Login with password * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * password: * type: string * responses: * 200: * description: Login successful * content: * application/json: * schema: * type: object * properties: * token: * type: string * expiresIn: * type: integer * 401: * description: Invalid password */ router.post('/login', (req, res) => { if (process.env.USE_KEYCLOAK === 'true') { return res.status(400).json({ error: 'Keycloak mode enabled - use OAuth flow' }); } const { password } = req.body; if (!password || password !== simplePassword) { return res.status(401).json({ error: 'Invalid password' }); } const token = crypto.randomBytes(32).toString('hex'); registerToken(token); res.json({ token, expiresIn: 3600 }); }); export default router;