UNPKG

lumber-forestadmin

Version:

Forest Admin for Lumber.

63 lines (53 loc) 1.99 kB
const os = require('os'); const fs = require('fs'); const P = require('bluebird'); const chalk = require('chalk'); const api = require('./api'); const { parseJwt } = require('../utils/authenticator-helper'); function Authenticator(logger, inquirer) { this.login = async (email, password) => { const sessionToken = await api.login(email, password); fs.writeFileSync(`${os.homedir()}/.lumberrc`, sessionToken); return sessionToken; }; this.loginWithGoogle = async (email) => { const endpoint = process.env.FOREST_URL && process.env.FOREST_URL.includes('localhost') ? 'http://localhost:4200' : 'https://app.forestadmin.com'; const url = chalk.cyan.underline(`${endpoint}/authentication-token`); logger.info(`To authentify with your google account please follow this link and copy the authentication token: ${url}`); const { sessionToken } = await inquirer.prompt([{ type: 'password', name: 'sessionToken', message: 'Enter your Forest Admin authentication token:', validate: (input) => { const errorMessage = 'Invalid token. Please enter your authentication token.'; if (!input) { return errorMessage; } const sessionInfo = parseJwt(input); if (sessionInfo && sessionInfo.data.data.attributes.email === email) { return true; } return errorMessage; }, }]); fs.writeFileSync(`${os.homedir()}/.lumberrc`, sessionToken); return sessionToken; }; this.logout = async () => { const path = `${os.homedir()}/.lumberrc`; return new P((resolve, reject) => { fs.stat(path, (err) => { if (err === null) { fs.unlinkSync(path); logger.success('Logout successful.'); resolve(); } else if (err.code === 'ENOENT') { logger.info('Your were not logged in.'); resolve(); } else { reject(err); } }); }); }; } module.exports = Authenticator;