From e61dcde4bdf3f2967a9aa05a4986847e3b3dc55a Mon Sep 17 00:00:00 2001 From: Flavio Granero Date: Mon, 16 Mar 2015 16:05:22 -0300 Subject: [PATCH] CommonJS package manager support --- dist/ng-token-auth.js | 4 ++++ dist/ng-token-auth.min.js | 2 +- package.json | 1 + src/ng-token-auth.coffee | 3 +++ 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/dist/ng-token-auth.js b/dist/ng-token-auth.js index 994a9418..689ee7dd 100644 --- a/dist/ng-token-auth.js +++ b/dist/ng-token-auth.js @@ -1,3 +1,7 @@ +if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) { + module.exports = 'ng-token-auth'; +} + angular.module('ng-token-auth', ['ipCookie']).provider('$auth', function() { var configs, defaultConfigName; configs = { diff --git a/dist/ng-token-auth.min.js b/dist/ng-token-auth.min.js index 4a0babd8..e1ea410d 100644 --- a/dist/ng-token-auth.min.js +++ b/dist/ng-token-auth.min.js @@ -1 +1 @@ -angular.module("ng-token-auth",["ipCookie"]).provider("$auth",function(){var t,e;return t={"default":{apiUrl:"/api",signOutUrl:"/auth/sign_out",emailSignInPath:"/auth/sign_in",emailRegistrationPath:"/auth",accountUpdatePath:"/auth",accountDeletePath:"/auth",confirmationSuccessUrl:function(){return window.location.href},passwordResetPath:"/auth/password",passwordUpdatePath:"/auth/password",passwordResetSuccessUrl:function(){return window.location.href},tokenValidationPath:"/auth/validate_token",proxyIf:function(){return!1},proxyUrl:"/proxy",validateOnPageLoad:!0,forceHardRedirect:!1,storage:"cookies",tokenFormat:{"access-token":"{{ token }}","token-type":"Bearer",client:"{{ clientId }}",expiry:"{{ expiry }}",uid:"{{ uid }}"},parseExpiry:function(t){return 1e3*parseInt(t.expiry,10)||null},handleLoginResponse:function(t){return t.data},handleAccountUpdateResponse:function(t){return t.data},handleTokenValidationResponse:function(t){return t.data},authProviderPaths:{github:"/auth/github",facebook:"/auth/facebook",google:"/auth/google_oauth2"}}},e="default",{configure:function(r){var n,i,s,a,o,u,c,d,h;if(r instanceof Array&&r.length){for(a=d=0,h=r.length;h>d;a=++d){n=r[a],u=null;for(o in n)c=n[o],u=o,0===a&&(e=u);i=angular.copy(t["default"]),s={},s[u]=angular.extend(i,n[u]),angular.extend(t,s)}"default"!==e&&delete t["default"]}else{if(!(r instanceof Object))throw"Invalid argument: ng-token-auth config should be an Array or Object.";angular.extend(t["default"],r)}return t},$get:["$http","$q","$location","ipCookie","$window","$timeout","$rootScope","$interpolate",function(){return function(r,n,i,s,a,o,u,c){return{header:null,dfd:null,user:{},mustResetPassword:!1,listener:null,initialize:function(){return this.initializeListeners(),this.addScopeMethods()},initializeListeners:function(){return this.listener=angular.bind(this,this.handlePostMessage),a.addEventListener?a.addEventListener("message",this.listener,!1):void 0},cancel:function(t){return null!=this.t&&o.cancel(this.t),null!=this.dfd&&this.rejectDfd(t),o(function(t){return function(){return t.t=null}}(this),0)},destroy:function(){return this.cancel(),a.removeEventListener?a.removeEventListener("message",this.listener,!1):void 0},handlePostMessage:function(t){var e;return"deliverCredentials"===t.data.message&&(delete t.data.message,this.handleValidAuth(t.data,!0),u.$broadcast("auth:login-success",t.data)),"authFailure"===t.data.message?(e={reason:"unauthorized",errors:[t.data.error]},this.cancel(e),u.$broadcast("auth:login-error",e)):void 0},addScopeMethods:function(){return u.user=this.user,u.authenticate=angular.bind(this,this.authenticate),u.signOut=angular.bind(this,this.signOut),u.destroyAccount=angular.bind(this,this.destroyAccount),u.submitRegistration=angular.bind(this,this.submitRegistration),u.submitLogin=angular.bind(this,this.submitLogin),u.requestPasswordReset=angular.bind(this,this.requestPasswordReset),u.updatePassword=angular.bind(this,this.updatePassword),u.updateAccount=angular.bind(this,this.updateAccount),this.getConfig().validateOnPageLoad?this.validateUser({config:this.getSavedConfig()}):void 0},submitRegistration:function(t,e){var n;return null==e&&(e={}),n=this.getResultOrValue(this.getConfig(e.config).confirmationSuccessUrl),angular.extend(t,{confirm_success_url:n,config_name:this.getCurrentConfigName(e.config)}),r.post(this.apiUrl(e.config)+this.getConfig(e.config).emailRegistrationPath,t).success(function(){return u.$broadcast("auth:registration-email-success",t)}).error(function(t){return u.$broadcast("auth:registration-email-error",t)})},submitLogin:function(t,e){return null==e&&(e={}),this.initDfd(),r.post(this.apiUrl(e.config)+this.getConfig(e.config).emailSignInPath,t).success(function(t){return function(r){var n;return t.setConfigName(e.config),n=t.getConfig(e.config).handleLoginResponse(r,t),t.handleValidAuth(n),u.$broadcast("auth:login-success",t.user)}}(this)).error(function(t){return function(e){return t.rejectDfd({reason:"unauthorized",errors:["Invalid credentials"]}),u.$broadcast("auth:login-error",e)}}(this)),this.dfd.promise},userIsAuthenticated:function(){return this.retrieveData("auth_headers")&&this.user.signedIn&&!this.tokenHasExpired()},requestPasswordReset:function(t,e){var n;return null==e&&(e={}),n=this.getResultOrValue(this.getConfig(e.config).passwordResetSuccessUrl),t.redirect_url=n,null!=e.config&&(t.config_name=e.config),r.post(this.apiUrl(e.config)+this.getConfig(e.config).passwordResetPath,t).success(function(){return u.$broadcast("auth:password-reset-request-success",t)}).error(function(t){return u.$broadcast("auth:password-reset-request-error",t)})},updatePassword:function(t){return r.put(this.apiUrl()+this.getConfig().passwordUpdatePath,t).success(function(t){return function(e){return u.$broadcast("auth:password-change-success",e),t.mustResetPassword=!1}}(this)).error(function(t){return u.$broadcast("auth:password-change-error",t)})},updateAccount:function(t){return r.put(this.apiUrl()+this.getConfig().accountUpdatePath,t).success(function(t){return function(e){var r,n,i,s,a,o;if(s=t.getConfig().handleAccountUpdateResponse(e),r=t.retrieveData("auth_headers"),angular.extend(t.user,s),r){i={},o=t.getConfig().tokenFormat;for(n in o)a=o[n],r[n]&&s[n]&&(i[n]=s[n]);t.setAuthHeaders(i)}return u.$broadcast("auth:account-update-success",e)}}(this)).error(function(t){return u.$broadcast("auth:account-update-error",t)})},destroyAccount:function(t){return r["delete"](this.apiUrl()+this.getConfig().accountUpdatePath,t).success(function(t){return function(e){return t.invalidateTokens(),u.$broadcast("auth:account-destroy-success",e)}}(this)).error(function(t){return u.$broadcast("auth:account-destroy-error",t)})},authenticate:function(t,e){return null==e&&(e={}),null==this.dfd&&(this.setConfigName(e.config),this.initDfd(),this.openAuthWindow(t,e)),this.dfd.promise},setConfigName:function(t){return null==t&&(t=e),this.persistData("currentConfigName",t,t)},openAuthWindow:function(t,e){var r;return r=this.buildAuthUrl(t,e),this.useExternalWindow()?this.requestCredentials(this.createPopup(r)):this.visitUrl(r)},visitUrl:function(t){return a.location.replace(t)},buildAuthUrl:function(t,e){var r,n,i,s;if(null==e&&(e={}),r=this.getConfig(e.config).apiUrl,r+=this.getConfig(e.config).authProviderPaths[t],r+="?auth_origin_url="+encodeURIComponent(a.location.href),null!=e.params){s=e.params;for(n in s)i=s[n],r+="&",r+=encodeURIComponent(n),r+="=",r+=encodeURIComponent(i)}return r},requestCredentials:function(t){return t.closed?(this.cancel({reason:"unauthorized",errors:["User canceled login"]}),u.$broadcast("auth:window-closed")):(t.postMessage("requestCredentials","*"),this.t=o(function(e){return function(){return e.requestCredentials(t)}}(this),500))},createPopup:function(t){return a.open(t)},resolveDfd:function(){return this.dfd.resolve(this.user),o(function(t){return function(){return t.dfd=null,u.$$phase?void 0:u.$digest()}}(this),0)},validateUser:function(t){var e,r,n,s,a;return null==t&&(t={}),r=t.config,null==this.dfd&&(this.initDfd(),this.userIsAuthenticated()?this.resolveDfd():(void 0!==i.search().token?(s=i.search().token,e=i.search().client_id,a=i.search().uid,n=i.search().expiry,r=i.search().config,this.setConfigName(r),this.mustResetPassword=i.search().reset_password,this.firstTimeLogin=i.search().account_confirmation_success,this.setAuthHeaders(this.buildAuthHeaders({token:s,clientId:e,uid:a,expiry:n})),i.url(i.path()||"/")):this.retrieveData("currentConfigName")&&(r=this.retrieveData("currentConfigName")),isEmpty(this.retrieveData("auth_headers"))?(this.rejectDfd({reason:"unauthorized",errors:["No credentials"]}),u.$broadcast("auth:invalid")):this.tokenHasExpired()?(u.$broadcast("auth:session-expired"),this.rejectDfd({reason:"unauthorized",errors:["Session expired."]})):this.validateToken({config:r}))),this.dfd.promise},validateToken:function(t){return null==t&&(t={}),this.tokenHasExpired()?this.rejectDfd({reason:"unauthorized",errors:["Expired credentials"]}):r.get(this.apiUrl(t.config)+this.getConfig(t.config).tokenValidationPath).success(function(e){return function(r){var n;return n=e.getConfig(t.config).handleTokenValidationResponse(r),e.handleValidAuth(n),e.firstTimeLogin&&u.$broadcast("auth:email-confirmation-success",e.user),e.mustResetPassword&&u.$broadcast("auth:password-reset-confirm-success",e.user),u.$broadcast("auth:validation-success",e.user)}}(this)).error(function(t){return function(e){return t.firstTimeLogin&&u.$broadcast("auth:email-confirmation-error",e),t.mustResetPassword&&u.$broadcast("auth:password-reset-confirm-error",e),u.$broadcast("auth:validation-error",e),t.rejectDfd({reason:"unauthorized",errors:e.errors})}}(this))},tokenHasExpired:function(){var t,e;return t=this.getExpiry(),e=(new Date).getTime(),t&&e>t},getExpiry:function(){return this.getConfig().parseExpiry(this.retrieveData("auth_headers")||{})},invalidateTokens:function(){var t,e,r;r=this.user;for(t in r)e=r[t],delete this.user[t];return this.deleteData("currentConfigName"),this.deleteData("auth_headers")},signOut:function(){return r["delete"](this.apiUrl()+this.getConfig().signOutUrl).success(function(t){return function(){return t.invalidateTokens(),u.$broadcast("auth:logout-success")}}(this)).error(function(t){return function(e){return t.invalidateTokens(),u.$broadcast("auth:logout-error",e)}}(this))},handleValidAuth:function(t,e){return null==e&&(e=!1),null!=this.t&&o.cancel(this.t),angular.extend(this.user,t),this.user.signedIn=!0,this.user.configName=this.getCurrentConfigName(),e&&this.setAuthHeaders(this.buildAuthHeaders({token:this.user.auth_token,clientId:this.user.client_id,uid:this.user.uid,expiry:this.user.expiry})),this.resolveDfd()},buildAuthHeaders:function(t){var e,r,n,i;e={},i=this.getConfig().tokenFormat;for(r in i)n=i[r],e[r]=c(n)(t);return e},persistData:function(t,e,r){switch(this.getConfig(r).storage){case"localStorage":return a.localStorage.setItem(t,JSON.stringify(e));default:return s(t,e,{path:"/"})}},retrieveData:function(t){switch(this.getConfig().storage){case"localStorage":return JSON.parse(a.localStorage.getItem(t));default:return s(t)}},deleteData:function(t){switch(this.getConfig().storage){case"localStorage":return a.localStorage.removeItem(t);default:return s.remove(t,{path:"/"})}},setAuthHeaders:function(t){var e;return e=angular.extend(this.retrieveData("auth_headers")||{},t),this.persistData("auth_headers",e)},useExternalWindow:function(){return!(this.getConfig().forceHardRedirect||a.isIE())},initDfd:function(){return this.dfd=n.defer()},rejectDfd:function(t){return this.invalidateTokens(),null!=this.dfd?(this.dfd.reject(t),o(function(t){return function(){return t.dfd=null}}(this),0)):void 0},apiUrl:function(t){return this.getConfig(t).proxyIf()?this.getConfig(t).proxyUrl:this.getConfig(t).apiUrl},getConfig:function(e){return t[this.getCurrentConfigName(e)]},getResultOrValue:function(t){return"function"==typeof t?t():t},getCurrentConfigName:function(t){return t||this.getSavedConfig()},getSavedConfig:function(){var t,r;return t=void 0,r="currentConfigName",a.localStorage&&null==t&&(t=JSON.parse(a.localStorage.getItem(r))),null==t&&(t=s(r)),t||e}}}}(this)]}}).config(["$httpProvider",function(t){var e,r,n;return r=function(t,e){var r,n;return n=Number(t.getExpiry()),r=Number(t.getConfig().parseExpiry(e||{})),r>=n},n=function(t,e){var n,i,s,a;i={},a=t.getConfig().tokenFormat;for(n in a)s=a[n],e.headers(n)&&(i[n]=e.headers(n));return r(t,i)?t.setAuthHeaders(i):void 0},t.interceptors.push(["$injector",function(t){return{request:function(e){return t.invoke(["$http","$auth",function(t,r){var n,i,s,a;if(e.url.match(r.apiUrl())){s=r.retrieveData("auth_headers"),a=[];for(n in s)i=s[n],a.push(e.headers[n]=i);return a}}]),e},response:function(e){return t.invoke(["$http","$auth",function(t,r){return e.config.url.match(r.apiUrl())?n(r,e):void 0}]),e},responseError:function(e){return t.invoke(["$http","$auth",function(t,r){return e.config.url.match(r.apiUrl())?n(r,e):void 0}]),t.get("$q").reject(e)}}}]),e=["get","post","put","patch","delete"],angular.forEach(e,function(e){var r;return null==(r=t.defaults.headers)[e]&&(r[e]={}),t.defaults.headers[e]["If-Modified-Since"]="Mon, 26 Jul 1997 05:00:00 GMT"})}]).run(["$auth","$window","$rootScope",function(t){return t.initialize()}]),window.isOldIE=function(){var t,e,r;return e=!1,t=navigator.userAgent.toLowerCase(),t&&-1!==t.indexOf("msie")&&(r=parseInt(t.split("msie")[1]),10>r&&(e=!0)),e},window.isIE=function(){var t;return t=navigator.userAgent.toLowerCase(),t&&-1!==t.indexOf("msie")||!!navigator.userAgent.match(/Trident.*rv\:11\./)},window.isEmpty=function(t){var e,r;if(!t)return!0;if(t.length>0)return!1;if(0===t.length)return!0;for(e in t)if(r=t[e],Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}; \ No newline at end of file +"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="ng-token-auth"),angular.module("ng-token-auth",["ipCookie"]).provider("$auth",function(){var t,e;return t={"default":{apiUrl:"/api",signOutUrl:"/auth/sign_out",emailSignInPath:"/auth/sign_in",emailRegistrationPath:"/auth",accountUpdatePath:"/auth",accountDeletePath:"/auth",confirmationSuccessUrl:function(){return window.location.href},passwordResetPath:"/auth/password",passwordUpdatePath:"/auth/password",passwordResetSuccessUrl:function(){return window.location.href},tokenValidationPath:"/auth/validate_token",proxyIf:function(){return!1},proxyUrl:"/proxy",validateOnPageLoad:!0,forceHardRedirect:!1,storage:"cookies",tokenFormat:{"access-token":"{{ token }}","token-type":"Bearer",client:"{{ clientId }}",expiry:"{{ expiry }}",uid:"{{ uid }}"},parseExpiry:function(t){return 1e3*parseInt(t.expiry,10)||null},handleLoginResponse:function(t){return t.data},handleAccountUpdateResponse:function(t){return t.data},handleTokenValidationResponse:function(t){return t.data},authProviderPaths:{github:"/auth/github",facebook:"/auth/facebook",google:"/auth/google_oauth2"}}},e="default",{configure:function(r){var n,i,s,a,o,u,c,d,h;if(r instanceof Array&&r.length){for(a=d=0,h=r.length;h>d;a=++d){n=r[a],u=null;for(o in n)c=n[o],u=o,0===a&&(e=u);i=angular.copy(t["default"]),s={},s[u]=angular.extend(i,n[u]),angular.extend(t,s)}"default"!==e&&delete t["default"]}else{if(!(r instanceof Object))throw"Invalid argument: ng-token-auth config should be an Array or Object.";angular.extend(t["default"],r)}return t},$get:["$http","$q","$location","ipCookie","$window","$timeout","$rootScope","$interpolate",function(){return function(r,n,i,s,a,o,u,c){return{header:null,dfd:null,user:{},mustResetPassword:!1,listener:null,initialize:function(){return this.initializeListeners(),this.addScopeMethods()},initializeListeners:function(){return this.listener=angular.bind(this,this.handlePostMessage),a.addEventListener?a.addEventListener("message",this.listener,!1):void 0},cancel:function(t){return null!=this.t&&o.cancel(this.t),null!=this.dfd&&this.rejectDfd(t),o(function(t){return function(){return t.t=null}}(this),0)},destroy:function(){return this.cancel(),a.removeEventListener?a.removeEventListener("message",this.listener,!1):void 0},handlePostMessage:function(t){var e;return"deliverCredentials"===t.data.message&&(delete t.data.message,this.handleValidAuth(t.data,!0),u.$broadcast("auth:login-success",t.data)),"authFailure"===t.data.message?(e={reason:"unauthorized",errors:[t.data.error]},this.cancel(e),u.$broadcast("auth:login-error",e)):void 0},addScopeMethods:function(){return u.user=this.user,u.authenticate=angular.bind(this,this.authenticate),u.signOut=angular.bind(this,this.signOut),u.destroyAccount=angular.bind(this,this.destroyAccount),u.submitRegistration=angular.bind(this,this.submitRegistration),u.submitLogin=angular.bind(this,this.submitLogin),u.requestPasswordReset=angular.bind(this,this.requestPasswordReset),u.updatePassword=angular.bind(this,this.updatePassword),u.updateAccount=angular.bind(this,this.updateAccount),this.getConfig().validateOnPageLoad?this.validateUser({config:this.getSavedConfig()}):void 0},submitRegistration:function(t,e){var n;return null==e&&(e={}),n=this.getResultOrValue(this.getConfig(e.config).confirmationSuccessUrl),angular.extend(t,{confirm_success_url:n,config_name:this.getCurrentConfigName(e.config)}),r.post(this.apiUrl(e.config)+this.getConfig(e.config).emailRegistrationPath,t).success(function(){return u.$broadcast("auth:registration-email-success",t)}).error(function(t){return u.$broadcast("auth:registration-email-error",t)})},submitLogin:function(t,e){return null==e&&(e={}),this.initDfd(),r.post(this.apiUrl(e.config)+this.getConfig(e.config).emailSignInPath,t).success(function(t){return function(r){var n;return t.setConfigName(e.config),n=t.getConfig(e.config).handleLoginResponse(r,t),t.handleValidAuth(n),u.$broadcast("auth:login-success",t.user)}}(this)).error(function(t){return function(e){return t.rejectDfd({reason:"unauthorized",errors:["Invalid credentials"]}),u.$broadcast("auth:login-error",e)}}(this)),this.dfd.promise},userIsAuthenticated:function(){return this.retrieveData("auth_headers")&&this.user.signedIn&&!this.tokenHasExpired()},requestPasswordReset:function(t,e){var n;return null==e&&(e={}),n=this.getResultOrValue(this.getConfig(e.config).passwordResetSuccessUrl),t.redirect_url=n,null!=e.config&&(t.config_name=e.config),r.post(this.apiUrl(e.config)+this.getConfig(e.config).passwordResetPath,t).success(function(){return u.$broadcast("auth:password-reset-request-success",t)}).error(function(t){return u.$broadcast("auth:password-reset-request-error",t)})},updatePassword:function(t){return r.put(this.apiUrl()+this.getConfig().passwordUpdatePath,t).success(function(t){return function(e){return u.$broadcast("auth:password-change-success",e),t.mustResetPassword=!1}}(this)).error(function(t){return u.$broadcast("auth:password-change-error",t)})},updateAccount:function(t){return r.put(this.apiUrl()+this.getConfig().accountUpdatePath,t).success(function(t){return function(e){var r,n,i,s,a,o;if(s=t.getConfig().handleAccountUpdateResponse(e),r=t.retrieveData("auth_headers"),angular.extend(t.user,s),r){i={},o=t.getConfig().tokenFormat;for(n in o)a=o[n],r[n]&&s[n]&&(i[n]=s[n]);t.setAuthHeaders(i)}return u.$broadcast("auth:account-update-success",e)}}(this)).error(function(t){return u.$broadcast("auth:account-update-error",t)})},destroyAccount:function(t){return r["delete"](this.apiUrl()+this.getConfig().accountUpdatePath,t).success(function(t){return function(e){return t.invalidateTokens(),u.$broadcast("auth:account-destroy-success",e)}}(this)).error(function(t){return u.$broadcast("auth:account-destroy-error",t)})},authenticate:function(t,e){return null==e&&(e={}),null==this.dfd&&(this.setConfigName(e.config),this.initDfd(),this.openAuthWindow(t,e)),this.dfd.promise},setConfigName:function(t){return null==t&&(t=e),this.persistData("currentConfigName",t,t)},openAuthWindow:function(t,e){var r;return r=this.buildAuthUrl(t,e),this.useExternalWindow()?this.requestCredentials(this.createPopup(r)):this.visitUrl(r)},visitUrl:function(t){return a.location.replace(t)},buildAuthUrl:function(t,e){var r,n,i,s;if(null==e&&(e={}),r=this.getConfig(e.config).apiUrl,r+=this.getConfig(e.config).authProviderPaths[t],r+="?auth_origin_url="+encodeURIComponent(a.location.href),null!=e.params){s=e.params;for(n in s)i=s[n],r+="&",r+=encodeURIComponent(n),r+="=",r+=encodeURIComponent(i)}return r},requestCredentials:function(t){return t.closed?(this.cancel({reason:"unauthorized",errors:["User canceled login"]}),u.$broadcast("auth:window-closed")):(t.postMessage("requestCredentials","*"),this.t=o(function(e){return function(){return e.requestCredentials(t)}}(this),500))},createPopup:function(t){return a.open(t)},resolveDfd:function(){return this.dfd.resolve(this.user),o(function(t){return function(){return t.dfd=null,u.$$phase?void 0:u.$digest()}}(this),0)},validateUser:function(t){var e,r,n,s,a;return null==t&&(t={}),r=t.config,null==this.dfd&&(this.initDfd(),this.userIsAuthenticated()?this.resolveDfd():(void 0!==i.search().token?(s=i.search().token,e=i.search().client_id,a=i.search().uid,n=i.search().expiry,r=i.search().config,this.setConfigName(r),this.mustResetPassword=i.search().reset_password,this.firstTimeLogin=i.search().account_confirmation_success,this.setAuthHeaders(this.buildAuthHeaders({token:s,clientId:e,uid:a,expiry:n})),i.url(i.path()||"/")):this.retrieveData("currentConfigName")&&(r=this.retrieveData("currentConfigName")),isEmpty(this.retrieveData("auth_headers"))?(this.rejectDfd({reason:"unauthorized",errors:["No credentials"]}),u.$broadcast("auth:invalid")):this.tokenHasExpired()?(u.$broadcast("auth:session-expired"),this.rejectDfd({reason:"unauthorized",errors:["Session expired."]})):this.validateToken({config:r}))),this.dfd.promise},validateToken:function(t){return null==t&&(t={}),this.tokenHasExpired()?this.rejectDfd({reason:"unauthorized",errors:["Expired credentials"]}):r.get(this.apiUrl(t.config)+this.getConfig(t.config).tokenValidationPath).success(function(e){return function(r){var n;return n=e.getConfig(t.config).handleTokenValidationResponse(r),e.handleValidAuth(n),e.firstTimeLogin&&u.$broadcast("auth:email-confirmation-success",e.user),e.mustResetPassword&&u.$broadcast("auth:password-reset-confirm-success",e.user),u.$broadcast("auth:validation-success",e.user)}}(this)).error(function(t){return function(e){return t.firstTimeLogin&&u.$broadcast("auth:email-confirmation-error",e),t.mustResetPassword&&u.$broadcast("auth:password-reset-confirm-error",e),u.$broadcast("auth:validation-error",e),t.rejectDfd({reason:"unauthorized",errors:e.errors})}}(this))},tokenHasExpired:function(){var t,e;return t=this.getExpiry(),e=(new Date).getTime(),t&&e>t},getExpiry:function(){return this.getConfig().parseExpiry(this.retrieveData("auth_headers")||{})},invalidateTokens:function(){var t,e,r;r=this.user;for(t in r)e=r[t],delete this.user[t];return this.deleteData("currentConfigName"),this.deleteData("auth_headers")},signOut:function(){return r["delete"](this.apiUrl()+this.getConfig().signOutUrl).success(function(t){return function(){return t.invalidateTokens(),u.$broadcast("auth:logout-success")}}(this)).error(function(t){return function(e){return t.invalidateTokens(),u.$broadcast("auth:logout-error",e)}}(this))},handleValidAuth:function(t,e){return null==e&&(e=!1),null!=this.t&&o.cancel(this.t),angular.extend(this.user,t),this.user.signedIn=!0,this.user.configName=this.getCurrentConfigName(),e&&this.setAuthHeaders(this.buildAuthHeaders({token:this.user.auth_token,clientId:this.user.client_id,uid:this.user.uid,expiry:this.user.expiry})),this.resolveDfd()},buildAuthHeaders:function(t){var e,r,n,i;e={},i=this.getConfig().tokenFormat;for(r in i)n=i[r],e[r]=c(n)(t);return e},persistData:function(t,e,r){switch(this.getConfig(r).storage){case"localStorage":return a.localStorage.setItem(t,JSON.stringify(e));default:return s(t,e,{path:"/"})}},retrieveData:function(t){switch(this.getConfig().storage){case"localStorage":return JSON.parse(a.localStorage.getItem(t));default:return s(t)}},deleteData:function(t){switch(this.getConfig().storage){case"localStorage":return a.localStorage.removeItem(t);default:return s.remove(t,{path:"/"})}},setAuthHeaders:function(t){var e;return e=angular.extend(this.retrieveData("auth_headers")||{},t),this.persistData("auth_headers",e)},useExternalWindow:function(){return!(this.getConfig().forceHardRedirect||a.isIE())},initDfd:function(){return this.dfd=n.defer()},rejectDfd:function(t){return this.invalidateTokens(),null!=this.dfd?(this.dfd.reject(t),o(function(t){return function(){return t.dfd=null}}(this),0)):void 0},apiUrl:function(t){return this.getConfig(t).proxyIf()?this.getConfig(t).proxyUrl:this.getConfig(t).apiUrl},getConfig:function(e){return t[this.getCurrentConfigName(e)]},getResultOrValue:function(t){return"function"==typeof t?t():t},getCurrentConfigName:function(t){return t||this.getSavedConfig()},getSavedConfig:function(){var t,r;return t=void 0,r="currentConfigName",a.localStorage&&null==t&&(t=JSON.parse(a.localStorage.getItem(r))),null==t&&(t=s(r)),t||e}}}}(this)]}}).config(["$httpProvider",function(t){var e,r,n;return r=function(t,e){var r,n;return n=Number(t.getExpiry()),r=Number(t.getConfig().parseExpiry(e||{})),r>=n},n=function(t,e){var n,i,s,a;i={},a=t.getConfig().tokenFormat;for(n in a)s=a[n],e.headers(n)&&(i[n]=e.headers(n));return r(t,i)?t.setAuthHeaders(i):void 0},t.interceptors.push(["$injector",function(t){return{request:function(e){return t.invoke(["$http","$auth",function(t,r){var n,i,s,a;if(e.url.match(r.apiUrl())){s=r.retrieveData("auth_headers"),a=[];for(n in s)i=s[n],a.push(e.headers[n]=i);return a}}]),e},response:function(e){return t.invoke(["$http","$auth",function(t,r){return e.config.url.match(r.apiUrl())?n(r,e):void 0}]),e},responseError:function(e){return t.invoke(["$http","$auth",function(t,r){return e.config.url.match(r.apiUrl())?n(r,e):void 0}]),t.get("$q").reject(e)}}}]),e=["get","post","put","patch","delete"],angular.forEach(e,function(e){var r;return null==(r=t.defaults.headers)[e]&&(r[e]={}),t.defaults.headers[e]["If-Modified-Since"]="Mon, 26 Jul 1997 05:00:00 GMT"})}]).run(["$auth","$window","$rootScope",function(t){return t.initialize()}]),window.isOldIE=function(){var t,e,r;return e=!1,t=navigator.userAgent.toLowerCase(),t&&-1!==t.indexOf("msie")&&(r=parseInt(t.split("msie")[1]),10>r&&(e=!0)),e},window.isIE=function(){var t;return t=navigator.userAgent.toLowerCase(),t&&-1!==t.indexOf("msie")||!!navigator.userAgent.match(/Trident.*rv\:11\./)},window.isEmpty=function(t){var e,r;if(!t)return!0;if(t.length>0)return!1;if(0===t.length)return!0;for(e in t)if(r=t[e],Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}; \ No newline at end of file diff --git a/package.json b/package.json index bad1b521..513d3174 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "request": "~2.36.0", "sitemap": "~0.7.3" }, + "main": "dist/ng-token-auth.js", "npmName": "ng-token-auth", "npmFileMap": [ { diff --git a/src/ng-token-auth.coffee b/src/ng-token-auth.coffee index ff703dbd..a404f4b0 100644 --- a/src/ng-token-auth.coffee +++ b/src/ng-token-auth.coffee @@ -1,3 +1,6 @@ +if typeof module != 'undefined' and typeof exports != 'undefined' and module.exports == exports + module.exports = 'ng-token-auth' + angular.module('ng-token-auth', ['ipCookie']) .provider('$auth', -> configs =