create.js (1903B)
1 import { app } from '../../../app.js'; 2 import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; 3 import { assertAdminRealmUser } from '../../../lib/admin-users.js'; 4 import { 5 createBan, 6 revokeBannedClientAccess, 7 revokeBannedRealmAccess, 8 serializeBan, 9 } from '../../../lib/bans.js'; 10 import { HttpError } from '../../../lib/http/http-error.js'; 11 import { getClient } from '../../../lib/oidc/clients.js'; 12 13 export default { 14 method: 'post', 15 path: '/api/v1/admin/realms/:realm/users/:userId/bans', 16 name: 'admin.bans.create', 17 async handler(req) { 18 const auth = await authenticateAdminRequest(req, { 19 realmSlug: req.params.realm, 20 }); 21 const body = req.body || {}; 22 if (typeof body.client_id !== 'string' || !body.client_id) { 23 throw new HttpError(400, 'invalid_request', 'client_id is required'); 24 } 25 26 const user = await assertAdminRealmUser({ 27 systemDb: auth.systemDb, 28 realmDb: auth.realmDb, 29 realm: auth.realm, 30 userId: req.params.userId, 31 }); 32 33 const clientId = body.client_id; 34 if (clientId !== '*') { 35 const client = await getClient(auth.realmDb, clientId); 36 if (!client || client.system_client) { 37 throw new HttpError(404, 'client_not_found', 'Client not found'); 38 } 39 } 40 41 const now = Date.now(); 42 const ban = await createBan(auth.realmDb, { 43 userId: user.id, 44 clientId, 45 createdBy: auth.user.id, 46 now, 47 }); 48 49 if (clientId === '*') { 50 await revokeBannedRealmAccess(auth.systemDb, { 51 userId: user.id, 52 realmId: auth.realm.id, 53 now, 54 }); 55 } else { 56 await revokeBannedClientAccess(auth.systemDb, { 57 userId: user.id, 58 realmId: auth.realm.id, 59 clientId, 60 now, 61 }); 62 } 63 64 return new app.HttpOk( 65 { ok: true, ban: serializeBan(ban) }, 66 { 'cache-control': 'no-store' } 67 ); 68 }, 69 };