-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.js
More file actions
104 lines (88 loc) · 2.5 KB
/
auth.js
File metadata and controls
104 lines (88 loc) · 2.5 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
/**
* Authentication Middleware Factory
*
* Creates appropriate auth middleware based on server configuration.
* - Multi-user mode: API key authentication via users module
* - Single-user mode: Optional token authentication
*/
const users = require("./users");
/**
* @typedef {import('./config').ServerConfig} ServerConfig
* @typedef {import('./config').SingleUserConfig} SingleUserConfig
*/
/**
* Create authentication middleware based on configuration.
*
* @param {ServerConfig} config - Server configuration
* @returns {function} Hono middleware function
*/
function createAuthMiddleware(config) {
if (config.mode === "single-user") {
return singleUserMiddleware(config.singleUser);
}
return multiUserMiddleware();
}
/**
* Single-user authentication middleware.
* - If token is configured, requires Bearer token auth
* - If no token, allows all authenticated requests
*
* @param {SingleUserConfig} singleUser
* @returns {function}
*/
function singleUserMiddleware(singleUser) {
const { userId, token } = singleUser;
return async (c, next) => {
// Health check is always public
if (c.req.path === "/") {
return next();
}
// Skip auth in e2e test mode
if (process.env.E2E_TEST === 'true') {
c.set("userId", userId);
return next();
}
// If token is configured, require it
if (token) {
const auth = c.req.header("Authorization");
const expected = `Bearer ${token}`;
if (!auth || auth !== expected) {
return c.json({ error: "Unauthorized" }, 401);
}
}
// Set the configured user ID
c.set("userId", userId);
return next();
};
}
/**
* Multi-user authentication middleware.
* Authenticates via API key lookup in users module.
*
* @returns {function}
*/
function multiUserMiddleware() {
return async (c, next) => {
// Health check is public
if (c.req.path === "/") {
return next();
}
// Skip auth in e2e test mode (use 'default' user)
if (process.env.E2E_TEST === 'true') {
c.set("userId", "default");
return next();
}
const auth = c.req.header("Authorization");
if (!auth || !auth.startsWith("Bearer ")) {
return c.json({ error: "Unauthorized" }, 401);
}
const apiKey = auth.slice(7); // Remove "Bearer " prefix
const userId = users.getUserIdFromApiKey(apiKey);
if (!userId) {
return c.json({ error: "Unauthorized" }, 401);
}
c.set("userId", userId);
return next();
};
}
module.exports = { createAuthMiddleware };