UNPKG

@curvenote/cli

Version:
60 lines (59 loc) 2.99 kB
import inquirer from 'inquirer'; import { MyUser } from '../../models.js'; import { getTokens, summarizeAsString, writeConfigFile } from '../tokens.js'; import { actionLinks } from '../../docs.js'; import { Session } from '../session.js'; import chalk from 'chalk'; /** * Validate token and save to local config file * * If config file does not exist, it will be created. * If config file does exist with saved tokens, this token will be added * to the saved tokens and set as the current token. */ export async function setUserToken(log, token) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; if (!token) { log.info(`Create an API token here:\n\n${actionLinks.apiToken}\n`); const resp = await inquirer.prompt([ { name: 'token', message: 'API Token:', type: 'input', }, ]); token = resp.token; } log.debug('Creating session with new token'); const session = await Session.create(token); log.debug('User token payload:'); log.debug(JSON.stringify((_a = session.activeTokens.user) === null || _a === void 0 ? void 0 : _a.decoded, null, 2)); log.debug('Session token payload:'); log.debug(JSON.stringify((_b = session.activeTokens.session) === null || _b === void 0 ? void 0 : _b.decoded, null, 2)); let me; try { me = await new MyUser(session).get(); } catch (error) { log.error(error); throw new Error(`There was a problem with the token for ${(_c = session.activeTokens.session) === null || _c === void 0 ? void 0 : _c.decoded.aud}`); } if (!me.data.email_verified) throw new Error('Your account is not activated'); const data = getTokens(); const tokens = data.saved ? [...data.saved] : []; if (!tokens.find(({ token: t }) => t === token)) { tokens.push({ api: (_e = (_d = session.activeTokens.user) === null || _d === void 0 ? void 0 : _d.decoded.aud) !== null && _e !== void 0 ? _e : 'unknown-audience', email: me.data.email, username: (_h = (_g = (_f = session.activeTokens.user) === null || _f === void 0 ? void 0 : _f.decoded.name) !== null && _g !== void 0 ? _g : me.data.username) !== null && _h !== void 0 ? _h : me.data.display_name, note: (_j = session.activeTokens.user) === null || _j === void 0 ? void 0 : _j.decoded.note, token, }); } writeConfigFile({ tokens, token }); const aud = (_l = (_k = session.activeTokens.user) === null || _k === void 0 ? void 0 : _k.decoded.aud) !== null && _l !== void 0 ? _l : 'unknown-audience'; const note = (_m = session.activeTokens.user) === null || _m === void 0 ? void 0 : _m.decoded.note; const { username, display_name, email } = me.data; session.log.info(chalk.green(`Token set for ${summarizeAsString({ note, email, username: username !== null && username !== void 0 ? username : display_name, api: aud })}.`)); }