UNPKG

@swell/cli

Version:

Swell's command line interface/utility

72 lines (71 loc) 3.1 kB
import { Flags } from '@oclif/core'; import config from '../lib/config.js'; import { getSessionIdOrLoginInBrowser } from '../lib/sessions.js'; import { modifyDefaultStore } from '../lib/stores.js'; import style from '../lib/style.js'; import { SwellCommand } from '../swell-command.js'; export default class Login extends SwellCommand { static description = ` If you are not already logged in, this command will open your browser to the Swell Admin login page, otherwise it will show you the stores you still have available for logging in to. `; static flags = { force: Flags.boolean({ char: 'f', description: 'show all available stores and switch the current session if needed', }), store: Flags.string({ char: 's', description: 'store to login to', }), }; static summary = 'Login to your Swell user account.'; constructor(argv, config) { super(argv, config); this.requiresAuth = false; } async run() { const { flags } = await this.parse(Login); const { force, store } = flags; const currentStoreId = config.getDefaultStore(); let user; if (currentStoreId && !force) { try { user = await this.api.get({ adminPath: 'user' }); config.setUser(user); this.log(`You are already logged in to ${style.storeId(currentStoreId)} as ${style.currentUser(user.username)}. Use --force to login again, or \`swell switch\` to switch stores.`); // eslint-disable-next-line no-process-exit, unicorn/no-process-exit process.env.NODE_ENV !== 'test' && process.exit(0); return; } catch { // noop } } const [sessionId, storeId] = await getSessionIdOrLoginInBrowser(store); await this.api.setStoreEnv(storeId); user = await this.api.get({ adminPath: 'user' }, { sessionId }); await this.getAndSetStoreConfig({ sessionId, storeId }); await modifyDefaultStore({ currentStoreId, storeId }, force); config.setUser(user); this.log(`\nYou are now logged in to ${style.storeId(storeId)} as ${style.currentUser(user.username)}.`); } /** * Use the /user/switch API request to either get the session id for the * current store or create a session id for the given store id. * * @param sessionId - The session id for the current store * @param storeId - The store id to get the session id for * * @returns void */ async getAndSetStoreConfig({ sessionId, storeId, }) { const switchResponse = await this.api.post({ adminPath: '/user/switch' }, { body: { client_id: storeId }, sessionId }); // ensure we have the attribute names as we expect before saving switchResponse.sessionId = switchResponse.session_id; switchResponse.storeId = switchResponse.client_id; switchResponse.name = switchResponse.client_name; config.setStore(switchResponse); } }