From 59432e84b470ac7433dd261dd9ad8113a6db0678 Mon Sep 17 00:00:00 2001 From: Dave Woodward Date: Mon, 12 Dec 2016 19:31:27 -0600 Subject: [PATCH 1/2] fix: Modify Promise handling code to use "then" rather than "success/error." (#29) --- tests/ngRouteApp.js | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/tests/ngRouteApp.js b/tests/ngRouteApp.js index c43cb5a..6799212 100644 --- a/tests/ngRouteApp.js +++ b/tests/ngRouteApp.js @@ -61,63 +61,63 @@ ngRouteApp.factory('TaskFactory', ['$http', function($http) { ngRouteApp.controller('TaskCtl', ['$scope', '$location', 'salteAuthService', 'TaskFactory', 'ItemFactory', function($scope, $location, salteAuthService, TaskFactory, ItemFactory) { $scope.taskCall = function() { - TaskFactory.getItem(5).success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem(5).then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.itemCall = function() { - ItemFactory.getItem(13).success(function(data) { - $scope.item = data; - }).error(function(err) { + ItemFactory.getItem(13).then(function(response) { + $scope.item = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.taskCall2 = function() { - TaskFactory.getItem2('https://test.com/').success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem2('https://test.com/').then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.taskCall3 = function() { - TaskFactory.getItem2('https://testapi.com/').success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem2('https://testapi.com/').then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.taskCall4 = function() { - TaskFactory.getItem2('/someapi/item').success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem2('/someapi/item').then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.taskCall5 = function() { - TaskFactory.getItem2('https://myapp.com/someapi/item').success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem2('https://myapp.com/someapi/item').then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loadingMsg = ''; }); }; $scope.taskCall6 = function() { - TaskFactory.getItem2('http://testwebapi.com/').success(function(data) { - $scope.task = data; - }).error(function(err) { + TaskFactory.getItem2('http://testwebapi.com/').then(function(response) { + $scope.task = response.data; + }, function(err) { $scope.error = err; $scope.loaingMsg = ''; }); From 551ad591007dcf3dbc72ef238bee075e937e4b48 Mon Sep 17 00:00:00 2001 From: salte-bot Date: Tue, 13 Dec 2016 01:33:42 +0000 Subject: [PATCH 2/2] v1.0.8 --- dist/salte-auth-angular.js | 2 ++ dist/salte-auth-angular.js.map | 1 + package.json | 4 ++-- 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 dist/salte-auth-angular.js create mode 100644 dist/salte-auth-angular.js.map diff --git a/dist/salte-auth-angular.js b/dist/salte-auth-angular.js new file mode 100644 index 0000000..c6078a0 --- /dev/null +++ b/dist/salte-auth-angular.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("angular"),require("salte-auth")):"function"==typeof define&&define.amd?define("salte-auth-angular",["angular","salte-auth"],t):"object"==typeof exports?exports["salte-auth-angular"]=t(require("angular"),require("salte-auth")):e["salte-auth-angular"]=t(e.angular,e["salte-auth"])}(this,function(e,t){return function(e){function t(o){if(r[o])return r[o].exports;var n=r[o]={exports:{},id:o,loaded:!1};return e[o].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),i=o(n),a=r(1),u=o(a),c=r(2),s=o(c),l=i["default"].module("salte.auth-angular",[]);l.factory("ProtectedResourceInterceptor",u["default"]),l.provider("salteAuthService",s["default"]),t["default"]=l.name},function(e,t){"use strict";function r(e,t,r){return{request:function(n){if(n){var i=function(){n.headers=n.headers||{};var o=e.getResourceForEndpoint(n.url);if(e.verbose("Url: "+n.url+" maps to resource: "+o),null===o)return{v:n};var i=e.getCachedToken(o);if(i)return e.info("Token is available for this url "+n.url),n.headers.Authorization="Bearer "+i,{v:n};var a=void 0;return e.loginInProgress()?e.config.popUp?(e.info("Url: "+n.url+" will be loaded after login is successful"),a=t.defer(),r.$on("salte-auth:loginSuccess",function(t,r){r&&(e.info("Login completed, sending request for "+n.url),n.headers.Authorization="Bearer "+i,a.resolve(n))}),{v:a.promise}):(e.info("login is in progress."),n.data="login in progress, cancelling the request for "+n.url,{v:t.reject(n)}):(a=t.defer(),e.acquireToken(o).then(function(t){e.verbose("Token is available"),n.headers.Authorization="Bearer "+t,a.resolve(n)},function(e){n.data=e,a.reject(n)}),{v:a.promise})}();if("object"===("undefined"==typeof i?"undefined":o(i)))return i.v}},responseError:function(o){if(e.info("Getting error in the response."),o){if(401===o.status){var n=e.getResourceForEndpoint(o.config.url);e.clearCacheForResource(n),r.$broadcast("salte-auth:notAuthorized",o,n)}else r.$broadcast("salte-auth:errorResponse",o);return t.reject(o)}}}}r.$inject=["salteAuthService","$q","$rootScope"],Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t["default"]=r},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){var e=null,t={isAuthenticated:!1,userName:"",loginError:"",profile:""},r=function(r){var o=e.getCachedToken(r);t.isAuthenticated=null!==o&&o.length>0;var n=e.getCachedUser()||{userName:""};t.userName=n.userName,t.profile=n.profile,t.loginError=e.getLoginError()};this.init=function(t,o){if(!t)throw new Error("You must set configOptions, when calling init");var n=window.location.hash,a=window.location.href;n&&(a=a.replace(n,"")),t.redirectUri=t.redirectUri||a,t.postLogoutRedirectUri=t.postLogoutRedirectUri||a,t.isAngular=!0,o&&o.interceptors&&o.interceptors.push("ProtectedResourceInterceptor"),e=new i["default"](t),r(e.config.loginResource)},this.$get=function(o,n,i,a,u,c){function s(e,t){return t.requireAuthentication?e.requireAuthentication!==!1:Boolean(e.requireAuthentication)}function l(t){if(e.config&&e.config.anonymousEndpoints)for(var r=0;r-1)return!0;return!1}function f(e){var t=null,r=[];if(e.hasOwnProperty("parent"))for(t=e;t;)r.unshift(t),t=c.get("$state").get(t.parent);else for(var o=e.name.split("."),n=0,i=o[0];n-1&&a.url(p.substring(p.indexOf("#")+1)),n.location=p)}}else o.$broadcast("salte-auth:stateMismatch",e._getItem(e.CONSTANTS.STORAGE.ERROR_DESCRIPTION))}else r(e.config.loginResource),t.isAuthenticated||!t.userName||e._renewActive||(e._renewActive=!0,e.acquireToken(e.config.loginResource,function(r,n){e._renewActive=!1,r?o.$broadcast("salte-auth:loginFailure","auto renew failure"):n&&(t.isAuthenticated=!0)}));u(function(){r(e.config.loginResource),o.userInfo=t},1)},d=function(){e.info("Login event for:"+a.$$url),e.config&&e.config.localLoginUrl?a.path(e.config.localLoginUrl):(e.info("Start login at:"+window.location.href),o.$broadcast("salte-auth:loginRedirect"),e.login(a.absUrl()))},p=function(r,o){if(o&&o.$$route)if(s(o.$$route,e.config))t.isAuthenticated||e._renewActive||e.loginInProgress()||(e.info("Route change event for:"+a.$$url),d());else{var n=void 0;n="function"==typeof o.$$route.templateUrl?o.$$route.templateUrl(o.params):o.$$route.templateUrl,n&&!l(n)&&e.config.anonymousEndpoints.push(n)}},h=function(r,o,n,i,u){if(o)for(var c=f(o),g=null,p=0;p 0;\n\t var user = salteAuth.getCachedUser() || {\n\t userName: ''\n\t };\n\t _oauthData.userName = user.userName;\n\t _oauthData.profile = user.profile;\n\t _oauthData.loginError = salteAuth.getLoginError();\n\t };\n\t\n\t this.init = function (configOptions, httpProvider) {\n\t if (configOptions) {\n\t // redirect and logout_redirect are set to current location by default\n\t var existingHash = window.location.hash;\n\t var pathDefault = window.location.href;\n\t if (existingHash) {\n\t pathDefault = pathDefault.replace(existingHash, '');\n\t }\n\t configOptions.redirectUri = configOptions.redirectUri || pathDefault;\n\t configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;\n\t configOptions.isAngular = true;\n\t\n\t if (httpProvider && httpProvider.interceptors) {\n\t httpProvider.interceptors.push('ProtectedResourceInterceptor');\n\t }\n\t\n\t // create instance with given config\n\t salteAuth = new _salteAuth2.default(configOptions);\n\t } else {\n\t throw new Error('You must set configOptions, when calling init');\n\t }\n\t\n\t // loginResource is used to set authenticated status\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t };\n\t\n\t /* @ngInject */\n\t this.$get = function SalteAuthService($rootScope, $window, $q, $location, $timeout, $injector) {\n\t var locationChangeHandler = function locationChangeHandler(event, newUrl, oldUrl) {\n\t salteAuth.verbose('Location change event from ' + oldUrl + ' to ' + newUrl);\n\t var hash = $window.location.hash;\n\t var search = $window.location.search;\n\t\n\t if (salteAuth.isCallback(hash, search)) {\n\t // callback can come from login or iframe request\n\t salteAuth.verbose('Processing Callback, Hash: ' + hash + '; Search String: ' + search);\n\t var requestInfo = salteAuth.getRequestInfo(hash, search);\n\t salteAuth.saveTokenFromHash(requestInfo);\n\t\n\t // Return to callback if it is sent from iframe\n\t if (requestInfo.stateMatch) {\n\t if (requestInfo.requestType === salteAuth.REQUEST_TYPE.RENEW_TOKEN) {\n\t var callback = $window.parent.AuthenticationContext.callBackMappedToRenewStates[requestInfo.stateResponse];\n\t // since this is a token renewal request in iFrame, we don't need to proceed with the location change.\n\t event.preventDefault();\n\t\n\t // Call within the same context without full page redirect keeps the callback\n\t if (callback && typeof callback === 'function') {\n\t // id_token or access_token can be renewed\n\t if (requestInfo.parameters.access_token) {\n\t callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.access_token);\n\t return;\n\t } else if (requestInfo.parameters.id_token) {\n\t callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.id_token);\n\t return;\n\t } else if (requestInfo.parameters.error) {\n\t callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null);\n\t return;\n\t }\n\t }\n\t } else if (requestInfo.requestType === salteAuth.REQUEST_TYPE.LOGIN) {\n\t // normal full login redirect happened on the page\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t if (_oauthData.userName) {\n\t $timeout(function () {\n\t // id_token is added as token for the app\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t $rootScope.userInfo = _oauthData;\n\t }, 1);\n\t\n\t $rootScope.$broadcast('salte-auth:loginSuccess', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.IDTOKEN));\n\t } else {\n\t $rootScope.$broadcast('salte-auth:loginFailure', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION));\n\t }\n\t\n\t if (salteAuth.callback && typeof salteAuth.callback === 'function') {\n\t salteAuth.callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.IDTOKEN));\n\t }\n\t\n\t // redirect to login start page\n\t if (!salteAuth.popUp) {\n\t var loginStartPage = salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.LOGIN_REQUEST);\n\t if (typeof loginStartPage !== 'undefined' && loginStartPage && loginStartPage.length !== 0) {\n\t // prevent the current location change and redirect the user back to the login start page\n\t salteAuth.verbose('Redirecting to start page: ' + loginStartPage);\n\t if (!$location.$$html5 && loginStartPage.indexOf('#') > -1) {\n\t $location.url(loginStartPage.substring(loginStartPage.indexOf('#') + 1));\n\t }\n\t $window.location = loginStartPage;\n\t }\n\t } else {\n\t event.preventDefault();\n\t }\n\t }\n\t } else {\n\t // state did not match, broadcast an error\n\t $rootScope.$broadcast('salte-auth:stateMismatch', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION));\n\t }\n\t } else {\n\t // No callback. App resumes after closing or moving to new page.\n\t // Check token and username\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t if (!_oauthData.isAuthenticated && _oauthData.userName && !salteAuth._renewActive) {\n\t // id_token is expired or not present\n\t salteAuth._renewActive = true;\n\t salteAuth.acquireToken(salteAuth.config.loginResource, function (error, tokenOut) {\n\t salteAuth._renewActive = false;\n\t if (error) {\n\t $rootScope.$broadcast('salte-auth:loginFailure', 'auto renew failure');\n\t } else if (tokenOut) {\n\t _oauthData.isAuthenticated = true;\n\t }\n\t });\n\t }\n\t }\n\t\n\t $timeout(function () {\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t $rootScope.userInfo = _oauthData;\n\t }, 1);\n\t };\n\t\n\t var loginHandler = function loginHandler() {\n\t salteAuth.info('Login event for:' + $location.$$url);\n\t if (salteAuth.config && salteAuth.config.localLoginUrl) {\n\t $location.path(salteAuth.config.localLoginUrl);\n\t } else {\n\t // directly start login flow\n\t salteAuth.info('Start login at:' + window.location.href);\n\t $rootScope.$broadcast('salte-auth:loginRedirect');\n\t salteAuth.login($location.absUrl());\n\t }\n\t };\n\t\n\t function isADLoginRequired(route, global) {\n\t return global.requireAuthentication ? route.requireAuthentication !== false : Boolean(route.requireAuthentication);\n\t }\n\t\n\t function isAnonymousEndpoint(url) {\n\t if (salteAuth.config && salteAuth.config.anonymousEndpoints) {\n\t for (var i = 0; i < salteAuth.config.anonymousEndpoints.length; i++) {\n\t if (url.indexOf(salteAuth.config.anonymousEndpoints[i]) > -1) {\n\t return true;\n\t }\n\t }\n\t }\n\t return false;\n\t }\n\t\n\t function getStates(toState) {\n\t var state = null;\n\t var states = [];\n\t if (toState.hasOwnProperty('parent')) {\n\t state = toState;\n\t while (state) {\n\t states.unshift(state);\n\t state = $injector.get('$state').get(state.parent);\n\t }\n\t } else {\n\t var stateNames = toState.name.split('.');\n\t for (var i = 0, stateName = stateNames[0]; i < stateNames.length; i++) {\n\t state = $injector.get('$state').get(stateName);\n\t if (state) {\n\t states.push(state);\n\t }\n\t stateName += '.' + stateNames[i + 1];\n\t }\n\t }\n\t return states;\n\t }\n\t\n\t var routeChangeHandler = function routeChangeHandler(e, nextRoute) {\n\t if (nextRoute && nextRoute.$$route) {\n\t if (isADLoginRequired(nextRoute.$$route, salteAuth.config)) {\n\t if (!_oauthData.isAuthenticated) {\n\t if (!salteAuth._renewActive && !salteAuth.loginInProgress()) {\n\t salteAuth.info('Route change event for:' + $location.$$url);\n\t loginHandler();\n\t }\n\t }\n\t } else {\n\t var nextRouteUrl = void 0;\n\t if (typeof nextRoute.$$route.templateUrl === 'function') {\n\t nextRouteUrl = nextRoute.$$route.templateUrl(nextRoute.params);\n\t } else {\n\t nextRouteUrl = nextRoute.$$route.templateUrl;\n\t }\n\t\n\t if (nextRouteUrl && !isAnonymousEndpoint(nextRouteUrl)) {\n\t salteAuth.config.anonymousEndpoints.push(nextRouteUrl);\n\t }\n\t }\n\t }\n\t };\n\t\n\t var stateChangeHandler = function stateChangeHandler(e, toState, toParams, fromState, fromParams) {\n\t // jshint ignore:line\n\t if (toState) {\n\t var states = getStates(toState);\n\t var state = null;\n\t for (var i = 0; i < states.length; i++) {\n\t state = states[i];\n\t if (isADLoginRequired(state, salteAuth.config)) {\n\t if (!_oauthData.isAuthenticated) {\n\t if (!salteAuth._renewActive && !salteAuth.loginInProgress()) {\n\t salteAuth.info('State change event for:' + $location.$$url);\n\t loginHandler();\n\t }\n\t }\n\t } else if (state.templateUrl) {\n\t var nextStateUrl = void 0;\n\t if (typeof state.templateUrl === 'function') {\n\t nextStateUrl = state.templateUrl(toParams);\n\t } else {\n\t nextStateUrl = state.templateUrl;\n\t }\n\t if (nextStateUrl && !isAnonymousEndpoint(nextStateUrl)) {\n\t salteAuth.config.anonymousEndpoints.push(nextStateUrl);\n\t }\n\t }\n\t }\n\t }\n\t };\n\t\n\t var stateChangeErrorHandler = function stateChangeErrorHandler(event, toState, toParams, fromState, fromParams, error) {\n\t salteAuth.verbose('State change error occured. Error: ' + error);\n\t\n\t if (error && error.data) {\n\t salteAuth.info('Setting defaultPrevented to true if state change error occured because the request was rejected. Error: ' + error.data);\n\t event.preventDefault();\n\t }\n\t };\n\t\n\t // Route change event tracking to receive fragment and also auto renew tokens\n\t $rootScope.$on('$routeChangeStart', routeChangeHandler);\n\t\n\t $rootScope.$on('$stateChangeStart', stateChangeHandler);\n\t\n\t $rootScope.$on('$locationChangeStart', locationChangeHandler);\n\t\n\t $rootScope.$on('$stateChangeError', stateChangeErrorHandler);\n\t\n\t updateDataFromCache(salteAuth.config.loginResource);\n\t $rootScope.userInfo = _oauthData;\n\t\n\t return {\n\t // public methods will be here that are accessible from Controller\n\t config: salteAuth.config,\n\t login: function login() {\n\t loginHandler();\n\t },\n\t loginInProgress: function loginInProgress() {\n\t return salteAuth.loginInProgress();\n\t },\n\t logOut: function logOut() {\n\t salteAuth.logOut();\n\t // call signout related method\n\t },\n\t getCachedToken: function getCachedToken(resource) {\n\t return salteAuth.getCachedToken(resource);\n\t },\n\t userInfo: _oauthData,\n\t acquireToken: function acquireToken(resource) {\n\t // automated token request call\n\t var deferred = $q.defer();\n\t salteAuth._renewActive = true;\n\t salteAuth.acquireToken(resource, function (error, tokenOut) {\n\t salteAuth._renewActive = false;\n\t if (error) {\n\t salteAuth.error('Error when acquiring token for resource: ' + resource, error);\n\t deferred.reject(error);\n\t } else {\n\t deferred.resolve(tokenOut);\n\t }\n\t });\n\t\n\t return deferred.promise;\n\t },\n\t getUser: function getUser() {\n\t var deferred = $q.defer();\n\t salteAuth.getUser(function (error, user) {\n\t if (error) {\n\t salteAuth.error('Error when getting user', error);\n\t deferred.reject(error);\n\t } else {\n\t deferred.resolve(user);\n\t }\n\t });\n\t\n\t return deferred.promise;\n\t },\n\t getResourceForEndpoint: function getResourceForEndpoint(endpoint) {\n\t return salteAuth.getResourceForEndpoint(endpoint);\n\t },\n\t clearCache: function clearCache() {\n\t salteAuth.clearCache();\n\t },\n\t clearCacheForResource: function clearCacheForResource(resource) {\n\t salteAuth.clearCacheForResource(resource);\n\t },\n\t info: function info(message) {\n\t salteAuth.info(message);\n\t },\n\t verbose: function verbose(message) {\n\t salteAuth.verbose(message);\n\t },\n\t salteAuth: salteAuth\n\t };\n\t };\n\t this.$get.$inject = [\"$rootScope\", \"$window\", \"$q\", \"$location\", \"$timeout\", \"$injector\"];\n\t};\n\t\n\tvar _salteAuth = __webpack_require__(4);\n\n\tvar _salteAuth2 = _interopRequireDefault(_salteAuth);\n\n\tfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\tmodule.exports = __WEBPACK_EXTERNAL_MODULE_3__;\n\n/***/ },\n/* 4 */\n/***/ function(module, exports) {\n\n\tmodule.exports = __WEBPACK_EXTERNAL_MODULE_4__;\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** salte-auth-angular.js\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap 611479b3a63a134f7e4e\n **/","import angular from 'angular';\nimport ProtectedResourceInterceptor from './protected-resource-interceptor.factory.js';\nimport salteAuthService from './salte-auth.provider.js';\n\nconst module = angular.module('salte.auth-angular', []);\n\nmodule.factory('ProtectedResourceInterceptor', ProtectedResourceInterceptor);\nmodule.provider('salteAuthService', salteAuthService);\n\nexport default module.name;\n\n\n\n/** WEBPACK FOOTER **\n ** ./salte-auth-angular.module.js\n **/","/* @ngInject */\nexport default function ProtectedResourceInterceptor(salteAuthService, $q, $rootScope) {\n return {\n request: function(config) {\n if (config) {\n config.headers = config.headers || {};\n let resource = salteAuthService.getResourceForEndpoint(config.url);\n salteAuthService.verbose('Url: ' + config.url + ' maps to resource: ' + resource);\n\n if (resource === null) {\n return config;\n }\n\n let tokenStored = salteAuthService.getCachedToken(resource);\n if (tokenStored) {\n salteAuthService.info('Token is available for this url ' + config.url);\n // check endpoint mapping if provided\n config.headers.Authorization = 'Bearer ' + tokenStored;\n return config;\n }\n\n // Cancel request if login is starting\n let delayedRequest;\n if (salteAuthService.loginInProgress()) {\n if (salteAuthService.config.popUp) {\n salteAuthService.info('Url: ' + config.url + ' will be loaded after login is successful');\n delayedRequest = $q.defer();\n $rootScope.$on('salte-auth:loginSuccess', function(event, token) {\n if (token) {\n salteAuthService.info('Login completed, sending request for ' + config.url);\n config.headers.Authorization = 'Bearer ' + tokenStored;\n delayedRequest.resolve(config);\n }\n });\n return delayedRequest.promise;\n }\n\n salteAuthService.info('login is in progress.');\n config.data = 'login in progress, cancelling the request for ' + config.url;\n return $q.reject(config);\n }\n\n // delayed request to return after iframe completes\n delayedRequest = $q.defer();\n salteAuthService.acquireToken(resource).then(function(token) {\n salteAuthService.verbose('Token is available');\n config.headers.Authorization = 'Bearer ' + token;\n delayedRequest.resolve(config);\n }, function(err) {\n config.data = err;\n delayedRequest.reject(config);\n });\n\n return delayedRequest.promise;\n }\n },\n responseError: function(rejection) {\n salteAuthService.info('Getting error in the response.');\n if (rejection) {\n if (rejection.status === 401) {\n let resource = salteAuthService.getResourceForEndpoint(rejection.config.url);\n salteAuthService.clearCacheForResource(resource);\n $rootScope.$broadcast('salte-auth:notAuthorized', rejection, resource);\n } else {\n $rootScope.$broadcast('salte-auth:errorResponse', rejection);\n }\n return $q.reject(rejection);\n }\n }\n };\n}\n\n\n\n/** WEBPACK FOOTER **\n ** ./protected-resource-interceptor.factory.js\n **/","import SalteAuth from 'salte-auth';\n\nexport default function() {\n let salteAuth = null;\n let _oauthData = {\n isAuthenticated: false,\n userName: '',\n loginError: '',\n profile: ''\n };\n\n let updateDataFromCache = function(resource) {\n // only cache lookup here to not interrupt with events\n let token = salteAuth.getCachedToken(resource);\n _oauthData.isAuthenticated = token !== null && token.length > 0;\n let user = salteAuth.getCachedUser() || {\n userName: ''\n };\n _oauthData.userName = user.userName;\n _oauthData.profile = user.profile;\n _oauthData.loginError = salteAuth.getLoginError();\n };\n\n this.init = function(configOptions, httpProvider) {\n if (configOptions) {\n // redirect and logout_redirect are set to current location by default\n let existingHash = window.location.hash;\n let pathDefault = window.location.href;\n if (existingHash) {\n pathDefault = pathDefault.replace(existingHash, '');\n }\n configOptions.redirectUri = configOptions.redirectUri || pathDefault;\n configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;\n configOptions.isAngular = true;\n\n if (httpProvider && httpProvider.interceptors) {\n httpProvider.interceptors.push('ProtectedResourceInterceptor');\n }\n\n // create instance with given config\n salteAuth = new SalteAuth(configOptions);\n } else {\n throw new Error('You must set configOptions, when calling init');\n }\n\n // loginResource is used to set authenticated status\n updateDataFromCache(salteAuth.config.loginResource);\n };\n\n /* @ngInject */\n this.$get = function SalteAuthService($rootScope, $window, $q, $location, $timeout, $injector) {\n let locationChangeHandler = function(event, newUrl, oldUrl) {\n salteAuth.verbose('Location change event from ' + oldUrl + ' to ' + newUrl);\n let hash = $window.location.hash;\n let search = $window.location.search;\n\n if (salteAuth.isCallback(hash, search)) {\n // callback can come from login or iframe request\n salteAuth.verbose('Processing Callback, Hash: ' + hash + '; Search String: ' + search);\n let requestInfo = salteAuth.getRequestInfo(hash, search);\n salteAuth.saveTokenFromHash(requestInfo);\n\n // Return to callback if it is sent from iframe\n if (requestInfo.stateMatch) {\n if (requestInfo.requestType === salteAuth.REQUEST_TYPE.RENEW_TOKEN) {\n let callback = $window.parent.AuthenticationContext.callBackMappedToRenewStates[requestInfo.stateResponse];\n // since this is a token renewal request in iFrame, we don't need to proceed with the location change.\n event.preventDefault();\n\n // Call within the same context without full page redirect keeps the callback\n if (callback && typeof callback === 'function') {\n // id_token or access_token can be renewed\n if (requestInfo.parameters.access_token) {\n callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.access_token);\n return;\n } else if (requestInfo.parameters.id_token) {\n callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.id_token);\n return;\n } else if (requestInfo.parameters.error) {\n callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null);\n return;\n }\n }\n } else if (requestInfo.requestType === salteAuth.REQUEST_TYPE.LOGIN) {\n // normal full login redirect happened on the page\n updateDataFromCache(salteAuth.config.loginResource);\n if (_oauthData.userName) {\n $timeout(function() {\n // id_token is added as token for the app\n updateDataFromCache(salteAuth.config.loginResource);\n $rootScope.userInfo = _oauthData;\n }, 1);\n\n $rootScope.$broadcast('salte-auth:loginSuccess', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.IDTOKEN));\n } else {\n $rootScope.$broadcast('salte-auth:loginFailure', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION));\n }\n\n if (salteAuth.callback && typeof salteAuth.callback === 'function') {\n salteAuth.callback(salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION), salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.IDTOKEN));\n }\n\n // redirect to login start page\n if (!salteAuth.popUp) {\n let loginStartPage = salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.LOGIN_REQUEST);\n if (typeof loginStartPage !== 'undefined' && loginStartPage && loginStartPage.length !== 0) {\n // prevent the current location change and redirect the user back to the login start page\n salteAuth.verbose('Redirecting to start page: ' + loginStartPage);\n if (!$location.$$html5 && loginStartPage.indexOf('#') > -1) {\n $location.url(loginStartPage.substring(loginStartPage.indexOf('#') + 1));\n }\n $window.location = loginStartPage;\n }\n } else {\n event.preventDefault();\n }\n }\n } else {\n // state did not match, broadcast an error\n $rootScope.$broadcast('salte-auth:stateMismatch', salteAuth._getItem(salteAuth.CONSTANTS.STORAGE.ERROR_DESCRIPTION));\n }\n } else {\n // No callback. App resumes after closing or moving to new page.\n // Check token and username\n updateDataFromCache(salteAuth.config.loginResource);\n if (!_oauthData.isAuthenticated && _oauthData.userName && !salteAuth._renewActive) {\n // id_token is expired or not present\n salteAuth._renewActive = true;\n salteAuth.acquireToken(salteAuth.config.loginResource, function(error, tokenOut) {\n salteAuth._renewActive = false;\n if (error) {\n $rootScope.$broadcast('salte-auth:loginFailure', 'auto renew failure');\n } else if (tokenOut) {\n _oauthData.isAuthenticated = true;\n }\n });\n }\n }\n\n $timeout(function() {\n updateDataFromCache(salteAuth.config.loginResource);\n $rootScope.userInfo = _oauthData;\n }, 1);\n };\n\n let loginHandler = function() {\n salteAuth.info('Login event for:' + $location.$$url);\n if (salteAuth.config && salteAuth.config.localLoginUrl) {\n $location.path(salteAuth.config.localLoginUrl);\n } else {\n // directly start login flow\n salteAuth.info('Start login at:' + window.location.href);\n $rootScope.$broadcast('salte-auth:loginRedirect');\n salteAuth.login($location.absUrl());\n }\n };\n\n function isADLoginRequired(route, global) {\n return global.requireAuthentication ? route.requireAuthentication !== false : Boolean(route.requireAuthentication);\n }\n\n function isAnonymousEndpoint(url) {\n if (salteAuth.config && salteAuth.config.anonymousEndpoints) {\n for (let i = 0; i < salteAuth.config.anonymousEndpoints.length; i++) {\n if (url.indexOf(salteAuth.config.anonymousEndpoints[i]) > -1) {\n return true;\n }\n }\n }\n return false;\n }\n\n function getStates(toState) {\n let state = null;\n let states = [];\n if (toState.hasOwnProperty('parent')) {\n state = toState;\n while (state) {\n states.unshift(state);\n state = $injector.get('$state').get(state.parent);\n }\n } else {\n let stateNames = toState.name.split('.');\n for (let i = 0, stateName = stateNames[0]; i < stateNames.length; i++) {\n state = $injector.get('$state').get(stateName);\n if (state) {\n states.push(state);\n }\n stateName += '.' + stateNames[i + 1];\n }\n }\n return states;\n }\n\n let routeChangeHandler = function(e, nextRoute) {\n if (nextRoute && nextRoute.$$route) {\n if (isADLoginRequired(nextRoute.$$route, salteAuth.config)) {\n if (!_oauthData.isAuthenticated) {\n if (!salteAuth._renewActive && !salteAuth.loginInProgress()) {\n salteAuth.info('Route change event for:' + $location.$$url);\n loginHandler();\n }\n }\n } else {\n let nextRouteUrl;\n if (typeof nextRoute.$$route.templateUrl === 'function') {\n nextRouteUrl = nextRoute.$$route.templateUrl(nextRoute.params);\n } else {\n nextRouteUrl = nextRoute.$$route.templateUrl;\n }\n\n if (nextRouteUrl && !isAnonymousEndpoint(nextRouteUrl)) {\n salteAuth.config.anonymousEndpoints.push(nextRouteUrl);\n }\n }\n }\n };\n\n let stateChangeHandler = function(e, toState, toParams, fromState, fromParams) { // jshint ignore:line\n if (toState) {\n let states = getStates(toState);\n let state = null;\n for (let i = 0; i < states.length; i++) {\n state = states[i];\n if (isADLoginRequired(state, salteAuth.config)) {\n if (!_oauthData.isAuthenticated) {\n if (!salteAuth._renewActive && !salteAuth.loginInProgress()) {\n salteAuth.info('State change event for:' + $location.$$url);\n loginHandler();\n }\n }\n } else if (state.templateUrl) {\n let nextStateUrl;\n if (typeof state.templateUrl === 'function') {\n nextStateUrl = state.templateUrl(toParams);\n } else {\n nextStateUrl = state.templateUrl;\n }\n if (nextStateUrl && !isAnonymousEndpoint(nextStateUrl)) {\n salteAuth.config.anonymousEndpoints.push(nextStateUrl);\n }\n }\n }\n }\n };\n\n let stateChangeErrorHandler = function(event, toState, toParams, fromState, fromParams, error) {\n salteAuth.verbose('State change error occured. Error: ' + error);\n\n if (error && error.data) {\n salteAuth.info('Setting defaultPrevented to true if state change error occured because the request was rejected. Error: ' + error.data);\n event.preventDefault();\n }\n };\n\n // Route change event tracking to receive fragment and also auto renew tokens\n $rootScope.$on('$routeChangeStart', routeChangeHandler);\n\n $rootScope.$on('$stateChangeStart', stateChangeHandler);\n\n $rootScope.$on('$locationChangeStart', locationChangeHandler);\n\n $rootScope.$on('$stateChangeError', stateChangeErrorHandler);\n\n updateDataFromCache(salteAuth.config.loginResource);\n $rootScope.userInfo = _oauthData;\n\n return {\n // public methods will be here that are accessible from Controller\n config: salteAuth.config,\n login: function() {\n loginHandler();\n },\n loginInProgress: function() {\n return salteAuth.loginInProgress();\n },\n logOut: function() {\n salteAuth.logOut();\n // call signout related method\n },\n getCachedToken: function(resource) {\n return salteAuth.getCachedToken(resource);\n },\n userInfo: _oauthData,\n acquireToken: function(resource) {\n // automated token request call\n let deferred = $q.defer();\n salteAuth._renewActive = true;\n salteAuth.acquireToken(resource, function(error, tokenOut) {\n salteAuth._renewActive = false;\n if (error) {\n salteAuth.error('Error when acquiring token for resource: ' + resource, error);\n deferred.reject(error);\n } else {\n deferred.resolve(tokenOut);\n }\n });\n\n return deferred.promise;\n },\n getUser: function() {\n let deferred = $q.defer();\n salteAuth.getUser(function(error, user) {\n if (error) {\n salteAuth.error('Error when getting user', error);\n deferred.reject(error);\n } else {\n deferred.resolve(user);\n }\n });\n\n return deferred.promise;\n },\n getResourceForEndpoint: function(endpoint) {\n return salteAuth.getResourceForEndpoint(endpoint);\n },\n clearCache: function() {\n salteAuth.clearCache();\n },\n clearCacheForResource: function(resource) {\n salteAuth.clearCacheForResource(resource);\n },\n info: function(message) {\n salteAuth.info(message);\n },\n verbose: function(message) {\n salteAuth.verbose(message);\n },\n salteAuth: salteAuth\n };\n };\n}\n\n\n\n/** WEBPACK FOOTER **\n ** ./salte-auth.provider.js\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_3__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"root\":\"angular\",\"commonjs2\":\"angular\",\"commonjs\":\"angular\",\"amd\":\"angular\"}\n ** module id = 3\n ** module chunks = 0\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_4__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"root\":\"salte-auth\",\"commonjs2\":\"salte-auth\",\"commonjs\":\"salte-auth\",\"amd\":\"salte-auth\"}\n ** module id = 4\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/package.json b/package.json index 363d7a5..9774f31 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salte-auth-angular", - "version": "0.0.0-semantically-released.0", + "version": "1.0.8", "main": "dist/salte-auth-angular.js", "description": "Provides OpenID Connect support to AngularJS applications through the addition of a simple configuration.", "homepage": "https://github.com/salte-io/salte-auth-angular", @@ -73,4 +73,4 @@ "path": "./node_modules/cz-conventional-changelog" } } -} +} \ No newline at end of file