diff --git a/.gitignore b/.gitignore index 522163c..67a0dad 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules +npm-debug.log bower_components components diff --git a/README.md b/README.md index 938ab16..ad36219 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ for AngularJS ------------- This is the implementation of the concept described in -[Authentication in AngularJS (or similar) based application](http://www.espeo.pl/1-authentication-in-angularjs-application/). +[Authentication in AngularJS (or similar) based application](http://espeo.eu/blog/authentication-in-angularjs-or-similar-based-application/). There are releases for both AngularJS **1.0.x** and **1.2.x**, see [releases](https://github.com/witoldsz/angular-http-auth/releases). @@ -16,7 +16,8 @@ branch for source code of the demo. Usage ------ -- Install via bower: `bower install --save` +- Install via bower: `bower install --save angular-http-auth` +- ...or via npm: `npm install --save angular-http-auth` - Include as a dependency in your app: `angular.module('myApp', ['http-auth-interceptor'])` Manual @@ -29,22 +30,28 @@ the configuration object (this is the requested URL, payload and parameters) of every HTTP 401 response is buffered and everytime it happens, the `event:auth-loginRequired` message is broadcasted from $rootScope. -The `authService` has only one method: #loginConfirmed(). -You are responsible to invoke this method after user logged in. You may optionally pass in -a data argument to the loginConfirmed method which will be passed on to the loginConfirmed +The `authService` has only 2 methods: `loginConfirmed()` and `loginCancelled()`. + +You are responsible to invoke `loginConfirmed()` after user logs in. You may optionally pass in +a data argument to this method which will be passed on to the loginConfirmed $broadcast. This may be useful, for example if you need to pass through details of the user that was logged in. The `authService` will then retry all the requests previously failed due to HTTP 401 response. -In the event that a requested resource returns an HTTP 403 response (i.e. the user is -authenticated but not authorized to access the resource), the user's request is discarded and -the `event:auth-forbidden` message is broadcasted from $rootScope. +You are responsible to invoke `loginCancelled()` when authentication has been invalidated. You may optionally pass in +a data argument to this method which will be passed on to the loginCancelled +$broadcast. The `authService` will cancel all pending requests previously failed and buffered due +to HTTP 401 response. + +In the event that a requested resource returns an HTTP 403 response (i.e. the user is +authenticated but not authorized to access the resource), the user's request is discarded and +the `event:auth-forbidden` message is broadcast from $rootScope. #### Ignoring the 401 interceptor -Sometimes you might not want the intercepter to intercept a request even if one returns 401 or 403. In a case like this you can add `ignoreAuthModule: true` to the request config. A common use case for this would be, for example, a login request which returns 401 if the login credentials are invalid. +Sometimes you might not want the interceptor to intercept a request even if one returns 401 or 403. In a case like this you can add `ignoreAuthModule: true` to the request config. A common use case for this would be, for example, a login request which returns 401 if the login credentials are invalid. -###Typical use case: +### Typical use case: * somewhere (some service or controller) the: `$http(...).then(function(response) { do-something-with-response })` is invoked, * the response of that requests is a **HTTP 401**, @@ -56,28 +63,33 @@ Sometimes you might not want the intercepter to intercept a request even if one the `function(response) {do-something-with-response}` will fire, * your application will continue as nothing had happened. -###Advanced use case: +### Advanced use case: -####Sending data to listeners: -You can supply additional data to observers across your application who are listening for `event:auth-loginConfirmed`: +#### Sending data to listeners: +You can supply additional data to observers across your application who are listening for `event:auth-loginConfirmed` and `event:auth-loginCancelled`: $scope.$on('event:auth-loginConfirmed', function(event, data){ $rootScope.isLoggedin = true; $log.log(data) }); -Use the `authService.loginConfirmed([data])` method to emit data with your login event. + $scope.$on('event:auth-loginCancelled', function(event, data){ + $rootScope.isLoggedin = false; + $log.log(data) + }); + +Use the `authService.loginConfirmed([data])` and `authService.loginCancelled([data])` methods to emit data with your login and logout events. -####Updating [$http(config)](https://docs.angularjs.org/api/ng/service/$http): -Successful login means that the previous request are ready to be fired again, however now that login has occured certain aspects of the previous requests might need to be modified on the fly. This is particularly important in a token based authentication scheme where an authorization token should be added to the header. +#### Updating [$http(config)](https://docs.angularjs.org/api/ng/service/$http): +Successful login means that the previous request are ready to be fired again, however now that login has occurred certain aspects of the previous requests might need to be modified on the fly. This is particularly important in a token based authentication scheme where an authorization token should be added to the header. The `loginConfirmed` method supports the injection of an Updater function that will apply changes to the http config object. authService.loginConfirmed([data], [Updater-Function]) - + //application of tokens to previously fired requests: - var token = reponse.token; - + var token = response.token; + authService.loginConfirmed('success', function(config){ config.headers["Authorization"] = token; return config; @@ -85,3 +97,10 @@ The `loginConfirmed` method supports the injection of an Updater function that w The initial failed request will now be retried, all queued http requests will be recalculated using the Updater-Function. +It is also possible to stop specific request from being retried, by returning ``false`` from the Updater-Function: + + authService.loginConfirmed('success', function(config){ + if (shouldSkipRetryOnSuccess(config)) + return false; + return config; + }) diff --git a/bower.json b/bower.json index 8b02643..54fac45 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,6 @@ { "author": "Witold Szczerba", "name": "angular-http-auth", - "version": "1.2.1", "homepage": "https://github.com/witoldsz/angular-http-auth", "repository": { "type": "git", @@ -10,5 +9,9 @@ "main": "./src/http-auth-interceptor.js", "dependencies": { "angular": "^1.2" - } + }, + "ignore": [ + "package.json" + ], + "license": "MIT" } diff --git a/dist/http-auth-interceptor.js b/dist/http-auth-interceptor.js new file mode 100644 index 0000000..3cff6cc --- /dev/null +++ b/dist/http-auth-interceptor.js @@ -0,0 +1,141 @@ +/*global angular:true, browser:true */ + +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2012 Witold Szczerba + * License: MIT + */ + +(function () { + 'use strict'; + + angular.module('http-auth-interceptor', ['http-auth-interceptor-buffer']) + + .factory('authService', ['$rootScope','httpBuffer', function($rootScope, httpBuffer) { + return { + /** + * Call this function to indicate that authentication was successful and trigger a + * retry of all deferred requests. + * @param data an optional argument to pass on to $broadcast which may be useful for + * example if you need to pass through details of the user that was logged in + * @param configUpdater an optional transformation function that can modify the + * requests that are retried after having logged in. This can be used for example + * to add an authentication token. It must return the request. + */ + loginConfirmed: function(data, configUpdater) { + var updater = configUpdater || function(config) {return config;}; + $rootScope.$broadcast('event:auth-loginConfirmed', data); + httpBuffer.retryAll(updater); + }, + + /** + * Call this function to indicate that authentication should not proceed. + * All deferred requests will be abandoned or rejected (if reason is provided). + * @param data an optional argument to pass on to $broadcast. + * @param reason if provided, the requests are rejected; abandoned otherwise. + */ + loginCancelled: function(data, reason) { + httpBuffer.rejectAll(reason); + $rootScope.$broadcast('event:auth-loginCancelled', data); + } + }; + }]) + + /** + * $http interceptor. + * On 401 response (without 'ignoreAuthModule' option) stores the request + * and broadcasts 'event:auth-loginRequired'. + * On 403 response (without 'ignoreAuthModule' option) discards the request + * and broadcasts 'event:auth-forbidden'. + */ + .config(['$httpProvider', function($httpProvider) { + $httpProvider.interceptors.push(['$rootScope', '$q', 'httpBuffer', function($rootScope, $q, httpBuffer) { + return { + responseError: function(rejection) { + var config = rejection.config || {}; + if (!config.ignoreAuthModule) { + switch (rejection.status) { + case 401: + var deferred = $q.defer(); + var bufferLength = httpBuffer.append(config, deferred); + if (bufferLength === 1) + $rootScope.$broadcast('event:auth-loginRequired', rejection); + return deferred.promise; + case 403: + $rootScope.$broadcast('event:auth-forbidden', rejection); + break; + } + } + // otherwise, default behaviour + return $q.reject(rejection); + } + }; + }]); + }]); + + /** + * Private module, a utility, required internally by 'http-auth-interceptor'. + */ + angular.module('http-auth-interceptor-buffer', []) + + .factory('httpBuffer', ['$injector', function($injector) { + /** Holds all the requests, so they can be re-requested in future. */ + var buffer = []; + + /** Service initialized later because of circular dependency problem. */ + var $http; + + function retryHttpRequest(config, deferred) { + function successCallback(response) { + deferred.resolve(response); + } + function errorCallback(response) { + deferred.reject(response); + } + $http = $http || $injector.get('$http'); + $http(config).then(successCallback, errorCallback); + } + + return { + /** + * Appends HTTP request configuration object with deferred response attached to buffer. + * @return {Number} The new length of the buffer. + */ + append: function(config, deferred) { + return buffer.push({ + config: config, + deferred: deferred + }); + }, + + /** + * Abandon or reject (if reason provided) all the buffered requests. + */ + rejectAll: function(reason) { + if (reason) { + for (var i = 0; i < buffer.length; ++i) { + buffer[i].deferred.reject(reason); + } + } + buffer = []; + }, + + /** + * Retries all the buffered requests clears the buffer. + */ + retryAll: function(updater) { + for (var i = 0; i < buffer.length; ++i) { + var _cfg = updater(buffer[i].config); + if (_cfg !== false) + retryHttpRequest(_cfg, buffer[i].deferred); + } + buffer = []; + } + }; + }]); +})(); + +/* commonjs package manager support (eg componentjs) */ +if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ + module.exports = 'http-auth-interceptor'; +} diff --git a/dist/http-auth-interceptor.min.js b/dist/http-auth-interceptor.min.js new file mode 100644 index 0000000..167529a --- /dev/null +++ b/dist/http-auth-interceptor.min.js @@ -0,0 +1 @@ +!function(){"use strict";angular.module("http-auth-interceptor",["http-auth-interceptor-buffer"]).factory("authService",["$rootScope","httpBuffer",function($rootScope,httpBuffer){return{loginConfirmed:function(data,configUpdater){var updater=configUpdater||function(config){return config};$rootScope.$broadcast("event:auth-loginConfirmed",data),httpBuffer.retryAll(updater)},loginCancelled:function(data,reason){httpBuffer.rejectAll(reason),$rootScope.$broadcast("event:auth-loginCancelled",data)}}}]).config(["$httpProvider",function($httpProvider){$httpProvider.interceptors.push(["$rootScope","$q","httpBuffer",function($rootScope,$q,httpBuffer){return{responseError:function(rejection){var config=rejection.config||{};if(!config.ignoreAuthModule)switch(rejection.status){case 401:var deferred=$q.defer(),bufferLength=httpBuffer.append(config,deferred);return 1===bufferLength&&$rootScope.$broadcast("event:auth-loginRequired",rejection),deferred.promise;case 403:$rootScope.$broadcast("event:auth-forbidden",rejection)}return $q.reject(rejection)}}}])}]),angular.module("http-auth-interceptor-buffer",[]).factory("httpBuffer",["$injector",function($injector){function retryHttpRequest(config,deferred){function successCallback(response){deferred.resolve(response)}function errorCallback(response){deferred.reject(response)}$http=$http||$injector.get("$http"),$http(config).then(successCallback,errorCallback)}var $http,buffer=[];return{append:function(config,deferred){return buffer.push({config:config,deferred:deferred})},rejectAll:function(reason){if(reason)for(var i=0;i dist/http-auth-interceptor.js", + "version": "npm run build && git add -A dist", + "postversion": "git push && git push --tags" + } +} diff --git a/src/http-auth-interceptor.js b/src/http-auth-interceptor.js index 7e85967..3cff6cc 100644 --- a/src/http-auth-interceptor.js +++ b/src/http-auth-interceptor.js @@ -5,6 +5,7 @@ * (c) 2012 Witold Szczerba * License: MIT */ + (function () { 'use strict'; @@ -13,11 +14,11 @@ .factory('authService', ['$rootScope','httpBuffer', function($rootScope, httpBuffer) { return { /** - * Call this function to indicate that authentication was successfull and trigger a + * Call this function to indicate that authentication was successful and trigger a * retry of all deferred requests. * @param data an optional argument to pass on to $broadcast which may be useful for * example if you need to pass through details of the user that was logged in - * @param configUpdater an optional transformation function that can modify the + * @param configUpdater an optional transformation function that can modify the * requests that are retried after having logged in. This can be used for example * to add an authentication token. It must return the request. */ @@ -51,12 +52,14 @@ $httpProvider.interceptors.push(['$rootScope', '$q', 'httpBuffer', function($rootScope, $q, httpBuffer) { return { responseError: function(rejection) { - if (!rejection.config.ignoreAuthModule) { + var config = rejection.config || {}; + if (!config.ignoreAuthModule) { switch (rejection.status) { case 401: var deferred = $q.defer(); - httpBuffer.append(rejection.config, deferred); - $rootScope.$broadcast('event:auth-loginRequired', rejection); + var bufferLength = httpBuffer.append(config, deferred); + if (bufferLength === 1) + $rootScope.$broadcast('event:auth-loginRequired', rejection); return deferred.promise; case 403: $rootScope.$broadcast('event:auth-forbidden', rejection); @@ -96,9 +99,10 @@ return { /** * Appends HTTP request configuration object with deferred response attached to buffer. + * @return {Number} The new length of the buffer. */ append: function(config, deferred) { - buffer.push({ + return buffer.push({ config: config, deferred: deferred }); @@ -121,10 +125,17 @@ */ retryAll: function(updater) { for (var i = 0; i < buffer.length; ++i) { - retryHttpRequest(updater(buffer[i].config), buffer[i].deferred); + var _cfg = updater(buffer[i].config); + if (_cfg !== false) + retryHttpRequest(_cfg, buffer[i].deferred); } buffer = []; } }; }]); })(); + +/* commonjs package manager support (eg componentjs) */ +if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ + module.exports = 'http-auth-interceptor'; +}