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