UNPKG

@viewdo/dxp-story-cli

Version:
96 lines (77 loc) 2.36 kB
const date_parse = require('date-fns/parse') const subHours = require('date-fns/sub_hours') const AuthConfig = require('../classes/auth-config') module.exports = class AuthenticationManager extends AuthConfig { constructor( { email = process.env.DXP_AUTH_EMAIL, token = process.env.DXP_AUTH_TOKEN },{ file_service, auth_service, console_service }) { super(email, token, file_service) Object.assign(this, { auth_service, console_service }) } // properties -------------- get last_updated() { return date_parse(this.updated) } get token_expiration() { return 6 // hours } // auth API ----- async requireToken(warn = true) { if(this.hasToken() || await this.getAppToken()) { this.console_service.log(`You are authenticated ${this.email ? `as ${this.email}`: ''}`.green) return true } else if(warn) { this.console_service.log(`You must be authenticated to use this command`.yellow) this.console_service.log(`Run ${"dxp-story login".yellow} ${"to authenticate first".gray}`.gray) } return false } async getAppToken() { let token = await this.auth_service.getAppToken() .catch(e => this.console_service.axiosError(e)) return this.token = token } async sendVerificationEmail(email) { let self = this await this.auth_service.sendVerificationEmail(email) .catch(e => self.console_service.axiosError(e)) this.console_service.log(`Sent a verification code to ${email}`.yellow) } async getTokenFromVerification(email, code) { let self = this let token = this.token = await this.auth_service.getTokenFromVerification(email, code) .catch(e => self.console_service.axiosError(e)) if(token) this.save() else throw new Error('Something went wrong.') this.console_service.log(`You are now authenticated ${this.email ? `as ${this.email}`: ''}`.green) } // config API ------ hasToken() { // if a token is passed in, assume it's good if(this.token) { let expiration = subHours(new Date(), this.token_expiration) if(this.last_updated > expiration) return true } return false } setToken(token) { this.token = token this.save() } setEmail(email) { this.email = email this.save() } }