import getRequiresTokens from "./get-requires-token" ; import getPool from "@cocalc/database/pool" ; export default async function redeem ( token ) { const required = await getRequiresTokens ( ) ; if ( ! required ) { return ; } if ( ! token ) { throw Error ( "no registration token provided" ) ; } const client = getPool ( ) ; try { await client . query ( "BEGIN" ) ; const q_match = `SELECT "expires", "counter", "limit", "disabled"
                     FROM registration_tokens
                     WHERE token = $1::TEXT
                     FOR UPDATE` ; const match = await client . query ( q_match , [ token ] ) ; if ( match . rows . length != 1 ) { throw Error ( "Registration token is wrong." ) ; } const { expires , counter : counter_raw , limit , disabled : disabled_raw , } = match . rows [ 0 ] ; const counter = counter_raw ?? 0 ; const disabled = disabled_raw ?? false ; if ( disabled ) { throw Error ( "Registration token disabled." ) ; } if ( expires != null && expires . getTime ( ) < new Date ( ) . getTime ( ) ) { throw Error ( "Registration token no longer valid." ) ; } if ( limit != null && limit <= counter ) { throw Error ( "Registration token used up." ) ; } else { const q_inc = `UPDATE registration_tokens SET "counter" = coalesce("counter", 0) + 1
                     WHERE token = $1::TEXT` ; await client . query ( q_inc , [ token ] ) ; } await client . query ( "COMMIT" ) ; } catch ( err ) { await client . query ( "ROLLBACK" ) ; throw err ; } }