import _ from 'lodash'; import {encode} from 'querystring'; import Cookies from 'js-cookie'; import Auth from '../api/auth'; export default class Session{ constructor(session){ if(typeof session != 'undefined'){ this.updateSession(session); }else{ this.restoreSession(); } this.sessionPath = '/'; } registerUpdate(){ this.updatedAt = new Date(); } isAuthenticate(){ return this.accessToken != undefined; } isAdmin(){ return this.isAuthenticate() && this.userProfile == 'admin'; } getToken(){ return this.accessToken; } getTokenType(){ return this.accessTokenType; } getClient(){ return this.client; } getExpiry(){ return this.expiry; } getUid(){ return this.uid; } applySessionHeader(headers){ if(this.accessToken){ return _.merge(this.session, headers); }else{ return headers; } } updateSession(session){ this.clearCookies(); this.session = session; this.accessToken = session["access-token"]; this.tokenType = session["token-type"]; this.client = session["client"]; this.expiry = session["expiry"]; this.uid = session["uid"]; this.storeCookies(); this.validateSession(); } validateSession(){ if(this.isAuthenticate() && (typeof this.updatedAt == 'undefined' || this.updatedAt - new Date() > 1500)){ this.registerUpdate(); new Auth().verifyToken((success)=>{ // console.log("Token Verification", success); if(success['success'] == true){ this.registerUpdate(); this.userProfile = success.data.profile; }else{ this.removeCookies(); } }, (error)=>{ if(error['success'] == true){ this.registerUpdate(); this.userProfile = success.data.profile; }else{ this.removeCookies(); } }); } } restoreSession(){ this.accessToken = Cookies.get("access-token", {path: this.sessionPath}); this.tokenType = Cookies.get("token-type", {path: this.sessionPath}); this.client = Cookies.get("client", {path: this.sessionPath}); this.expiry = Cookies.get("expiry", {path: this.sessionPath}); this.uid = Cookies.get("uid", {path: this.sessionPath}); this.session = { "access-token": this.accessToken, "token-type": this.tokenType, "client": this.client, "expiry": this.expiry, "uid": this.uid, }; } storeCookies(){ Cookies.set("access-token", this.accessToken, {path: this.sessionPath}); Cookies.set("token-type", this.tokenType, {path: this.sessionPath}); Cookies.set("client", this.client, {path: this.sessionPath}); Cookies.set("expiry", this.expiry, {path: this.sessionPath}); Cookies.set("uid", this.uid, {path: this.sessionPath}); } clearCookies(){ Cookies.remove("access-token", {path: this.sessionPath}); Cookies.remove("token-type", {path: this.sessionPath}); Cookies.remove("client", {path: this.sessionPath}); Cookies.remove("expiry", {path: this.sessionPath}); Cookies.remove("uid", {path: this.sessionPath}); this.accessToken = undefined; this.tokenType = undefined; this.client = undefined; this.expiry = undefined; this.uid = undefined; this.session = {}; } removeCookies(){ this.clearCookies(); window.location.href = '/'; // window.location.reload(); } }