-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin.js
More file actions
186 lines (163 loc) · 5.75 KB
/
admin.js
File metadata and controls
186 lines (163 loc) · 5.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
/**
* Admin API routes for OAuth client management.
*
* All endpoints require admin authentication (JWT or session) and are rate limited.
*/
import express from 'express';
import { authenticateAdminAPI } from '../auth/adminApi.js';
import { listClients, getClient, createClient, updateClient, deleteClient } from '../auth/oauth2/client.js';
import { asyncHandler } from '../middleware/asyncHandler.js';
import { sendSuccess, sendCreated, throwBadRequest, throwNotFound } from '../middleware/responseHelpers.js';
import { validateBody, validateParams, CreateClientSchema, UpdateClientSchema, ClientIdParamsSchema } from '../middleware/validation-schemas.js';
import { adminLimiter, standardWriteLimiter, deleteLimiter } from '../middleware/rateLimiters.js';
import logger from '../logging/logger.js';
const router = express.Router();
// All admin routes require authentication (JWT or session) and rate limiting
router.use(asyncHandler(authenticateAdminAPI));
router.use(adminLimiter);
/**
* GET /admin/oauth-clients
*
* List all OAuth clients (without secrets).
*/
router.get('/oauth-clients', asyncHandler(async (req, res) => {
logger.debug('[Admin] Listing OAuth clients', { userId: req.user?.user_id });
const clients = await listClients();
logger.info('[Admin] OAuth clients listed', { userId: req.user?.user_id, count: clients.length });
sendSuccess(res, { clients });
}));
/**
* GET /admin/oauth-clients/:clientId
*
* Get a specific OAuth client (without secret).
*/
router.get('/oauth-clients/:clientId', validateParams(ClientIdParamsSchema), asyncHandler(async (req, res) => {
const { clientId } = req.validatedParams;
logger.debug('[Admin] Getting OAuth client', { userId: req.user?.user_id, clientId });
const client = await getClient(clientId);
if (!client) {
logger.warn('[Admin] OAuth client not found', { userId: req.user?.user_id, clientId });
throwNotFound(`OAuth client '${clientId}' not found`);
}
logger.info('[Admin] OAuth client retrieved', { userId: req.user?.user_id, clientId });
sendSuccess(res, { client });
}));
/**
* POST /admin/oauth-clients
*
* Create a new OAuth client.
* Generates a secure secret automatically if not provided.
* Returns the client with the plain secret (only time it's available).
*/
router.post('/oauth-clients', standardWriteLimiter, validateBody(CreateClientSchema), asyncHandler(async (req, res) => {
const { client_id, client_secret, allowed_scopes, redirect_uris } = req.validatedBody;
logger.debug('[Admin] Creating OAuth client', {
userId: req.user?.user_id,
client_id,
hasSecret: !!client_secret,
allowed_scopes,
redirect_uris: redirect_uris ? (Array.isArray(redirect_uris) ? redirect_uris.length : 1) : 0
});
try {
const client = await createClient({
clientId: client_id,
clientSecret: client_secret,
allowedScopes: allowed_scopes,
redirectUris: redirect_uris,
});
logger.info('[Admin] OAuth client created', {
userId: req.user?.user_id,
client_id,
allowed_scopes: client.allowed_scopes
});
sendCreated(res, {
client,
message: 'OAuth client created successfully. Save the client_secret now - it will not be shown again.',
});
} catch (error) {
if (error.message.includes('already exists')) {
logger.warn('[Admin] OAuth client creation failed - already exists', {
userId: req.user?.user_id,
client_id
});
throwBadRequest(error.message);
}
logger.error('[Admin] OAuth client creation failed', {
userId: req.user?.user_id,
client_id,
error: error.message
});
throw error;
}
}));
/**
* PUT /admin/oauth-clients/:clientId
*
* Update an existing OAuth client.
* If client_secret is provided, it will be hashed and stored.
*/
router.put('/oauth-clients/:clientId',
standardWriteLimiter,
validateParams(ClientIdParamsSchema),
validateBody(UpdateClientSchema),
asyncHandler(async (req, res) => {
const { clientId } = req.validatedParams;
const updates = req.validatedBody;
logger.debug('[Admin] Updating OAuth client', {
userId: req.user?.user_id,
clientId,
updateFields: Object.keys(updates.fields || {})
});
try {
const client = await updateClient(clientId, updates);
logger.info('[Admin] OAuth client updated', {
userId: req.user?.user_id,
clientId
});
sendSuccess(res, {
client,
message: 'OAuth client updated successfully',
});
} catch (error) {
if (error.message.includes('not found')) {
logger.warn('[Admin] OAuth client update failed - not found', {
userId: req.user?.user_id,
clientId
});
throwNotFound(error.message);
}
logger.error('[Admin] OAuth client update failed', {
userId: req.user?.user_id,
clientId,
error: error.message
});
throw error;
}
})
);
/**
* DELETE /admin/oauth-clients/:clientId
*
* Delete an OAuth client.
*/
router.delete('/oauth-clients/:clientId', deleteLimiter, validateParams(ClientIdParamsSchema), asyncHandler(async (req, res) => {
const { clientId } = req.validatedParams;
logger.debug('[Admin] Deleting OAuth client', {
userId: req.user?.user_id,
clientId
});
const deleted = await deleteClient(clientId);
if (!deleted) {
logger.warn('[Admin] OAuth client deletion failed - not found', {
userId: req.user?.user_id,
clientId
});
throwNotFound(`OAuth client '${clientId}' not found`);
}
logger.info('[Admin] OAuth client deleted', {
userId: req.user?.user_id,
clientId
});
sendSuccess(res, { message: `OAuth client '${clientId}' deleted successfully` });
}));
export default router;