-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathsessionAuth.ts
More file actions
78 lines (68 loc) · 2.17 KB
/
sessionAuth.ts
File metadata and controls
78 lines (68 loc) · 2.17 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
import { createApiError } from '@inkeep/agents-core';
import { registerAuthzMeta } from '@inkeep/agents-core/middleware';
import { createMiddleware } from 'hono/factory';
import { HTTPException } from 'hono/http-exception';
import type { AppVariables } from '../types/app';
/**
* Middleware to enforce session-based authentication.
* Requires that a user has already been authenticated via Better Auth session.
* Used primarily for manage routes that require an active user session.
*/
export const sessionAuth = () => {
const mw = createMiddleware(async (c, next) => {
try {
const user = c.get('user');
if (!user) {
throw createApiError({
code: 'unauthorized',
message: 'Please log in to access this resource',
});
}
c.set('userId', user.id);
c.set('userEmail', user.email);
await next();
} catch (error) {
if (error instanceof HTTPException) {
throw error;
}
throw createApiError({
code: 'unauthorized',
message: 'Authentication failed',
});
}
});
registerAuthzMeta(mw, {
description: 'Requires an active user session (cookie-based)',
});
return mw;
};
/**
* Global session middleware - sets user and session in context for all routes
* Used for all routes that require an active user session.
*/
export const sessionContext = () =>
createMiddleware<{ Variables: AppVariables }>(async (c, next) => {
const auth = c.get('auth');
if (!auth) {
c.set('user', null);
c.set('session', null);
await next();
return;
}
// Create headers with x-forwarded-cookie mapped to cookie (browsers forbid setting Cookie header directly)
const headers = new Headers(c.req.raw.headers);
const forwardedCookie = headers.get('x-forwarded-cookie');
if (forwardedCookie && !headers.get('cookie')) {
headers.set('cookie', forwardedCookie);
}
const session = await auth.api.getSession({ headers });
if (!session) {
c.set('user', null);
c.set('session', null);
await next();
return;
}
c.set('user', session.user);
c.set('session', session.session);
await next();
});