vue-authenticate
Version:
Authentication library for Vue.js
9 lines (7 loc) • 20 kB
JavaScript
/**
* vue-authenticate v1.5.0
* https://github.com/dgrubelic/vue-authenticate
* Released under the MIT License.
*
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).VueAuthenticate=e()}(this,function(){"use strict";function o(t){return void 0===t}function s(t){return"function"==typeof t}function p(e,o){return null==e||null==o||Object.keys(o).forEach(function(t){"[object Object]"!=Object.prototype.toString.call(o[t])||"[object Object]"!=Object.prototype.toString.call(e[t])?e[t]=o[t]:e[t]=p(e[t],o[t])}),e}function n(t,e){if(/^(?:[a-z]+:)?\/\//i.test(e))return e;return[t,e].join("/").replace(/[\/]+/g,"/").replace(/\/\?/g,"?").replace(/\/\#/g,"#").replace(/\:\//g,"://")}function u(t){var e="https:"===t.protocol;return t.protocol+"//"+t.hostname+":"+(t.port||(e?"443":"80"))+(/^\//.test(t.pathname)?t.pathname:"/"+t.pathname)}function c(t){var e,o,r={};return(t||"").split("&").forEach(function(t){t&&(o=t.split("="),e=decodeURIComponent(o[0]),r[e]=!o[1]||decodeURIComponent(o[1]))}),r}function r(t){var e;if("undefined"!=typeof module&&module.exports)try{e=require("buffer").Buffer}catch(t){}function o(t){switch(t.length){case 4:var e=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return r(55296+(e>>>10))+r(56320+(1023&e));case 3:return r((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return r((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}}var r=String.fromCharCode,n=new RegExp(["[À-ß][-¿]","[à-ï][-¿]{2}","[ð-÷][-¿]{3}"].join("|"),"g");return(e?function(t){return(t.constructor===e.constructor?t:new e(t,"base64")).toString()}:function(t){return atob(t).replace(n,o)})(String(t).replace(/[-_]/g,function(t){return"-"===t?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))}function i(t,e,o){return[encodeURIComponent(t),"=",encodeURIComponent(e),(t=(r=o).path,e=r.domain,o=r.expires,r=r.secure,[null==t?"":";path="+t,null==e?"":";domain="+e,null==o?"":";expires="+o.toUTCString(),null==r||!1===r?"":";secure"].join(""))].join("");var r}"function"!=typeof Object.assign&&(Object.assign=function(t,e){var o=arguments;if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var r=Object(t),n=1;n<arguments.length;n++){var i=o[n];if(null!=i)for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(r[s]=i[s])}return r});var e=setTimeout;function a(){}function h(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],y(t,this)}function l(o,r){for(;3===o._state;)o=o._value;0!==o._state?(o._handled=!0,h._immediateFn(function(){var t,e=1===o._state?r.onFulfilled:r.onRejected;if(null!==e){try{t=e(o._value)}catch(t){return void f(r.promise,t)}d(r.promise,t)}else(1===o._state?d:f)(r.promise,o._value)})):o._deferreds.push(r)}function d(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var o=t.then;if(t instanceof h)return e._state=3,e._value=t,void g(e);if("function"==typeof o)return void y((r=o,n=t,function(){r.apply(n,arguments)}),e)}e._state=1,e._value=t,g(e)}catch(t){f(e,t)}var r,n}function f(t,e){t._state=2,t._value=e,g(t)}function g(t){2===t._state&&0===t._deferreds.length&&h._immediateFn(function(){t._handled||h._unhandledRejectionFn(t._value)});for(var e=0,o=t._deferreds.length;e<o;e++)l(t,t._deferreds[e]);t._deferreds=null}function m(t,e,o){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=o}function y(t,e){var o=!1;try{t(function(t){o||(o=!0,d(e,t))},function(t){o||(o=!0,f(e,t))})}catch(t){if(o)return;o=!0,f(e,t)}}h.prototype.catch=function(t){return this.then(null,t)},h.prototype.then=function(t,e){var o=new this.constructor(a);return l(this,new m(t,e,o)),o},h.all=function(t){var a=Array.prototype.slice.call(t);return new h(function(n,i){if(0===a.length)return n([]);var s=a.length;for(var t=0;t<a.length;t++)!function e(o,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if("function"==typeof r)return void r.call(t,function(t){e(o,t)},i)}a[o]=t,0==--s&&n(a)}catch(t){i(t)}}(t,a[t])})},h.resolve=function(e){return e&&"object"==typeof e&&e.constructor===h?e:new h(function(t){t(e)})},h.reject=function(o){return new h(function(t,e){e(o)})},h.race=function(n){return new h(function(t,e){for(var o=0,r=n.length;o<r;o++)n[o].then(t,e)})},h._immediateFn="function"==typeof setImmediate?function(t){setImmediate(t)}:function(t){e(t,0)},h._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)},h._setImmediateFn=function(t){h._immediateFn=t},h._setUnhandledRejectionFn=function(t){h._unhandledRejectionFn=t};var v=document,w=window;function C(){try{return w.location.hostname}catch(t){}return""}function t(t){try{return o(t)?w.location.origin:""+w.location.origin+t}catch(t){}return t||null}function _(t){this._defaultOptions=p({domain:C(),expires:null,path:"/",secure:!1},t)}var b={baseUrl:null,tokenPath:"access_token",tokenName:"token",tokenPrefix:"vueauth",tokenHeader:"Authorization",tokenType:"Bearer",loginUrl:"/auth/login",registerUrl:"/auth/register",logoutUrl:null,storageType:"localStorage",storageNamespace:"vue-authenticate",cookieStorage:{domain:C(),path:"/",secure:!1},requestDataKey:"data",responseDataKey:"data",bindRequestInterceptor:function(e){var o=e.options.tokenHeader;e.$http.interceptors.request.use(function(t){return e.isAuthenticated()?t.headers[o]=[e.options.tokenType,e.getToken()].join(" "):delete t.headers[o],t})},providers:{facebook:{name:"facebook",url:"/auth/facebook",authorizationEndpoint:"https://www.facebook.com/v10.0/dialog/oauth",redirectUri:t("/"),requiredUrlParams:["display","scope"],scope:["email"],scopeDelimiter:",",display:"popup",oauthType:"2.0",popupOptions:{width:580,height:400}},google:{name:"google",url:"/auth/google",authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",redirectUri:t(),requiredUrlParams:["scope"],optionalUrlParams:["display"],scope:["profile","email"],scopePrefix:"openid",scopeDelimiter:" ",display:"popup",oauthType:"2.0",popupOptions:{width:452,height:633}},github:{name:"github",url:"/auth/github",authorizationEndpoint:"https://github.com/login/oauth/authorize",redirectUri:t(),optionalUrlParams:["scope"],scope:["user:email"],scopeDelimiter:" ",oauthType:"2.0",popupOptions:{width:1020,height:618}},instagram:{name:"instagram",url:"/auth/instagram",authorizationEndpoint:"https://api.instagram.com/oauth/authorize",redirectUri:t(),requiredUrlParams:["scope"],scope:["basic"],scopeDelimiter:"+",oauthType:"2.0",popupOptions:{width:null,height:null}},twitter:{name:"twitter",url:"/auth/twitter",authorizationEndpoint:"https://api.twitter.com/oauth/authenticate",redirectUri:t(),oauthType:"1.0",popupOptions:{width:495,height:645}},bitbucket:{name:"bitbucket",url:"/auth/bitbucket",authorizationEndpoint:"https://bitbucket.org/site/oauth2/authorize",redirectUri:t("/"),optionalUrlParams:["scope"],scope:["email"],scopeDelimiter:" ",oauthType:"2.0",popupOptions:{width:1020,height:618}},linkedin:{name:"linkedin",url:"/auth/linkedin",authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",redirectUri:t(),requiredUrlParams:["state"],scope:["r_emailaddress"],scopeDelimiter:" ",state:"STATE",oauthType:"2.0",popupOptions:{width:527,height:582}},live:{name:"live",url:"/auth/live",authorizationEndpoint:"https://login.live.com/oauth20_authorize.srf",redirectUri:t(),requiredUrlParams:["display","scope"],scope:["wl.emails"],scopeDelimiter:" ",display:"popup",oauthType:"2.0",popupOptions:{width:500,height:560}},oauth1:{name:null,url:"/auth/oauth1",authorizationEndpoint:null,redirectUri:t(),oauthType:"1.0",popupOptions:null},oauth2:{name:null,url:"/auth/oauth2",clientId:null,redirectUri:t(),authorizationEndpoint:null,defaultUrlParams:["response_type","client_id","redirect_uri"],requiredUrlParams:null,optionalUrlParams:null,scope:null,scopePrefix:null,scopeDelimiter:null,state:null,oauthType:"2.0",popupOptions:null,responseType:"code",responseParams:{code:"code",clientId:"clientId",redirectUri:"redirectUri"}}}};_.prototype.setItem=function(t,e){e=i(t,e,p({},this._defaultOptions));this._setCookie(e)},_.prototype.getItem=function(t){var e=function(t){if(0===(t=void 0===t?"":t).length)return{};var o={},e=new RegExp("\\s*;\\s*");return t.split(e).forEach(function(t){var e=t.split("="),t=e[0],e=e[1],t=decodeURIComponent(t),e=decodeURIComponent(e);o[t]=e}),o}(this._getCookie());return e.hasOwnProperty(t)?e[t]:null},_.prototype.removeItem=function(t){var e=p({},this._defaultOptions),e=i(t,"",p(e,{expires:new Date(0)}));this._setCookie(e)},_.prototype._getCookie=function(){try{return"undefined"===v.cookie?"":v.cookie}catch(t){}return""},_.prototype._setCookie=function(t){try{v.cookie=t}catch(t){}};function U(t){this.namespace=t||null}U.prototype.setItem=function(t,e){w.localStorage.setItem(this._getStorageKey(t),e)},U.prototype.getItem=function(t){return w.localStorage.getItem(this._getStorageKey(t))},U.prototype.removeItem=function(t){w.localStorage.removeItem(this._getStorageKey(t))},U.prototype._getStorageKey=function(t){return this.namespace?[this.namespace,t].join("."):t};function k(t){this.namespace=t||null,this._storage={}}k.prototype.setItem=function(t,e){this._storage[this._getStorageKey(t)]=e},k.prototype.getItem=function(t){return this._storage[this._getStorageKey(t)]},k.prototype.removeItem=function(t){delete this._storage[this._getStorageKey(t)]},k.prototype._getStorageKey=function(t){return this.namespace?[this.namespace,t].join("."):t};function I(t){this.namespace=t||null}I.prototype.setItem=function(t,e){w.sessionStorage.setItem(this._getStorageKey(t),e)},I.prototype.getItem=function(t){return w.sessionStorage.getItem(this._getStorageKey(t))},I.prototype.removeItem=function(t){w.sessionStorage.removeItem(this._getStorageKey(t))},I.prototype._getStorageKey=function(t){return this.namespace?[this.namespace,t].join("."):t};function P(t,e,o){this.popup=null,this.url=t,this.name=e,this.popupOptions=o}P.prototype.open=function(t,e){try{return this.popup=w.open(this.url,this.name,this._stringifyOptions()),this.popup&&this.popup.focus&&this.popup.focus(),e?h.resolve():this.pooling(t)}catch(t){return h.reject(new Error("OAuth popup error occurred"))}},P.prototype.pooling=function(e){var a=this;return new h(function(r,n){var t=v.createElement("a");t.href=e;var i=u(t),s=setInterval(function(){a.popup&&!a.popup.closed&&void 0!==a.popup.closed||(clearInterval(s),s=null,n(new Error("Auth popup window closed")));try{var t,e,o;u(a.popup.location)===i&&(a.popup.location.search||a.popup.location.hash?(t=c(a.popup.location.search.substring(1).replace(/\/$/,"")),e=c(a.popup.location.hash.substring(1).replace(/[\/$]/,"")),o=p({},t),(o=p(o,e)).error?n(new Error(o.error)):r(o)):n(new Error("OAuth redirect has occurred but no query or hash parameters were found.")),clearInterval(s),s=null,a.popup.close())}catch(t){}},250)})},P.prototype._stringifyOptions=function(){var t,e=[];for(t in this.popupOptions)o(this.popupOptions[t])||e.push(t+"="+this.popupOptions[t]);return e.join(",")};function T(t,e,o,r){this.$http=t,this.storage=e,this.providerConfig=p({},O),this.providerConfig=p(this.providerConfig,o),this.options=r}var O={name:null,url:null,authorizationEndpoint:null,scope:null,scopePrefix:null,scopeDelimiter:null,redirectUri:null,requiredUrlParams:null,defaultUrlParams:null,oauthType:"1.0",popupOptions:{}};T.prototype.init=function(e){var o=this;return this.oauthPopup=new P("about:blank",this.providerConfig.name,this.providerConfig.popupOptions),w.cordova||this.oauthPopup.open(this.providerConfig.redirectUri,!0),this.getRequestToken().then(function(t){return o.openPopup(t).then(function(t){return o.exchangeForToken(t,e)})})},T.prototype.getRequestToken=function(){var t={method:"POST"};return t[this.options.requestDataKey]=p({},this.providerConfig),t.withCredentials=this.options.withCredentials,this.options.baseUrl?t.url=n(this.options.baseUrl,this.providerConfig.url):t.url=this.providerConfig.url,this.$http(t)},T.prototype.openPopup=function(t){t=[this.providerConfig.authorizationEndpoint,this.buildQueryString(t[this.options.responseDataKey])].join("?");return this.oauthPopup.popup.location=t,w.cordova?this.oauthPopup.open(this.providerConfig.redirectUri):this.oauthPopup.pooling(this.providerConfig.redirectUri)},T.prototype.exchangeForToken=function(t,e){e=p({},e),e=p(e,t),t={method:"POST"};return t[this.options.requestDataKey]=e,t.withCredentials=this.options.withCredentials,this.options.baseUrl?t.url=n(this.options.baseUrl,this.providerConfig.url):t.url=this.providerConfig.url,this.$http(t)},T.prototype.buildQueryString=function(t){var e,o=[];for(e in t){var r=t[e];o.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}return o.join("&")};function j(t,e,o,r){this.$http=t,this.storage=e,this.providerConfig=p({},S),this.providerConfig=p(this.providerConfig,o),this.options=r}var S={name:null,url:null,clientId:null,authorizationEndpoint:null,redirectUri:null,scope:null,scopePrefix:null,scopeDelimiter:null,state:null,requiredUrlParams:null,defaultUrlParams:["response_type","client_id","redirect_uri"],responseType:"code",responseParams:{code:"code",clientId:"clientId",redirectUri:"redirectUri"},oauthType:"2.0",popupOptions:{}};j.prototype.init=function(r){var n=this,i=this.providerConfig.name+"_state";s(this.providerConfig.state)?this.storage.setItem(i,this.providerConfig.state()):"string"==typeof this.providerConfig.state&&this.storage.setItem(i,this.providerConfig.state);var t=[this.providerConfig.authorizationEndpoint,this._stringifyRequestParams()].join("?");return this.oauthPopup=new P(t,this.providerConfig.name,this.providerConfig.popupOptions),new Promise(function(e,o){n.oauthPopup.open(n.providerConfig.redirectUri).then(function(t){return"token"!==n.providerConfig.responseType&&n.providerConfig.url?t.state&&t.state!==n.storage.getItem(i)?o(new Error("State parameter value does not match original OAuth request state value")):void e(n.exchangeForToken(t,r)):e(t)}).catch(function(t){o(t)})})},j.prototype.exchangeForToken=function(t,e){var o,r=p({},e);for(o in this.providerConfig.responseParams)switch(this.providerConfig.responseParams[o],o){case"code":r[o]=t.code;break;case"clientId":r[o]=this.providerConfig.clientId;break;case"redirectUri":r[o]=this.providerConfig.redirectUri;break;default:r[o]=t[o]}return t.state&&(r.state=t.state),e=this.options.baseUrl?n(this.options.baseUrl,this.providerConfig.url):this.providerConfig.url,this.$http.post(e,r,{withCredentials:this.options.withCredentials})},j.prototype._stringifyRequestParams=function(){var r=this,n=[];return["defaultUrlParams","requiredUrlParams","optionalUrlParams"].forEach(function(t){r.providerConfig[t]&&Array.isArray(r.providerConfig[t])&&r.providerConfig[t].forEach(function(t){var e=t.replace(/([\:\-\_]+(.))/g,function(t,e,o,r){return r?o.toUpperCase():o}),o=s(r.providerConfig[t])?r.providerConfig[t]():r.providerConfig[e];"redirect_uri"===t&&!o||("state"===t&&(e=r.providerConfig.name+"_state",o=encodeURIComponent(r.storage.getItem(e))),"scope"===t&&Array.isArray(o)&&(o=o.join(r.providerConfig.scopeDelimiter),r.providerConfig.scopePrefix&&(o=[r.providerConfig.scopePrefix,o].join(r.providerConfig.scopeDelimiter))),n.push([t,o]))})}),n.map(function(t){return t.join("=")}).join("&")};var E=function(t,e){var o=p({},b),r=function(t){switch(t.storageType){case"localStorage":try{return w.localStorage.setItem("testKey","test"),w.localStorage.removeItem("testKey"),new U(t.storageNamespace)}catch(t){}case"sessionStorage":try{return w.sessionStorage.setItem("testKey","test"),w.sessionStorage.removeItem("testKey"),new I(t.storageNamespace)}catch(t){}case"cookieStorage":return new _(t.cookieStorage);case"memoryStorage":default:return new k(t.storageNamespace)}}(o=p(o,e));if(Object.defineProperties(this,{$http:{get:function(){return t}},options:{get:function(){return o}},storage:{get:function(){return r}},tokenName:{get:function(){return this.options.tokenPrefix?[this.options.tokenPrefix,this.options.tokenName].join("_"):this.options.tokenName}}}),!this.options.bindRequestInterceptor||!s(this.options.bindRequestInterceptor))throw new Error("Request interceptor must be functions");this.options.bindRequestInterceptor.call(this,this)};function q(t,e){var o;q.installed||(q.installed=!0,o=null,Object.defineProperties(t.prototype,{$auth:{get:function(){if(!o){if(!this.$http)throw new Error("Request handler instance not found");o=new E(this.$http,e)}return o}}}))}return E.prototype.isAuthenticated=function(){var t=this.storage.getItem(this.tokenName);if(t){if(3===t.split(".").length)try{var e=t.split(".")[1].replace("-","+").replace("_","/"),o=JSON.parse(w.atob(e)).exp;if("number"==typeof o)return Math.round((new Date).getTime()/1e3)<o}catch(t){return!0}return!0}return!1},E.prototype.getToken=function(){return this.storage.getItem(this.tokenName)},E.prototype.setToken=function(t,e){e=function(t,e){for(var o,r=void 0,n=t,i=e.split("."),s=0;s<i.length;s++){var a=i[s],r=n[a];if(null===(o=r)||"object"!=typeof o)break;n=n[a]}return r}(t=t[this.options.responseDataKey]?t[this.options.responseDataKey]:t,e||this.options.tokenPath);e&&this.storage.setItem(this.tokenName,e)},E.prototype.getPayload=function(){var t=this.storage.getItem(this.tokenName);if(t&&3===t.split(".").length)try{var e=t.split(".")[1].replace("-","+").replace("_","/");return JSON.parse(r(e))}catch(t){}},E.prototype.login=function(t,e){var o=this;return(e=e||{}).url=e.url||n(this.options.baseUrl,this.options.loginUrl),e[this.options.requestDataKey]=t||e[this.options.requestDataKey],e.method=e.method||"POST",e.withCredentials=e.withCredentials||this.options.withCredentials,this.$http(e).then(function(t){return o.setToken(t),t})},E.prototype.register=function(t,e){var o=this;return(e=e||{}).url=e.url||n(this.options.baseUrl,this.options.registerUrl),e[this.options.requestDataKey]=t||e[this.options.requestDataKey],e.method=e.method||"POST",e.withCredentials=e.withCredentials||this.options.withCredentials,this.$http(e).then(function(t){return o.setToken(t),t})},E.prototype.logout=function(t){var e=this;return this.isAuthenticated()?(t=t||{}).url||this.options.logoutUrl?(t.url=t.url||n(this.options.baseUrl,this.options.logoutUrl),t.method=t.method||"POST",t[this.options.requestDataKey]=t[this.options.requestDataKey]||void 0,t.withCredentials=t.withCredentials||this.options.withCredentials,this.$http(t).then(function(t){return e.storage.removeItem(e.tokenName),t})):(this.storage.removeItem(this.tokenName),h.resolve()):h.reject(new Error("There is no currently authenticated user"))},E.prototype.authenticate=function(n,i){var s=this;return new h(function(e,o){var t,r=s.options.providers[n];if(!r)return o(new Error("Unknown provider"));switch(r.oauthType){case"1.0":t=new T(s.$http,s.storage,r,s.options);break;case"2.0":t=new j(s.$http,s.storage,r,s.options);break;default:return o(new Error("Invalid OAuth type"))}return t.init(i).then(function(t){return s.setToken(t,r.tokenPath),s.isAuthenticated()?e(t):o(new Error("Authentication failed"))}).catch(function(t){return o(t)})})},E.prototype.link=function(n,i){var s=this;return new h(function(e,t){var o,r=s.options.providers[n];if(!r)return t(new Error("Unknown provider"));switch(r.oauthType){case"1.0":o=new T(s.$http,s.storage,r,s.options);break;case"2.0":o=new j(s.$http,s.storage,r,s.options);break;default:return t(new Error("Invalid OAuth type"))}return o.init(i).then(function(t){t[s.options.responseDataKey]&&(t=t[s.options.responseDataKey]),e(t)}).catch(t)})},q.factory=function(t,e){return new E(t,e)},q});