From 3cff252ad7898f8610f1bd48be5e7602e2cb9c43 Mon Sep 17 00:00:00 2001 From: Sahat Yalkabov Date: Wed, 26 Nov 2014 09:33:04 -0800 Subject: [PATCH] fixed the order of .config block so that provider is registered before it can be used Fixes #200 --- dist/satellizer.js | 186 ++++++++++++++------------- dist/satellizer.min.js | 2 +- examples/client/vendor/satellizer.js | 162 +++++++++++------------ gulpfile.js | 5 +- src/index.js | 20 +-- src/interceptor.js | 23 ++++ 6 files changed, 196 insertions(+), 202 deletions(-) create mode 100644 src/interceptor.js diff --git a/dist/satellizer.js b/dist/satellizer.js index d64b87bd..14edf270 100644 --- a/dist/satellizer.js +++ b/dist/satellizer.js @@ -4,25 +4,7 @@ * License: MIT */ -angular.module('satellizer', []) - .config(['$httpProvider', '$authProvider', 'satellizer.config', function($httpProvider, $authProvider, config) { - $httpProvider.interceptors.push(['$q', function($q) { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - return { - request: function(httpConfig) { - var token = localStorage.getItem(tokenName); - if (token) { - token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token; - httpConfig.headers[config.authHeader] = token; - } - return httpConfig; - }, - responseError: function(response) { - return $q.reject(response); - } - }; - }]); - }]); +angular.module('satellizer', []); angular.module('satellizer') .constant('satellizer.config', { @@ -111,77 +93,6 @@ angular.module('satellizer') } }); -angular.module('satellizer') - .factory('satellizer.shared', [ - '$q', - '$window', - '$location', - 'satellizer.config', - function($q, $window, $location, config) { - var shared = {}; - - shared.getToken = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - return $window.localStorage[tokenName]; - }; - - shared.getPayload = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - var token = $window.localStorage[tokenName]; - - if (token && token.split('.').length === 3) { - var base64Url = token.split('.')[1]; - var base64 = base64Url.replace('-', '+').replace('_', '/'); - return JSON.parse($window.atob(base64)); - } - }; - - shared.setToken = function(response, isLinking) { - var token = response.access_token || response.data[config.tokenName]; - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - - if (!token) { - throw new Error('Expecting a token named "' + config.tokenName + '" but instead got: ' + JSON.stringify(response.data)); - } - - $window.localStorage[tokenName] = token; - - if (config.loginRedirect && !isLinking) { - $location.path(config.loginRedirect); - } - }; - - shared.isAuthenticated = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - var token = $window.localStorage[tokenName]; - - if (token) { - if (token.split('.').length === 3) { - var base64Url = token.split('.')[1]; - var base64 = base64Url.replace('-', '+').replace('_', '/'); - var exp = JSON.parse($window.atob(base64)).exp; - return Math.round(new Date().getTime() / 1000) <= exp; - } else { - return true; - } - } - - return false; - }; - - shared.logout = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - delete $window.localStorage[tokenName]; - - if (config.logoutRedirect) { - $location.path(config.logoutRedirect); - } - return $q.when(); - }; - - return shared; - }]); - angular.module('satellizer') .provider('$auth', ['satellizer.config', function(config) { Object.defineProperties(this, { @@ -309,6 +220,77 @@ angular.module('satellizer') }]); +angular.module('satellizer') + .factory('satellizer.shared', [ + '$q', + '$window', + '$location', + 'satellizer.config', + function($q, $window, $location, config) { + var shared = {}; + + shared.getToken = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + return $window.localStorage[tokenName]; + }; + + shared.getPayload = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + var token = $window.localStorage[tokenName]; + + if (token && token.split('.').length === 3) { + var base64Url = token.split('.')[1]; + var base64 = base64Url.replace('-', '+').replace('_', '/'); + return JSON.parse($window.atob(base64)); + } + }; + + shared.setToken = function(response, isLinking) { + var token = response.access_token || response.data[config.tokenName]; + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + + if (!token) { + throw new Error('Expecting a token named "' + config.tokenName + '" but instead got: ' + JSON.stringify(response.data)); + } + + $window.localStorage[tokenName] = token; + + if (config.loginRedirect && !isLinking) { + $location.path(config.loginRedirect); + } + }; + + shared.isAuthenticated = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + var token = $window.localStorage[tokenName]; + + if (token) { + if (token.split('.').length === 3) { + var base64Url = token.split('.')[1]; + var base64 = base64Url.replace('-', '+').replace('_', '/'); + var exp = JSON.parse($window.atob(base64)).exp; + return Math.round(new Date().getTime() / 1000) <= exp; + } else { + return true; + } + } + + return false; + }; + + shared.logout = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + delete $window.localStorage[tokenName]; + + if (config.logoutRedirect) { + $location.path(config.logoutRedirect); + } + return $q.when(); + }; + + return shared; + }]); + angular.module('satellizer') .factory('satellizer.popup', [ '$q', @@ -600,6 +582,30 @@ angular.module('satellizer') }; }); +angular.module('satellizer') + .config([ + '$httpProvider', + '$authProvider', + 'satellizer.config', + function($httpProvider, $authProvider, config) { + $httpProvider.interceptors.push(['$q', function($q) { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + return { + request: function(httpConfig) { + var token = localStorage.getItem(tokenName); + if (token) { + token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token; + httpConfig.headers[config.authHeader] = token; + } + return httpConfig; + }, + responseError: function(response) { + return $q.reject(response); + } + }; + }]); + }]); + // Base64.js Polyfill (@davidchambers) (function() { var object = typeof exports != 'undefined' ? exports : this; diff --git a/dist/satellizer.min.js b/dist/satellizer.min.js index c706123d..2c0b4b32 100644 --- a/dist/satellizer.min.js +++ b/dist/satellizer.min.js @@ -1 +1 @@ -angular.module("satellizer",[]).config(["$httpProvider","$authProvider","satellizer.config",function(e,t,n){e.interceptors.push(["$q",function(e){var t=n.tokenPrefix?n.tokenPrefix+"_"+n.tokenName:n.tokenName;return{request:function(e){var o=localStorage.getItem(t);return o&&(o="Authorization"===n.authHeader?"Bearer "+o:o,e.headers[n.authHeader]=o),e},responseError:function(t){return e.reject(t)}}}])}]),angular.module("satellizer").constant("satellizer.config",{loginOnSignup:!0,loginRedirect:"/",logoutRedirect:"/",signupRedirect:"/login",loginUrl:"/auth/login",signupUrl:"/auth/signup",loginRoute:"/login",signupRoute:"/signup",tokenName:"token",tokenPrefix:"satellizer",unlinkUrl:"/auth/unlink/",authHeader:"Authorization",providers:{google:{url:"/auth/google",authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:["profile","email"],scopePrefix:"openid",scopeDelimiter:" ",requiredUrlParams:["scope"],optionalUrlParams:["display"],display:"popup",type:"2.0",popupOptions:{width:452,height:633}},facebook:{url:"/auth/facebook",authorizationEndpoint:"https://www.facebook.com/dialog/oauth",redirectUri:window.location.origin+"/"||window.location.protocol+"//"+window.location.host+"/",scope:["email"],scopeDelimiter:",",requiredUrlParams:["display","scope"],display:"popup",type:"2.0",popupOptions:{width:481,height:269}},linkedin:{url:"/auth/linkedin",authorizationEndpoint:"https://www.linkedin.com/uas/oauth2/authorization",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,requiredUrlParams:["state"],scope:["r_emailaddress"],scopeDelimiter:" ",state:"STATE",type:"2.0",popupOptions:{width:527,height:582}},github:{url:"/auth/github",authorizationEndpoint:"https://github.com/login/oauth/authorize",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:[],scopeDelimiter:" ",type:"2.0",popupOptions:{width:1020,height:618}},yahoo:{url:"/auth/yahoo",authorizationEndpoint:"https://api.login.yahoo.com/oauth2/request_auth",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:[],scopeDelimiter:",",type:"2.0",popupOptions:{width:559,height:519}},twitter:{url:"/auth/twitter",type:"1.0",popupOptions:{width:495,height:645}},live:{url:"/auth/live",authorizationEndpoint:"https://login.live.com/oauth20_authorize.srf",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:["wl.basic"],scopeDelimiter:" ",requiredUrlParams:["display","scope"],display:"popup",type:"2.0",popupOptions:{width:500,height:560}}}}),angular.module("satellizer").factory("satellizer.shared",["$q","$window","$location","satellizer.config",function(e,t,n,o){var r={};return r.getToken=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;return t.localStorage[e]},r.getPayload=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName,n=t.localStorage[e];if(n&&3===n.split(".").length){var r=n.split(".")[1],i=r.replace("-","+").replace("_","/");return JSON.parse(t.atob(i))}},r.setToken=function(e,r){var i=e.access_token||e.data[o.tokenName],a=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;if(!i)throw new Error('Expecting a token named "'+o.tokenName+'" but instead got: '+JSON.stringify(e.data));t.localStorage[a]=i,o.loginRedirect&&!r&&n.path(o.loginRedirect)},r.isAuthenticated=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName,n=t.localStorage[e];if(n){if(3===n.split(".").length){var r=n.split(".")[1],i=r.replace("-","+").replace("_","/"),a=JSON.parse(t.atob(i)).exp;return Math.round((new Date).getTime()/1e3)<=a}return!0}return!1},r.logout=function(){var r=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;return delete t.localStorage[r],o.logoutRedirect&&n.path(o.logoutRedirect),e.when()},r}]),angular.module("satellizer").provider("$auth",["satellizer.config",function(e){Object.defineProperties(this,{logoutRedirect:{get:function(){return e.logoutRedirect},set:function(t){e.logoutRedirect=t}},loginRedirect:{set:function(t){e.loginRedirect=t},get:function(){return e.loginRedirect}},signupRedirect:{get:function(){return e.signupRedirect},set:function(t){e.signupRedirect=t}},loginOnSignup:{get:function(){return e.loginOnSignup},set:function(t){e.loginOnSignup=t}},loginUrl:{get:function(){return e.loginUrl},set:function(t){e.loginUrl=t}},signupUrl:{get:function(){return e.signupUrl},set:function(t){e.signupUrl=t}},loginRoute:{get:function(){return e.loginRoute},set:function(t){e.loginRoute=t}},signupRoute:{get:function(){return e.signupRoute},set:function(t){e.signupRoute=t}},tokenName:{get:function(){return e.tokenName},set:function(t){e.tokenName=t}},tokenPrefix:{get:function(){return e.tokenPrefix},set:function(t){e.tokenPrefix=t}},unlinkUrl:{get:function(){return e.unlinkUrl},set:function(t){e.unlinkUrl=t}},authHeader:{get:function(){return e.authHeader},set:function(t){e.authHeader=t}}}),angular.forEach(Object.keys(e.providers),function(t){this[t]=function(n){return angular.extend(e.providers[t],n)}},this);var t=function(t){e.providers[t.name]=e.providers[t.name]||{},angular.extend(e.providers[t.name],t)};this.oauth1=function(n){t(n),e.providers[n.name].type="1.0"},this.oauth2=function(n){t(n),e.providers[n.name].type="2.0"},this.$get=["$q","satellizer.shared","satellizer.local","satellizer.oauth",function(e,t,n,o){var r={};return r.authenticate=function(e,t){return o.authenticate(e,!1,t)},r.login=function(e){return n.login(e)},r.signup=function(e){return n.signup(e)},r.logout=function(){return t.logout()},r.isAuthenticated=function(){return t.isAuthenticated()},r.link=function(e,t){return o.authenticate(e,!0,t)},r.unlink=function(e){return o.unlink(e)},r.getToken=function(){return t.getToken()},r.setToken=function(e,n){t.setToken({access_token:e},n)},r.getPayload=function(){return t.getPayload()},r}]}]),angular.module("satellizer").factory("satellizer.popup",["$q","$interval","$window","$location","satellizer.utils",function(e,t,n,o,r){var i=null,a=null,u={};return u.popupWindow=i,u.open=function(e,t){var n=u.stringifyOptions(u.prepareOptions(t||{}));return i=window.open(e,"_blank",n),i&&i.focus&&i.focus(),u.pollPopup()},u.pollPopup=function(){var n=e.defer();return a=t(function(){try{if(i.document.domain===document.domain&&(i.location.search||i.location.hash)){var e=i.location.search.substring(1).replace(/\/$/,""),o=i.location.hash.substring(1).replace(/\/$/,""),u=r.parseQueryString(o),l=r.parseQueryString(e);angular.extend(l,u),l.error?n.reject({error:l.error}):n.resolve(l),i.close(),t.cancel(a)}}catch(c){}i.closed&&(t.cancel(a),n.reject({data:"Authorization Failed"}))},35),n.promise},u.prepareOptions=function(e){var t=e.width||500,o=e.height||500;return angular.extend({width:t,height:o,left:n.screenX+(n.outerWidth-t)/2,top:n.screenY+(n.outerHeight-o)/2.5},e)},u.stringifyOptions=function(e){var t=[];return angular.forEach(e,function(e,n){t.push(n+"="+e)}),t.join(",")},u}]),angular.module("satellizer").factory("satellizer.local",["$q","$http","$location","satellizer.utils","satellizer.shared","satellizer.config",function(e,t,n,o,r,i){var a={};return a.login=function(e){return t.post(i.loginUrl,e).then(function(e){return r.setToken(e),e})},a.signup=function(e){return t.post(i.signupUrl,e).then(function(e){return i.loginOnSignup?r.setToken(e):n.path(i.signupRedirect),e})},a}]),angular.module("satellizer").factory("satellizer.oauth",["$q","$http","satellizer.config","satellizer.shared","satellizer.Oauth1","satellizer.Oauth2",function(e,t,n,o,r,i){var a={};return a.authenticate=function(e,t,a){var u="1.0"===n.providers[e].type?new r:new i;return u.open(n.providers[e],a||{}).then(function(e){return o.setToken(e,t),e})},a.unlink=function(e){return t.get(n.unlinkUrl+e)},a}]),angular.module("satellizer").factory("satellizer.Oauth1",["$q","$http","satellizer.popup",function(e,t,n){return function(){var e={url:null,name:null,popupOptions:null},o={};return o.open=function(t,r){return angular.extend(e,t),n.open(e.url,e.popupOptions).then(function(e){return o.exchangeForToken(e,r)})},o.exchangeForToken=function(n,r){var i=angular.extend({},r,n),a=o.buildQueryString(i);return t.get(e.url+"?"+a)},o.buildQueryString=function(e){var t=[];return angular.forEach(e,function(e,n){t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}),t.join("&")},o}}]),angular.module("satellizer").factory("satellizer.Oauth2",["$q","$http","satellizer.popup","satellizer.utils","satellizer.config",function(e,t,n,o){return function(){var e={url:null,name:null,scope:null,scopeDelimiter:null,clientId:null,redirectUri:null,popupOptions:null,authorizationEndpoint:null,requiredUrlParams:null,optionalUrlParams:null,defaultUrlParams:["response_type","client_id","redirect_uri"],responseType:"code"},r={};return r.open=function(t,o){angular.extend(e,t);var i=r.buildUrl();return n.open(i,e.popupOptions).then(function(t){return"token"===e.responseType?t:r.exchangeForToken(t,o)})},r.exchangeForToken=function(n,o){var r=angular.extend({},o,{code:n.code,clientId:e.clientId,redirectUri:e.redirectUri});return t.post(e.url,r)},r.buildUrl=function(){var t=e.authorizationEndpoint,n=r.buildQueryString();return[t,n].join("?")},r.buildQueryString=function(){var t=[],n=["defaultUrlParams","requiredUrlParams","optionalUrlParams"];return angular.forEach(n,function(n){angular.forEach(e[n],function(n){var r=o.camelCase(n),i=e[r];"scope"===n&&Array.isArray(i)&&(i=i.join(e.scopeDelimiter),e.scopePrefix&&(i=[e.scopePrefix,i].join(e.scopeDelimiter))),t.push([n,i])})}),t.map(function(e){return e.join("=")}).join("&")},r}}]),angular.module("satellizer").service("satellizer.utils",function(){this.camelCase=function(e){return e.replace(/([\:\-\_]+(.))/g,function(e,t,n,o){return o?n.toUpperCase():n})},this.parseQueryString=function(e){var t,n,o={};return angular.forEach((e||"").split("&"),function(e){e&&(n=e.split("="),t=decodeURIComponent(n[0]),o[t]=angular.isDefined(n[1])?decodeURIComponent(n[1]):!0)}),o}}),function(){function e(e){this.message=e}var t="undefined"!=typeof exports?exports:this,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",t.btoa||(t.btoa=function(t){for(var o,r,i=String(t),a=0,u=n,l="";i.charAt(0|a)||(u="=",a%1);l+=u.charAt(63&o>>8-a%1*8)){if(r=i.charCodeAt(a+=.75),r>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|r}return l}),t.atob||(t.atob=function(t){var o=String(t).replace(/=+$/,"");if(o.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,a=0,u=0,l="";i=o.charAt(u++);~i&&(r=a%4?64*r+i:i,a++%4)?l+=String.fromCharCode(255&r>>(-2*a&6)):0)i=n.indexOf(i);return l})}(); \ No newline at end of file +angular.module("satellizer",[]),angular.module("satellizer").constant("satellizer.config",{loginOnSignup:!0,loginRedirect:"/",logoutRedirect:"/",signupRedirect:"/login",loginUrl:"/auth/login",signupUrl:"/auth/signup",loginRoute:"/login",signupRoute:"/signup",tokenName:"token",tokenPrefix:"satellizer",unlinkUrl:"/auth/unlink/",authHeader:"Authorization",providers:{google:{url:"/auth/google",authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:["profile","email"],scopePrefix:"openid",scopeDelimiter:" ",requiredUrlParams:["scope"],optionalUrlParams:["display"],display:"popup",type:"2.0",popupOptions:{width:452,height:633}},facebook:{url:"/auth/facebook",authorizationEndpoint:"https://www.facebook.com/dialog/oauth",redirectUri:window.location.origin+"/"||window.location.protocol+"//"+window.location.host+"/",scope:["email"],scopeDelimiter:",",requiredUrlParams:["display","scope"],display:"popup",type:"2.0",popupOptions:{width:481,height:269}},linkedin:{url:"/auth/linkedin",authorizationEndpoint:"https://www.linkedin.com/uas/oauth2/authorization",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,requiredUrlParams:["state"],scope:["r_emailaddress"],scopeDelimiter:" ",state:"STATE",type:"2.0",popupOptions:{width:527,height:582}},github:{url:"/auth/github",authorizationEndpoint:"https://github.com/login/oauth/authorize",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:[],scopeDelimiter:" ",type:"2.0",popupOptions:{width:1020,height:618}},yahoo:{url:"/auth/yahoo",authorizationEndpoint:"https://api.login.yahoo.com/oauth2/request_auth",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:[],scopeDelimiter:",",type:"2.0",popupOptions:{width:559,height:519}},twitter:{url:"/auth/twitter",type:"1.0",popupOptions:{width:495,height:645}},live:{url:"/auth/live",authorizationEndpoint:"https://login.live.com/oauth20_authorize.srf",redirectUri:window.location.origin||window.location.protocol+"//"+window.location.host,scope:["wl.basic"],scopeDelimiter:" ",requiredUrlParams:["display","scope"],display:"popup",type:"2.0",popupOptions:{width:500,height:560}}}}),angular.module("satellizer").provider("$auth",["satellizer.config",function(e){Object.defineProperties(this,{logoutRedirect:{get:function(){return e.logoutRedirect},set:function(t){e.logoutRedirect=t}},loginRedirect:{set:function(t){e.loginRedirect=t},get:function(){return e.loginRedirect}},signupRedirect:{get:function(){return e.signupRedirect},set:function(t){e.signupRedirect=t}},loginOnSignup:{get:function(){return e.loginOnSignup},set:function(t){e.loginOnSignup=t}},loginUrl:{get:function(){return e.loginUrl},set:function(t){e.loginUrl=t}},signupUrl:{get:function(){return e.signupUrl},set:function(t){e.signupUrl=t}},loginRoute:{get:function(){return e.loginRoute},set:function(t){e.loginRoute=t}},signupRoute:{get:function(){return e.signupRoute},set:function(t){e.signupRoute=t}},tokenName:{get:function(){return e.tokenName},set:function(t){e.tokenName=t}},tokenPrefix:{get:function(){return e.tokenPrefix},set:function(t){e.tokenPrefix=t}},unlinkUrl:{get:function(){return e.unlinkUrl},set:function(t){e.unlinkUrl=t}},authHeader:{get:function(){return e.authHeader},set:function(t){e.authHeader=t}}}),angular.forEach(Object.keys(e.providers),function(t){this[t]=function(n){return angular.extend(e.providers[t],n)}},this);var t=function(t){e.providers[t.name]=e.providers[t.name]||{},angular.extend(e.providers[t.name],t)};this.oauth1=function(n){t(n),e.providers[n.name].type="1.0"},this.oauth2=function(n){t(n),e.providers[n.name].type="2.0"},this.$get=["$q","satellizer.shared","satellizer.local","satellizer.oauth",function(e,t,n,o){var r={};return r.authenticate=function(e,t){return o.authenticate(e,!1,t)},r.login=function(e){return n.login(e)},r.signup=function(e){return n.signup(e)},r.logout=function(){return t.logout()},r.isAuthenticated=function(){return t.isAuthenticated()},r.link=function(e,t){return o.authenticate(e,!0,t)},r.unlink=function(e){return o.unlink(e)},r.getToken=function(){return t.getToken()},r.setToken=function(e,n){t.setToken({access_token:e},n)},r.getPayload=function(){return t.getPayload()},r}]}]),angular.module("satellizer").factory("satellizer.shared",["$q","$window","$location","satellizer.config",function(e,t,n,o){var r={};return r.getToken=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;return t.localStorage[e]},r.getPayload=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName,n=t.localStorage[e];if(n&&3===n.split(".").length){var r=n.split(".")[1],i=r.replace("-","+").replace("_","/");return JSON.parse(t.atob(i))}},r.setToken=function(e,r){var i=e.access_token||e.data[o.tokenName],a=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;if(!i)throw new Error('Expecting a token named "'+o.tokenName+'" but instead got: '+JSON.stringify(e.data));t.localStorage[a]=i,o.loginRedirect&&!r&&n.path(o.loginRedirect)},r.isAuthenticated=function(){var e=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName,n=t.localStorage[e];if(n){if(3===n.split(".").length){var r=n.split(".")[1],i=r.replace("-","+").replace("_","/"),a=JSON.parse(t.atob(i)).exp;return Math.round((new Date).getTime()/1e3)<=a}return!0}return!1},r.logout=function(){var r=o.tokenPrefix?o.tokenPrefix+"_"+o.tokenName:o.tokenName;return delete t.localStorage[r],o.logoutRedirect&&n.path(o.logoutRedirect),e.when()},r}]),angular.module("satellizer").factory("satellizer.popup",["$q","$interval","$window","$location","satellizer.utils",function(e,t,n,o,r){var i=null,a=null,u={};return u.popupWindow=i,u.open=function(e,t){var n=u.stringifyOptions(u.prepareOptions(t||{}));return i=window.open(e,"_blank",n),i&&i.focus&&i.focus(),u.pollPopup()},u.pollPopup=function(){var n=e.defer();return a=t(function(){try{if(i.document.domain===document.domain&&(i.location.search||i.location.hash)){var e=i.location.search.substring(1).replace(/\/$/,""),o=i.location.hash.substring(1).replace(/\/$/,""),u=r.parseQueryString(o),l=r.parseQueryString(e);angular.extend(l,u),l.error?n.reject({error:l.error}):n.resolve(l),i.close(),t.cancel(a)}}catch(c){}i.closed&&(t.cancel(a),n.reject({data:"Authorization Failed"}))},35),n.promise},u.prepareOptions=function(e){var t=e.width||500,o=e.height||500;return angular.extend({width:t,height:o,left:n.screenX+(n.outerWidth-t)/2,top:n.screenY+(n.outerHeight-o)/2.5},e)},u.stringifyOptions=function(e){var t=[];return angular.forEach(e,function(e,n){t.push(n+"="+e)}),t.join(",")},u}]),angular.module("satellizer").factory("satellizer.local",["$q","$http","$location","satellizer.utils","satellizer.shared","satellizer.config",function(e,t,n,o,r,i){var a={};return a.login=function(e){return t.post(i.loginUrl,e).then(function(e){return r.setToken(e),e})},a.signup=function(e){return t.post(i.signupUrl,e).then(function(e){return i.loginOnSignup?r.setToken(e):n.path(i.signupRedirect),e})},a}]),angular.module("satellizer").factory("satellizer.oauth",["$q","$http","satellizer.config","satellizer.shared","satellizer.Oauth1","satellizer.Oauth2",function(e,t,n,o,r,i){var a={};return a.authenticate=function(e,t,a){var u="1.0"===n.providers[e].type?new r:new i;return u.open(n.providers[e],a||{}).then(function(e){return o.setToken(e,t),e})},a.unlink=function(e){return t.get(n.unlinkUrl+e)},a}]),angular.module("satellizer").factory("satellizer.Oauth1",["$q","$http","satellizer.popup",function(e,t,n){return function(){var e={url:null,name:null,popupOptions:null},o={};return o.open=function(t,r){return angular.extend(e,t),n.open(e.url,e.popupOptions).then(function(e){return o.exchangeForToken(e,r)})},o.exchangeForToken=function(n,r){var i=angular.extend({},r,n),a=o.buildQueryString(i);return t.get(e.url+"?"+a)},o.buildQueryString=function(e){var t=[];return angular.forEach(e,function(e,n){t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}),t.join("&")},o}}]),angular.module("satellizer").factory("satellizer.Oauth2",["$q","$http","satellizer.popup","satellizer.utils","satellizer.config",function(e,t,n,o){return function(){var e={url:null,name:null,scope:null,scopeDelimiter:null,clientId:null,redirectUri:null,popupOptions:null,authorizationEndpoint:null,requiredUrlParams:null,optionalUrlParams:null,defaultUrlParams:["response_type","client_id","redirect_uri"],responseType:"code"},r={};return r.open=function(t,o){angular.extend(e,t);var i=r.buildUrl();return n.open(i,e.popupOptions).then(function(t){return"token"===e.responseType?t:r.exchangeForToken(t,o)})},r.exchangeForToken=function(n,o){var r=angular.extend({},o,{code:n.code,clientId:e.clientId,redirectUri:e.redirectUri});return t.post(e.url,r)},r.buildUrl=function(){var t=e.authorizationEndpoint,n=r.buildQueryString();return[t,n].join("?")},r.buildQueryString=function(){var t=[],n=["defaultUrlParams","requiredUrlParams","optionalUrlParams"];return angular.forEach(n,function(n){angular.forEach(e[n],function(n){var r=o.camelCase(n),i=e[r];"scope"===n&&Array.isArray(i)&&(i=i.join(e.scopeDelimiter),e.scopePrefix&&(i=[e.scopePrefix,i].join(e.scopeDelimiter))),t.push([n,i])})}),t.map(function(e){return e.join("=")}).join("&")},r}}]),angular.module("satellizer").service("satellizer.utils",function(){this.camelCase=function(e){return e.replace(/([\:\-\_]+(.))/g,function(e,t,n,o){return o?n.toUpperCase():n})},this.parseQueryString=function(e){var t,n,o={};return angular.forEach((e||"").split("&"),function(e){e&&(n=e.split("="),t=decodeURIComponent(n[0]),o[t]=angular.isDefined(n[1])?decodeURIComponent(n[1]):!0)}),o}}),function(){function e(e){this.message=e}var t="undefined"!=typeof exports?exports:this,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",t.btoa||(t.btoa=function(t){for(var o,r,i=String(t),a=0,u=n,l="";i.charAt(0|a)||(u="=",a%1);l+=u.charAt(63&o>>8-a%1*8)){if(r=i.charCodeAt(a+=.75),r>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|r}return l}),t.atob||(t.atob=function(t){var o=String(t).replace(/=+$/,"");if(o.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,a=0,u=0,l="";i=o.charAt(u++);~i&&(r=a%4?64*r+i:i,a++%4)?l+=String.fromCharCode(255&r>>(-2*a&6)):0)i=n.indexOf(i);return l})}(); \ No newline at end of file diff --git a/examples/client/vendor/satellizer.js b/examples/client/vendor/satellizer.js index d64b87bd..a558c047 100644 --- a/examples/client/vendor/satellizer.js +++ b/examples/client/vendor/satellizer.js @@ -4,25 +4,7 @@ * License: MIT */ -angular.module('satellizer', []) - .config(['$httpProvider', '$authProvider', 'satellizer.config', function($httpProvider, $authProvider, config) { - $httpProvider.interceptors.push(['$q', function($q) { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - return { - request: function(httpConfig) { - var token = localStorage.getItem(tokenName); - if (token) { - token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token; - httpConfig.headers[config.authHeader] = token; - } - return httpConfig; - }, - responseError: function(response) { - return $q.reject(response); - } - }; - }]); - }]); +angular.module('satellizer', []); angular.module('satellizer') .constant('satellizer.config', { @@ -111,77 +93,6 @@ angular.module('satellizer') } }); -angular.module('satellizer') - .factory('satellizer.shared', [ - '$q', - '$window', - '$location', - 'satellizer.config', - function($q, $window, $location, config) { - var shared = {}; - - shared.getToken = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - return $window.localStorage[tokenName]; - }; - - shared.getPayload = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - var token = $window.localStorage[tokenName]; - - if (token && token.split('.').length === 3) { - var base64Url = token.split('.')[1]; - var base64 = base64Url.replace('-', '+').replace('_', '/'); - return JSON.parse($window.atob(base64)); - } - }; - - shared.setToken = function(response, isLinking) { - var token = response.access_token || response.data[config.tokenName]; - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - - if (!token) { - throw new Error('Expecting a token named "' + config.tokenName + '" but instead got: ' + JSON.stringify(response.data)); - } - - $window.localStorage[tokenName] = token; - - if (config.loginRedirect && !isLinking) { - $location.path(config.loginRedirect); - } - }; - - shared.isAuthenticated = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - var token = $window.localStorage[tokenName]; - - if (token) { - if (token.split('.').length === 3) { - var base64Url = token.split('.')[1]; - var base64 = base64Url.replace('-', '+').replace('_', '/'); - var exp = JSON.parse($window.atob(base64)).exp; - return Math.round(new Date().getTime() / 1000) <= exp; - } else { - return true; - } - } - - return false; - }; - - shared.logout = function() { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - delete $window.localStorage[tokenName]; - - if (config.logoutRedirect) { - $location.path(config.logoutRedirect); - } - return $q.when(); - }; - - return shared; - }]); - angular.module('satellizer') .provider('$auth', ['satellizer.config', function(config) { Object.defineProperties(this, { @@ -309,6 +220,77 @@ angular.module('satellizer') }]); +angular.module('satellizer') + .factory('satellizer.shared', [ + '$q', + '$window', + '$location', + 'satellizer.config', + function($q, $window, $location, config) { + var shared = {}; + + shared.getToken = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + return $window.localStorage[tokenName]; + }; + + shared.getPayload = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + var token = $window.localStorage[tokenName]; + + if (token && token.split('.').length === 3) { + var base64Url = token.split('.')[1]; + var base64 = base64Url.replace('-', '+').replace('_', '/'); + return JSON.parse($window.atob(base64)); + } + }; + + shared.setToken = function(response, isLinking) { + var token = response.access_token || response.data[config.tokenName]; + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + + if (!token) { + throw new Error('Expecting a token named "' + config.tokenName + '" but instead got: ' + JSON.stringify(response.data)); + } + + $window.localStorage[tokenName] = token; + + if (config.loginRedirect && !isLinking) { + $location.path(config.loginRedirect); + } + }; + + shared.isAuthenticated = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + var token = $window.localStorage[tokenName]; + + if (token) { + if (token.split('.').length === 3) { + var base64Url = token.split('.')[1]; + var base64 = base64Url.replace('-', '+').replace('_', '/'); + var exp = JSON.parse($window.atob(base64)).exp; + return Math.round(new Date().getTime() / 1000) <= exp; + } else { + return true; + } + } + + return false; + }; + + shared.logout = function() { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + delete $window.localStorage[tokenName]; + + if (config.logoutRedirect) { + $location.path(config.logoutRedirect); + } + return $q.when(); + }; + + return shared; + }]); + angular.module('satellizer') .factory('satellizer.popup', [ '$q', diff --git a/gulpfile.js b/gulpfile.js index 52bf7f81..e2e7e3a9 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,6 +1,6 @@ var gulp = require('gulp'); var concat = require('gulp-concat'); -var rename = require("gulp-rename"); +var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var plumber = require('gulp-plumber'); var complexity = require('gulp-complexity'); @@ -9,14 +9,15 @@ gulp.task('concat', function() { gulp.src([ 'src/index.js', 'src/config.js', - 'src/shared.js', 'src/auth.js', + 'src/shared.js', 'src/popup.js', 'src/local.js', 'src/oauth.js', 'src/oauth1.js', 'src/oauth2.js', 'src/utils.js', + 'src/interceptor.js', 'src/base64.js' ]) .pipe(concat('satellizer.js')) diff --git a/src/index.js b/src/index.js index d14d582c..2eb8aab6 100644 --- a/src/index.js +++ b/src/index.js @@ -4,22 +4,4 @@ * License: MIT */ -angular.module('satellizer', []) - .config(['$httpProvider', '$authProvider', 'satellizer.config', function($httpProvider, $authProvider, config) { - $httpProvider.interceptors.push(['$q', function($q) { - var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; - return { - request: function(httpConfig) { - var token = localStorage.getItem(tokenName); - if (token) { - token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token; - httpConfig.headers[config.authHeader] = token; - } - return httpConfig; - }, - responseError: function(response) { - return $q.reject(response); - } - }; - }]); - }]); +angular.module('satellizer', []); diff --git a/src/interceptor.js b/src/interceptor.js new file mode 100644 index 00000000..be1e5f5a --- /dev/null +++ b/src/interceptor.js @@ -0,0 +1,23 @@ +angular.module('satellizer') + .config([ + '$httpProvider', + '$authProvider', + 'satellizer.config', + function($httpProvider, $authProvider, config) { + $httpProvider.interceptors.push(['$q', function($q) { + var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName; + return { + request: function(httpConfig) { + var token = localStorage.getItem(tokenName); + if (token) { + token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token; + httpConfig.headers[config.authHeader] = token; + } + return httpConfig; + }, + responseError: function(response) { + return $q.reject(response); + } + }; + }]); + }]);