diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67a0dad --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules +npm-debug.log +bower_components +components diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b94f1f6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2012 Witold Szczerba + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index eefd6ac..ad36219 100644 --- a/README.md +++ b/README.md @@ -3,35 +3,104 @@ HTTP Auth Interceptor Module for AngularJS ------------- -This is the implementation of the concept described in -[Authentication in AngularJS (or similar) based application](http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application). +This is the implementation of the concept described in +[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). Launch demo [here](http://witoldsz.github.com/angular-http-auth/) -or switch to [gh-pages](https://github.com/witoldsz/angular-http-auth/tree/gh-pages) +or switch to [gh-pages](https://github.com/witoldsz/angular-http-auth/tree/gh-pages) branch for source code of the demo. +Usage +------ + +- 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 ------ -This module installs $http interceptor and provides the 'authService'. +This module installs $http interceptor and provides the `authService`. The $http interceptor does the following: -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 -$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 +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 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. -###Typical use case: +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 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: + +* 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**, +* `http-auth-interceptor` captures the initial request and broadcasts `event:auth-loginRequired`, +* your application intercepts this to e.g. show a login dialog: + * DO NOT REDIRECT anywhere (you can hide your forms), just show login dialog +* once your application figures out the authentication is OK, call: `authService.loginConfirmed()`, +* your initial failed request will now be retried and when proper response is finally received, +the `function(response) {do-something-with-response}` will fire, +* your application will continue as nothing had happened. + +### Advanced use case: + +#### 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) + }); + + $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 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 = response.token; + + authService.loginConfirmed('success', function(config){ + config.headers["Authorization"] = token; + return config; + }) + +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: -* somewhere the: **$http(...).then(function(response) { do-something-with-response })** is invoked, -* the response of that requests is a HTTP 401, -* 'http-auth-interceptor' captures the initial request and broadcasts 'event:auth-loginRequired', -* your application intercepts this to e.g. show a login dialog (or whatever else), -* once your application figures out the authentication is OK, you are to call: **authService.loginConfirmed()**, -* your initial failed request will now be retried and finally, the **do-something-with-response** will fire. + authService.loginConfirmed('success', function(config){ + if (shouldSkipRetryOnSuccess(config)) + return false; + return config; + }) diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..54fac45 --- /dev/null +++ b/bower.json @@ -0,0 +1,17 @@ +{ + "author": "Witold Szczerba", + "name": "angular-http-auth", + "homepage": "https://github.com/witoldsz/angular-http-auth", + "repository": { + "type": "git", + "url": "git://github.com/witoldsz/angular-http-auth.git" + }, + "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 cadd055..3cff6cc 100644 --- a/src/http-auth-interceptor.js +++ b/src/http-auth-interceptor.js @@ -5,57 +5,74 @@ * (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 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 + * 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) { + loginConfirmed: function(data, configUpdater) { + var updater = configUpdater || function(config) {return config;}; $rootScope.$broadcast('event:auth-loginConfirmed', data); - httpBuffer.retryAll(); + 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:angular-auth-loginRequired'. + * 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) { - - var interceptor = ['$rootScope', '$q', 'httpBuffer', function($rootScope, $q, httpBuffer) { - function success(response) { - return response; - } - - function error(response) { - if (response.status === 401 && !response.config.ignoreAuthModule) { - var deferred = $q.defer(); - httpBuffer.append(response.config, deferred); - $rootScope.$broadcast('event:auth-loginRequired'); - return deferred.promise; + $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); } - // otherwise, default behaviour - return $q.reject(response); - } - - return function(promise) { - return promise.then(success, error); }; - - }]; - $httpProvider.responseInterceptors.push(interceptor); + }]); }]); - + /** * Private module, a utility, required internally by 'http-auth-interceptor'. */ @@ -64,10 +81,10 @@ .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; - + var $http; + function retryHttpRequest(config, deferred) { function successCallback(response) { deferred.resolve(response); @@ -78,27 +95,47 @@ $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) { - buffer.push({ - config: config, + 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() { + retryAll: function(updater) { for (var i = 0; i < buffer.length; ++i) { - retryHttpRequest(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'; +}