|
| 1 | +/* |
| 2 | + * Copyright 2025 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | + |
| 13 | +import { assertAuthorization } from '../../utils/auth.js'; |
| 14 | +import { errorResponse, errorWithResponse } from '../../utils/http.js'; |
| 15 | + |
| 16 | +const generateToken = () => crypto.randomUUID().toUpperCase(); |
| 17 | + |
| 18 | +/** |
| 19 | + * |
| 20 | + * @param {Context} ctx |
| 21 | + * @param {string} [token] |
| 22 | + * @returns {Promise<string>} |
| 23 | + */ |
| 24 | +export async function updateToken(ctx, token = generateToken()) { |
| 25 | + const { config } = ctx; |
| 26 | + try { |
| 27 | + await ctx.env.KEYS.put(config.siteKey, token); |
| 28 | + } catch (e) { |
| 29 | + ctx.log.error('failed to update token', e); |
| 30 | + throw errorWithResponse(500, 'failed to update token'); |
| 31 | + } |
| 32 | + return token; |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * @param {Context} ctx |
| 37 | + */ |
| 38 | +export default async function update(ctx) { |
| 39 | + const { data } = ctx; |
| 40 | + if (!data.token || typeof data.token !== 'string') { |
| 41 | + return errorResponse(400, 'missing or invalid token'); |
| 42 | + } |
| 43 | + |
| 44 | + await assertAuthorization(ctx); |
| 45 | + |
| 46 | + const token = await updateToken(ctx, data.token); |
| 47 | + return new Response(JSON.stringify({ token }), { |
| 48 | + headers: { |
| 49 | + 'Content-Type': 'application/json', |
| 50 | + }, |
| 51 | + }); |
| 52 | +} |
0 commit comments