-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthCore.ts
More file actions
224 lines (193 loc) · 7.75 KB
/
authCore.ts
File metadata and controls
224 lines (193 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
* Core authentication routes
* Handles logout, profile, locale, health, and error pages
* Status (/api/auth/status) is served by authStatusContractRouter
* Login/callback handled by Better Auth at /api/auth/v2/*
*/
import { fromNodeHeaders } from 'better-auth/node';
import { and, eq, like } from 'drizzle-orm';
import express, { type Router, type Response } from 'express';
import { auth } from '../../config/betterAuth.js';
import { env } from '../../config/env.js';
import { ba_accounts } from '../../database/schema/auth.js';
import { getDrizzleInstance } from '../../database/services/DrizzleService.js';
import authMiddlewareModule from '../../middleware/authMiddleware.js';
import * as chatMemory from '../../services/chat/ChatMemoryService.js';
import { createLogger } from '../../utils/logger.js';
import type { AuthRequest, LocaleUpdateBody } from './types.js';
const log = createLogger('authCore');
const { requireAuth: ensureAuthenticated } = authMiddlewareModule;
const router: Router = express.Router();
// ============================================================================
// Health & Test Routes
// ============================================================================
router.get('/health', (_req: AuthRequest, res: Response): void => {
res.status(200).json({ status: 'ok', message: 'Backend is healthy' });
});
router.get('/test', (_req: AuthRequest, res: Response): void => {
res.json({
success: true,
message: 'Auth routes are working',
timestamp: new Date().toISOString(),
});
});
// ============================================================================
// Error Route
// ============================================================================
router.get('/error', (req: AuthRequest, res: Response): void => {
const htmlEscape = (s: string) =>
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
const errorCode = htmlEscape(String(req.query.message || 'unknown_error'));
const correlationId = htmlEscape(String(req.query.correlationId || 'N/A'));
const retry = req.query.retry === 'true';
log.error(`[Auth Error] Code: ${errorCode}, Correlation: ${correlationId}`);
if (retry) {
res.status(401).send(`<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="2;url=/auth/login">
<title>Anmeldung fehlgeschlagen</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: #f5f5f5; color: #333; }
.card { background: #fff; border-radius: 12px; padding: 2.5rem; max-width: 420px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
h1 { color: #316049; font-size: 1.25rem; margin: 0 0 0.75rem; }
p { margin: 0 0 1rem; line-height: 1.5; font-size: 0.95rem; }
a { color: #316049; font-weight: 600; text-decoration: none; }
a:hover { text-decoration: underline; }
.hint { font-size: 0.8rem; color: #888; }
</style>
</head>
<body>
<div class="card">
<h1>Anmeldung fehlgeschlagen</h1>
<p>Du wirst in wenigen Sekunden automatisch weitergeleitet…</p>
<p><a href="/auth/login">Jetzt erneut anmelden</a></p>
<p class="hint">Fehler: ${errorCode} · Referenz: ${correlationId}</p>
</div>
</body>
</html>`);
return;
}
res
.status(401)
.send(
`Authentication Error: ${errorCode}. Please try again or contact support with correlation ID: ${correlationId}`
);
});
// ============================================================================
// Logout Routes
// ============================================================================
router.get('/logout', async (req: AuthRequest, res: Response): Promise<void> => {
if (req.user?.id) {
try {
await chatMemory.clearConversation(req.user.id);
} catch (error) {
log.error('[Auth GET /logout] Error clearing chat memory:', error);
}
}
try {
await auth.api.signOut({ headers: fromNodeHeaders(req.headers) });
} catch {
// Sign-out may fail if no session — that's fine
}
res.status(200).json({ success: true, message: 'Logout completed', sessionCleared: true });
});
router.post('/logout', async (req: AuthRequest, res: Response): Promise<void> => {
const keycloakLogoutUrl = `${env.KEYCLOAK_BASE_URL}/realms/${env.KEYCLOAK_REALM}/protocol/openid-connect/logout`;
if (req.user?.id) {
try {
await chatMemory.clearConversation(req.user.id);
} catch (error) {
log.error('[Auth POST /logout] Error clearing chat memory:', error);
}
}
// Look up id_token from ba_accounts for Keycloak SSO logout
let keycloakBackgroundLogoutUrl: string | null = null;
if (req.user?.id) {
try {
const db = getDrizzleInstance();
const rows = await db
.select({ idToken: ba_accounts.id_token })
.from(ba_accounts)
.where(
and(eq(ba_accounts.user_id, req.user.id), like(ba_accounts.provider_id, 'keycloak-%'))
)
.limit(1);
log.info(
'[Auth Logout] ba_accounts lookup for user_id=%s: rows=%d, has_id_token=%s',
req.user.id,
rows.length,
rows[0]?.idToken != null ? 'yes' : 'no'
);
if (rows[0]?.idToken) {
keycloakBackgroundLogoutUrl = `${keycloakLogoutUrl}?id_token_hint=${rows[0].idToken}`;
}
} catch (err) {
// Account lookup may fail — proceed without SSO logout, but log the error
log.error(
'[Auth Logout] ba_accounts query threw for user_id=%s: %s',
req.user.id,
(err as Error).message
);
}
}
try {
await auth.api.signOut({ headers: fromNodeHeaders(req.headers) });
} catch (err) {
// Sign-out may fail if no session — log so we know it happened
log.warn('[Auth Logout] auth.api.signOut threw: %s', (err as Error).message);
}
res.json({
success: true,
message: 'Logout successful',
sessionDestroyed: true,
sessionCleared: true,
cookieCleared: true,
redirectToHome: true,
timestamp: Date.now(),
keycloakBackgroundLogoutUrl,
authentikBackgroundLogoutUrl: keycloakBackgroundLogoutUrl,
});
});
// ============================================================================
// Profile & Locale Routes
// ============================================================================
router.get('/profile', ensureAuthenticated, (req: AuthRequest, res: Response): void => {
res.json({ user: req.user || null });
});
router.get('/locale', ensureAuthenticated, (req: AuthRequest, res: Response): void => {
try {
const userLocale = req.user?.locale || 'de-DE';
res.json({ success: true, locale: userLocale });
} catch (error) {
log.error('[Auth /locale GET] Error:', error);
res.status(500).json({ success: false, error: 'Failed to get locale' });
}
});
router.put(
'/locale',
ensureAuthenticated,
async (req: AuthRequest, res: Response): Promise<void> => {
try {
const { locale } = req.body as LocaleUpdateBody;
if (!locale || !['de-DE', 'de-AT'].includes(locale)) {
res.status(400).json({
success: false,
error: 'Invalid locale. Must be de-DE or de-AT',
});
return;
}
const { getProfileService } = await import('../../services/user/ProfileService.js');
const profileService = getProfileService();
await profileService.updateProfile(req.user!.id, { locale });
req.user!.locale = locale;
res.json({ success: true, message: 'Locale updated successfully', locale });
} catch (error) {
log.error('[Auth /locale PUT] Error:', error);
res.status(500).json({ success: false, error: 'Failed to update locale' });
}
}
);
export default router;