CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

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