UNPKG

waterbase

Version:
109 lines (108 loc) 3.81 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const node_localstorage_1 = require("node-localstorage"); const Service_1 = __importDefault(require("../Service")); const User_1 = __importDefault(require("../helpers/User")); if (typeof global.localStorage === 'undefined' || global.localStorage === null) { global.localStorage = new node_localstorage_1.LocalStorage('./localStorage'); } class Auth extends Service_1.default { constructor() { /** * * Will create the account and create a JWT and store it (login) * * @param email string * * @param password string * * @param profile object * * @return Promise<User> */ super(...arguments); this.CreateAccount = (email, password, profile) => { return new Promise((res, rej) => { this.client .call('post', '/auth/', { 'content-type': 'application/json', }, { email, password, profile: profile || {} }) .then((value) => { localStorage.setItem('authToken', value.token); res(new User_1.default(this.client, value.token)); }) .catch(rej); }); }; /** * * Will create JWT and store it if the user exists * * @param email string * * @param password string * * @return Promise<User> */ this.loginWithEmailAndPassword = (email, password) => { return new Promise((res, rej) => { this.client .call('post', '/auth/login', { 'content-type': 'application/json', }, { email, password }) .then((value) => { localStorage.setItem('authToken', value.token); res(new User_1.default(this.client, value.token)); }) .catch(rej); }); }; /** * * Will decode the current JWT and return it * * @return Promise<User> */ this.getCurrentUser = () => { return new Promise((res, rej) => { const token = localStorage.getItem('authToken'); if (token !== null) { res(new User_1.default(this.client, token)); } else { rej(null); } }); }; /** * * Will sign out the user from its account * * @return Promise<any> */ this.signOut = () => { return new Promise((res, rej) => { const token = localStorage.getItem('authToken'); const email = jsonwebtoken_1.default.decode(token).email; if (token !== null) { this.client .call('delete', '/auth/token', { 'content-type': 'application/json' }, { email, }) .then((data) => { localStorage.removeItem('authToken'); res(data); }) .catch(rej); } else { rej(new Error('no user signed in')); } }); }; } } module.exports = Auth;