realm-hosts.js (2549B)
1 import { app } from '../../app.js'; 2 import { authenticateAdminRequest } from '../../lib/admin-auth.js'; 3 import { 4 addAdminRealmHost, 5 deleteAdminRealmHost, 6 listAdminRealmHostsPage, 7 normalizeReservedHosts, 8 } from '../../lib/admin-realm-hosts.js'; 9 import { HttpError } from '../../lib/http/http-error.js'; 10 import { parsePagination } from '../../lib/pagination.js'; 11 import { isSystemAdmin } from '../../lib/policy.js'; 12 13 const reservedHosts = normalizeReservedHosts(app.config); 14 15 function assertBody(body) { 16 if (body === null || typeof body !== 'object' || Array.isArray(body)) { 17 throw new HttpError(400, 'invalid_request', 'Request body must be a JSON object'); 18 } 19 for (const field of Object.keys(body)) { 20 if (field !== 'host') { 21 throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`); 22 } 23 } 24 } 25 26 export default [ 27 { 28 method: 'get', 29 path: '/api/v1/admin/realms/:realm/hosts', 30 name: 'admin.realm-hosts.list', 31 async handler(req) { 32 const auth = await authenticateAdminRequest(req, { 33 realmSlug: req.params.realm, 34 }); 35 const pagination = parsePagination( 36 Object.fromEntries(new URL(req.url, 'http://localhost').searchParams) 37 ); 38 39 const result = await listAdminRealmHostsPage({ 40 systemDb: auth.systemDb, 41 realm: auth.realm, 42 pagination, 43 }); 44 45 return new app.HttpOk(result, { 'cache-control': 'no-store' }); 46 }, 47 }, 48 { 49 method: 'post', 50 path: '/api/v1/admin/realms/:realm/hosts', 51 name: 'admin.realm-hosts.create', 52 async handler(req) { 53 const auth = await authenticateAdminRequest(req, { 54 realmSlug: req.params.realm, 55 }); 56 const body = req.body || {}; 57 assertBody(body); 58 const host = await addAdminRealmHost({ 59 systemDb: auth.systemDb, 60 realm: auth.realm, 61 host: body.host, 62 isSystemAdmin: isSystemAdmin(auth.user), 63 reservedHosts, 64 }); 65 66 return new app.HttpOk({ ok: true, host }, { 'cache-control': 'no-store' }); 67 }, 68 }, 69 { 70 method: 'delete', 71 path: '/api/v1/admin/realms/:realm/hosts/:host', 72 name: 'admin.realm-hosts.delete', 73 async handler(req) { 74 const auth = await authenticateAdminRequest(req, { 75 realmSlug: req.params.realm, 76 }); 77 const result = await deleteAdminRealmHost({ 78 systemDb: auth.systemDb, 79 realm: auth.realm, 80 host: req.params.host, 81 }); 82 83 return new app.HttpOk({ ok: true, ...result }, { 'cache-control': 'no-store' }); 84 }, 85 }, 86 ];