import getPool from "@cocalc/database/pool" ; import { isValidUUID } from "@cocalc/util/misc" ; import isPasswordCorrect from "@cocalc/server/auth/is-password-correct" ; import hasPassword from "@cocalc/server/auth/has-password" ; import { generate } from "random-key" ; interface Options { account_id : string ; password ? : string ; action : "get" | "delete" | "regenerate" ; } export default async function manage ( { account_id , password , action , } ) { if ( ! isValidUUID ) { throw Error ( "account_id is not a valid uuid" ) ; } if ( await hasPassword ( account_id ) ) { if ( ! password ) { throw Error ( "password must be provided" ) ; } if ( ! ( await isPasswordCorrect ( { account_id , password } ) ) ) { throw Error ( "invalid password" ) ; } } const pool = getPool ( ) ; switch ( action ) { case "get" : const { rows } = await pool . query ( "SELECT api_key FROM accounts WHERE account_id=$1::UUID" , [ account_id ] ) ; if ( rows . length == 0 ) { throw Error ( "no such account" ) ; } return rows [ 0 ] . api_key ; case "delete" : await pool . query ( "UPDATE accounts SET api_key=NULL WHERE account_id=$1::UUID" , [ account_id ] ) ; return ; case "regenerate" : const api_key = `sk_${ generate ( ) }` ; await pool . query ( "UPDATE accounts SET api_key=$1 WHERE account_id=$2::UUID" , [ api_key , account_id ] ) ; return api_key ; default : throw Error ( `unknown action="${ action }"` ) ; } } export async function getAccountWithApiKey ( api_key ) { const pool = getPool ( "medium" ) ; const { rows } = await pool . query ( "SELECT account_id FROM accounts WHERE api_key = $1::TEXT" , [ api_key ] ) ; return rows [ 0 ] ?. account_id ; }