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