retailer-vue/src/services/auth.js

60 lines
1.9 KiB
JavaScript

import { Base64 } from 'js-base64';
const rpAuthName = process.env.VUE_APP_RP_AUTH_NAME;
console.log("rpAuthName",rpAuthName)
const getAuthUser = function() {
// return authorization header with jwt token
const userAuthEncoded = window.$cookies.get(rpAuthName);
if (userAuthEncoded === null) {
return null;
}
const userAuth = JSON.parse(Base64.decode(userAuthEncoded));
return userAuth;
}
const getDomain = function(domain) {
const s = domain.split('.');
if (s.length < 3) {
return domain;
}
return s.slice(1).join('.');
}
const setAuthUser = function(userAuth,flag) {
if(flag)
{
const userAuthEncoded = Base64.encode(JSON.stringify(userAuth));
window.$cookies.set(rpAuthName, userAuthEncoded, '30d', null, getDomain(window.location.hostname));
}
else
{
const userAuthEncoded = Base64.encode(JSON.stringify(userAuth));
window.$cookies.set(rpAuthName, userAuthEncoded, '1h', null, getDomain(window.location.hostname));
}
}
const resetAuthUser = function() {
const au = getAuthUser();
if (au === null) {
return false;
}
window.$cookies.remove(rpAuthName, null, getDomain(window.location.hostname));
}
const authHeader = function() {
const userAuth = getAuthUser();
if (userAuth) {
return { 'Authorization': 'Bearer ' + userAuth };
} else {
return {};
}
}
const getCookieByName = function(name) {
return window.$cookies.get(name);
}
const setCookieByName = function(name, value) {
window.$cookies.set(name, value, '168h', null, getDomain(window.location.hostname))
}
const removeCookieByName = function(name) {
window.$cookies.remove(name, null, getDomain(window.location.hostname))
}
export { authHeader, getAuthUser, setAuthUser, resetAuthUser, getCookieByName, setCookieByName, removeCookieByName ,getDomain};