Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/registration-tokens.ts
5759 views
1
import { callback2 } from "@cocalc/util/async-utils";
2
import { PostgreSQL } from "./types";
3
4
function isDelete(options: { delete?: boolean }[]) {
5
return options.some((v) => v?.delete === true);
6
}
7
8
interface Query {
9
token: string;
10
descr?: string;
11
expires?: Date;
12
limit?: number;
13
disabled?: boolean;
14
ephemeral?: boolean;
15
customize?;
16
}
17
18
export default async function registrationTokensQuery(
19
db: PostgreSQL,
20
options: { delete?: boolean }[],
21
query: Query,
22
) {
23
if (isDelete(options) && query.token) {
24
// delete if option is set and there is a token which is defined and not an empty string
25
await callback2(db._query, {
26
query: "DELETE FROM registration_tokens WHERE token = $1",
27
params: [query.token],
28
});
29
return;
30
}
31
32
// either we want to get all tokens or insert/edit one
33
if (query.token == "*") {
34
// select all tokens -- there is of course no WHERE clause, since this is not user specific.
35
// It's the same tokens for any ADMIN.
36
const { rows } = await callback2(db._query, {
37
query: "SELECT * FROM registration_tokens",
38
});
39
return rows;
40
} else if (query.token) {
41
// upsert an existing one
42
const { token, descr, expires, limit, disabled, ephemeral, customize } =
43
query;
44
const { rows } = await callback2(db._query, {
45
query: `INSERT INTO registration_tokens ("token","descr","expires","limit","disabled","ephemeral","customize")
46
VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (token)
47
DO UPDATE SET
48
"token" = EXCLUDED.token,
49
"descr" = EXCLUDED.descr,
50
"expires" = EXCLUDED.expires,
51
"limit" = EXCLUDED.limit,
52
"disabled" = EXCLUDED.disabled,
53
"ephemeral" = EXCLUDED.ephemeral,
54
"customize" = EXCLUDED.customize`,
55
params: [
56
token,
57
descr ? descr : null,
58
expires ? expires : null,
59
limit == null ? null : limit, // if undefined make it null
60
disabled != null ? disabled : false,
61
ephemeral == null ? null : ephemeral,
62
customize == null ? null : customize,
63
],
64
});
65
return rows;
66
} else {
67
throw new Error("don't know what to do with this query");
68
}
69
}
70
71