Path: blob/master/src/packages/next/pages/api/v2/auth/ephemeral.ts
2575 views
/*1* This file is part of CoCalc: Copyright © 2024 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { v4 } from "uuid";67import createAccount from "@cocalc/server/accounts/create-account";8import redeemRegistrationToken from "@cocalc/server/auth/tokens/redeem";9import getProjects from "@cocalc/server/projects/get";10import { signUserIn } from "./sign-in";11import getParams from "lib/api/get-params";1213export default async function createEphemeralAccount(req, res) {14let { registrationToken } = getParams(req);15registrationToken = (registrationToken ?? "").trim();16if (!registrationToken) {17res.json({ error: "Registration token required." });18return;19}20let tokenInfo;21try {22tokenInfo = await redeemRegistrationToken(registrationToken);23} catch (err) {24res.json({25error: `Issue with registration token -- ${err.message}`,26});27return;28}29if (!tokenInfo?.ephemeral || tokenInfo.ephemeral <= 0) {30res.json({31error:32"This registration token is not configured for ephemeral accounts.",33});34return;35}3637const account_id = v4();38const suffix = account_id.slice(0, 6);39try {40await createAccount({41email: undefined,42password: undefined,43firstName: "Ephemeral",44lastName: `User-${suffix}`,45account_id,46tags: ["ephemeral"],47signupReason: "ephemeral",48ephemeral: tokenInfo.ephemeral,49customize: tokenInfo.customize,50});51} catch (err) {52res.json({53error: `Problem creating ephemeral account -- ${err.message}`,54});55return;56}5758let project_id: string | undefined;59try {60const [project] = await getProjects({ account_id, limit: 1 });61project_id = project?.project_id;62} catch (err) {63// non-fatal; we just won't return a redirect target64}6566await signUserIn(req, res, account_id, { maxAge: tokenInfo.ephemeral });67res.json({68account_id,69project_id,70});71}727374