decide.js (2146B)
1 import { app } from '../../app.js'; 2 import { resolveConsentRequest } from '../../lib/consent-request.js'; 3 import { recordConsent } from '../../lib/consents.js'; 4 import { HttpError } from '../../lib/http/http-error.js'; 5 import { endpointUrls, requestOrigin } from '../../lib/oidc/context.js'; 6 import { clearAuthRequestCookie, deleteAuthRequest } from '../../lib/oidc/requests.js'; 7 8 function withQuery(url, params) { 9 const target = new URL(url); 10 for (const [key, value] of Object.entries(params)) { 11 if (value !== undefined && value !== null && value !== '') { 12 target.searchParams.set(key, String(value)); 13 } 14 } 15 return target.toString(); 16 } 17 18 export default { 19 method: 'post', 20 path: '/api/v1/consent', 21 name: 'consent.decide', 22 async handler(req, res) { 23 const body = req.body || {}; 24 if (body.decision !== 'allow' && body.decision !== 'deny') { 25 throw new HttpError(400, 'invalid_request', 'decision must be allow or deny'); 26 } 27 28 const request = await resolveConsentRequest({ 29 req, 30 res, 31 publicUrl: app.config.server.public_url, 32 clientId: body.client_id, 33 }); 34 35 if (body.decision === 'deny') { 36 const redirect = withQuery(request.pending.redirect_uri, { 37 error: 'access_denied', 38 error_description: 'The user denied access', 39 state: request.pending.state, 40 }); 41 await deleteAuthRequest(request.store, request.pending.id); 42 clearAuthRequestCookie(res, req, request.target); 43 return new app.HttpOk({ ok: true, redirect }, { 'cache-control': 'no-store' }); 44 } 45 46 await recordConsent(request.systemDb, { 47 userId: request.auth.user.id, 48 realmId: request.target.realm.id, 49 clientId: request.target.clientId, 50 scopes: request.pending.scope, 51 grantedVia: 'user', 52 }); 53 54 const context = { 55 ...request.hostContext, 56 origin: requestOrigin(req), 57 clientId: request.target.clientId, 58 realm: request.target.realm, 59 systemClient: false, 60 }; 61 62 return new app.HttpOk( 63 { ok: true, redirect: endpointUrls(context).authorize }, 64 { 'cache-control': 'no-store' } 65 ); 66 }, 67 };