forked from Esri/arcgis-js-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IdentityManagerBase.js
25 lines (24 loc) · 29.1 KB
/
IdentityManagerBase.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// COPYRIGHT © 201 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/3.30/esri/copyright.txt for details.
define(["dojo/_base/declare","dojo/_base/config","dojo/_base/lang","dojo/_base/array","dojo/_base/Deferred","dojo/_base/json","dojo/_base/url","dojo/sniff","dojo/cookie","dojo/io-query","dojo/on","dojo/regexp","./kernel","./config","./lang","./ServerInfo","./urlUtils","./deferredUtils","./request","./Evented","./OAuthCredential","./arcgis/OAuthInfo"],function(e,r,t,s,i,n,o,a,l,c,h,u,d,f,_,g,v,p,m,S,I,w){var k,U={},A=function(e){var r=new o(e.owningSystemUrl).host,t=new o(e.server).host,s=/.+\.arcgis\.com$/i;return s.test(r)&&s.test(t)},T=function(e,r){return!!(A(e)&&r&&s.some(r,function(r){return r.test(e.server)}))},b=e(S,{declaredClass:"esri.IdentityManagerBase",constructor:function(){this._portalConfig=t.getObject("esriGeowConfig"),this.serverInfos=[],this.oAuthInfos=[],this.credentials=[],this._soReqs=[],this._xoReqs=[],this._portals=[],this._getOAuthHash(),h(window,"pageshow",t.hitch(this,this._pageShowHandler))},defaultOAuthInfo:null,defaultTokenValidity:60,tokenValidity:null,signInPage:null,useSignInPage:!0,normalizeWebTierAuth:!1,_busy:null,_rejectOnPersistedPageShow:!1,_oAuthHash:null,_gwTokenUrl:"/sharing/generateToken",_agsRest:"/rest/services",_agsPortal:/\/sharing(\/|$)/i,_agsAdmin:/(https?:\/\/[^\/]+\/[^\/]+)\/admin\/?(\/.*)?$/i,_adminSvcs:/\/rest\/admin\/services(\/|$)/i,_agolSuffix:".arcgis.com",_gwDomains:[{regex:/https?:\/\/www\.arcgis\.com/i,tokenServiceUrl:"https://www.arcgis.com/sharing/generateToken"},{regex:/https?:\/\/dev\.arcgis\.com/i,tokenServiceUrl:"https://dev.arcgis.com/sharing/generateToken"},{regex:/https?:\/\/.*dev[^.]*\.arcgis\.com/i,tokenServiceUrl:"https://devext.arcgis.com/sharing/generateToken"},{regex:/https?:\/\/.*qa[^.]*\.arcgis\.com/i,tokenServiceUrl:"https://qaext.arcgis.com/sharing/generateToken"},{regex:/https?:\/\/.*\.arcgis\.com/i,tokenServiceUrl:"https://www.arcgis.com/sharing/generateToken"}],_legacyFed:[],_regexSDirUrl:/http.+\/rest\/services\/?/gi,_regexServerType:/(\/(MapServer|GeocodeServer|GPServer|GeometryServer|ImageServer|NAServer|FeatureServer|GeoDataServer|GlobeServer|MobileServer|GeoenrichmentServer|VectorTileServer)).*/gi,_gwUser:/http.+\/users\/([^\/]+)\/?.*/i,_gwItem:/http.+\/items\/([^\/]+)\/?.*/i,_gwGroup:/http.+\/groups\/([^\/]+)\/?.*/i,_errorCodes:[499,498,403,401],_rePortalTokenSvc:/\/sharing(\/rest)?\/generatetoken/i,_publicUrls:[/\/arcgis\/tokens/i,/\/sharing(\/rest)?\/generatetoken/i,/\/rest\/info/i],_createDefaultOAuthInfo:!0,_hasTestedIfAppIsOnPortal:!1,registerServers:function(e){var r=this.serverInfos;r?(e=s.filter(e,function(e){return!this.findServerInfo(e.server)},this),this.serverInfos=r.concat(e)):this.serverInfos=e,s.forEach(e,function(e){if(e.owningSystemUrl&&this._portals.push(e.owningSystemUrl),e.hasPortal){this._portals.push(e.server);var r=f.defaults.io.corsEnabledServers,t=this._getOrigin(e.tokenServiceUrl);v.canUseXhr(e.server)||r.push(e.server.replace(/^https?:\/\//i,"")),v.canUseXhr(t)||r.push(t.replace(/^https?:\/\//i,""))}},this)},registerOAuthInfos:function(e){var r=this.oAuthInfos;r?(e=s.filter(e,function(e){return!this.findOAuthInfo(e.portalUrl)},this),this.oAuthInfos=r.concat(e)):this.oAuthInfos=e},registerToken:function(e){e=_.mixin({},e);var r,s=this._sanitizeUrl(e.server),i=this.findServerInfo(s),n=!0;i||(i=new g,i.server=this._getServerInstanceRoot(s),i.tokenServiceUrl=this._getTokenSvcUrl(s),i.hasPortal=!0,this.registerServers([i])),r=this.findCredential(s,e.userId),r?(delete e.server,t.mixin(r,e),n=!1):(r=new k({userId:e.userId,server:i.server,token:e.token,expires:e.expires,ssl:e.ssl,scope:this._isServerRsrc(s)?"server":"portal"}),r.resources=[s],this.credentials.push(r)),r.onTokenChange(!1),n||r.refreshServerTokens()},toJson:function(){return _.fixJson({serverInfos:s.map(this.serverInfos,function(e){return e.toJson()}),oAuthInfos:s.map(this.oAuthInfos,function(e){return e.toJson()}),credentials:s.map(this.credentials,function(e){return e.toJson()})})},initialize:function(e){if(e){t.isString(e)&&(e=n.fromJson(e));var r=e.serverInfos,i=e.oAuthInfos,o=e.credentials;if(r){var a=[];s.forEach(r,function(e){e.server&&e.tokenServiceUrl&&a.push(e.declaredClass?e:new g(e))}),a.length&&this.registerServers(a)}if(i){var l=[];s.forEach(i,function(e){e.appId&&l.push(e.declaredClass?e:new w(e))}),l.length&&this.registerOAuthInfos(l)}o&&s.forEach(o,function(e){e.userId&&e.server&&e.token&&e.expires&&e.expires>(new Date).getTime()&&(e=e.declaredClass?e:new k(e),e.onTokenChange(),this.credentials.push(e))},this)}},findServerInfo:function(e){var r;return e=this._sanitizeUrl(e),s.some(this.serverInfos,function(t){return this._hasSameServerInstance(t.server,e)&&(r=t),!!r},this),r},findOAuthInfo:function(e){var r;return e=this._sanitizeUrl(e),s.some(this.oAuthInfos,function(t){return this._hasSameServerInstance(t.portalUrl,e)&&(r=t),!!r},this),r},findCredential:function(e,r){var t,i;return e=this._sanitizeUrl(e),i=this._isServerRsrc(e)?"server":"portal",r?s.some(this.credentials,function(s){return this._hasSameServerInstance(s.server,e)&&r===s.userId&&s.scope===i&&(t=s),!!t},this):s.some(this.credentials,function(r){return this._hasSameServerInstance(r.server,e)&&-1!==this._getIdenticalSvcIdx(e,r)&&r.scope===i&&(t=r),!!t},this),t},getCredential:function(e,s){var n,o,a=!0;_.isDefined(s)&&(t.isObject(s)?(n=!!s.token,o=s.error,a=!1!==s.prompt):n=s),e=this._sanitizeUrl(e);var c,h=new i(p._dfdCanceller),u=this._isAdminResource(e),d=n&&this._doPortalSignIn(e)?this._getEsriAuthCookie():null,f=n?this.findCredential(e):null;if(f&&o&&498===o.code)f.destroy(),d&&d.token===s.token&&l("esri_auth",null,{expires:-1,path:"/",domain:document.domain});else if(d||f){var v=d&&d.email||f&&f.userId;return c=new Error("You are currently signed in as: '"+v+"'. You do not have access to this resource: "+e),c.code="IdentityManagerBase.1",c.httpCode=o&&o.httpCode,c.messageCode=o?o.messageCode:null,c.subcode=o?o.subcode:null,c.details=o?o.details:null,c.log=!!r.isDebug,h.errback(c),h}var m=this._findCredential(e,s);if(m)return h.callback(m),h;var S=this.findServerInfo(e);if(S)!S.hasServer&&this._isServerRsrc(e)&&(S._restInfoDfd=this._getTokenSvcUrl(e,!0),S.hasServer=!0);else{var I=this._getTokenSvcUrl(e);if(!I)return c=new Error("Unknown resource - could not find token service endpoint."),c.code="IdentityManagerBase.2",c.log=!!r.isDebug,h.errback(c),h;S=new g,S.server=this._getServerInstanceRoot(e),t.isString(I)?(S.tokenServiceUrl=I,S.hasPortal=!0):(S._restInfoDfd=I,S.hasServer=!0),this.registerServers([S])}return a&&S.hasPortal&&void 0===S._selfReq&&!this._findOAuthInfo(e)&&(S._selfReq={owningTenant:s&&s.owningTenant,selfDfd:this._getPortalSelf(S.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),e)}),this._enqueue(e,S,s,h,u)},getResourceName:function(e){return this._isRESTService(e)?e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(e)&&e.replace(this._gwUser,"$1")||this._gwItem.test(e)&&e.replace(this._gwItem,"$1")||this._gwGroup.test(e)&&e.replace(this._gwGroup,"$1")||""},generateToken:function(e,s,i){var n,a,l,c,h,u,f,_,g,p,S=this._rePortalTokenSvc.test(e.tokenServiceUrl),I=new o(window.location.href.toLowerCase()),w=this._getEsriAuthCookie(),k=!s,A=e.shortLivedTokenValidity;s&&(p=d.id.tokenValidity||A||d.id.defaultTokenValidity)>A&&(p=A),i&&(n=i.isAdmin,a=i.serverUrl,l=i.token,u=i.ssl,e.customParameters=i.customParameters),n?c=e.adminTokenServiceUrl:(c=e.tokenServiceUrl,h=new o(c.toLowerCase()),w&&(g=w.auth_tier,g=g&&g.toLowerCase()),("web"===g||e.webTierAuth)&&i&&i.serverUrl&&!u&&"http"===I.scheme&&(v.hasSameOrigin(I.uri,c,!0)||"https"===h.scheme&&I.host===h.host&&"7080"===I.port&&"7443"===h.port)&&(c=c.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),k&&S&&(c=c.replace(/\/rest/i,""))),f=t.mixin({url:c,content:t.mixin({request:"getToken",username:s&&s.username,password:s&&s.password,serverUrl:a,token:l,expiration:p,referer:n||S?window.location.host:null,client:n?"referer":null,f:"json"},e.customParameters),handleAs:"json",callbackParamName:k?"callback":void 0},i&&i.ioArgs),_={usePost:!k,disableIdentityLookup:!0,useProxy:this._useProxy(e,i)},S||(f.withCredentials=!1);var T=m(f,_);return T.addCallback(function(t){if(!t||!t.token){var i=new Error("Unable to generate token");return i.code="IdentityManagerBase.3",i.log=!!r.isDebug,i}var n=e.server;return U[n]||(U[n]={}),s&&(U[n][s.username]=s.password),t.validity=p,t}),T.addErrback(function(e){}),T},isBusy:function(){return!!this._busy},checkSignInStatus:function(e){var r=new i;return this.checkAppAccess(e,"").then(function(e){r.resolve(e.credential)}).catch(function(e){r.reject(e)}),r},checkAppAccess:function(e,t,s){var i=this;return this.getCredential(e,{prompt:!1}).then(function(n){var o,a={f:"json"};if("portal"===n.scope)if(t&&(i._doPortalSignIn(e,!0)||s&&s.force))o=n.server+"/sharing/rest/oauth2/validateAppAccess",a.client_id=t;else{if(!n.token)return{credential:n};o=n.server+"/sharing/rest"}else{if(!n.token)return{credential:n};o=n.server+"/rest/services"}return n.token&&(a.token=n.token),m({url:o,content:a,callbackParamName:"callback"},{disableIdentityLookup:!0}).then(function(e){if(!1===e.valid){var s=new Error("You are currently signed in as: '"+n.userId+"'. You do not have access to this app: '"+t+"'.");throw s.code="IdentityManagerBase.1",s.log=!!r.isDebug,s}return{credential:n}}).catch(function(e){if("IdentityManagerBase.1"===e.code||400===e.code)throw e;if(498===e.code){n.destroy();var t=new Error("User is not signed in.");throw t.code="IdentityManagerBase.6",t.log=!!r.isDebug,t}return{credential:n}})})},setRedirectionHandler:function(e){this._redirectFunc=e},setProtocolErrorHandler:function(e){this._protocolFunc=e},signIn:function(){},oAuthSignIn:function(){},onCredentialCreate:function(){},onCredentialsDestroy:function(){},destroyCredentials:function(){if(this.credentials){var e=this.credentials.slice();s.forEach(e,function(e){e.destroy()})}this.onCredentialsDestroy()},_getOAuthHash:function(){var e=window.location.hash;if(e){"#"===e.charAt(0)&&(e=e.substring(1));var r=c.queryToObject(e),t=!1;r.access_token&&r.expires_in&&r.state&&r.hasOwnProperty("username")?(r.state=n.fromJson(r.state),this._oAuthHash=r,t=!0):r.error&&r.error_description&&(console.log("IdentityManager OAuth Error: ",r.error," - ",r.error_description),"access_denied"===r.error&&(t=!0)),t&&(!a("ie")||a("ie")>8)&&(window.location.hash="")}},_pageShowHandler:function(e){if(e.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow){var t=new Error("ABORTED");t.code="IdentityManager.2",t.log=!!r.isDebug,this._errbackFunc(t)}},_findCredential:function(e,r){var t,i,n,o,a=-1,l=r&&r.token,c=r&&r.resource,h=this._isServerRsrc(e)?"server":"portal",u=s.filter(this.credentials,function(r){return this._hasSameServerInstance(r.server,e)&&r.scope===h},this);if(e=c||e,u.length)if(1===u.length){if(t=u[0],o=this.findServerInfo(t.server),i=o&&o.owningSystemUrl,n=i&&this.findCredential(i,t.userId),a=this._getIdenticalSvcIdx(e,t),!l)return-1===a&&t.resources.push(e),this._addResource(e,n),t;-1!==a&&(t.resources.splice(a,1),this._removeResource(e,n))}else{var d,f;if(s.some(u,function(r){return-1!==(f=this._getIdenticalSvcIdx(e,r))&&(d=r,o=this.findServerInfo(d.server),i=o&&o.owningSystemUrl,n=i&&this.findCredential(i,d.userId),a=f,!0)},this),l)d&&(d.resources.splice(a,1),this._removeResource(e,n));else if(d)return this._addResource(e,n),d}},_findOAuthInfo:function(e){var r=this.findOAuthInfo(e);return r||s.some(this.oAuthInfos,function(t){return this._isIdProvider(t.portalUrl,e)&&(r=t),!!r},this),r},_addResource:function(e,r){r&&-1===this._getIdenticalSvcIdx(e,r)&&r.resources.push(e)},_removeResource:function(e,r){var t=-1;r&&(t=this._getIdenticalSvcIdx(e,r))>-1&&r.resources.splice(t,1)},_useProxy:function(e,r){return r&&r.isAdmin&&!v.hasSameOrigin(e.adminTokenServiceUrl,window.location.href)||!this._isPortalDomain(e.tokenServiceUrl)&&10.1==e.currentVersion&&!v.hasSameOrigin(e.tokenServiceUrl,window.location.href)},_getOrigin:function(e){var r=new o(e);return r.scheme+"://"+r.host+(_.isDefined(r.port)?":"+r.port:"")},_getServerInstanceRoot:function(e){var r=e.toLowerCase(),t=r.indexOf(this._agsRest);return-1===t&&this._isAdminResource(e)&&(t=this._agsAdmin.test(e)?e.replace(this._agsAdmin,"$1").length:e.search(this._adminSvcs)),-1===t&&(t=r.indexOf("/sharing")),-1===t&&"/"===r.substr(-1)&&(t=r.length-1),t>-1?e.substring(0,t):e},_hasSameServerInstance:function(e,r){return"/"===e.substr(-1)&&(e=e.slice(0,-1)),e=e.toLowerCase(),r=this._getServerInstanceRoot(r).toLowerCase(),e=this._normalizeAGOLorgDomain(e),r=this._normalizeAGOLorgDomain(r),e=e.substr(e.indexOf(":")),r=r.substr(r.indexOf(":")),e===r},_normalizeAGOLorgDomain:function(e){var r=/^https?:\/\/.+\.maps\.arcgis\.com/i,t=/^https?:\/\/.+\.mapsdevext\.arcgis\.com/i,s=/^https?:\/\/.+\.mapsqa\.arcgis\.com/i;return r.test(e)?e=e.replace(r,"https://www.arcgis.com"):t.test(e)?e=e.replace(t,"https://devext.arcgis.com"):s.test(e)&&(e=e.replace(s,"https://qaext.arcgis.com")),e},_sanitizeUrl:function(e){var r=(f.defaults.io.proxyUrl||"").toLowerCase(),t=r?e.toLowerCase().indexOf(r+"?"):-1;return-1!==t&&(e=e.substring(t+r.length+1)),e=v.normalize(e),v.urlToObject(e).path},_isRESTService:function(e){return e.indexOf(this._agsRest)>-1},_isAdminResource:function(e){return this._agsAdmin.test(e)||this._adminSvcs.test(e)},_isServerRsrc:function(e){return this._isRESTService(e)||this._isAdminResource(e)},_isIdenticalService:function(e,r){var t;if(this._isRESTService(e)&&this._isRESTService(r)){var s=this._getSuffix(e).toLowerCase(),i=this._getSuffix(r).toLowerCase();if(!(t=s===i)){var n=/(.*)\/(MapServer|FeatureServer).*/gi;t=s.replace(n,"$1")===i.replace(n,"$1")}}else this._isAdminResource(e)&&this._isAdminResource(r)?t=!0:this._isServerRsrc(e)||this._isServerRsrc(r)||!this._isPortalDomain(e)||(t=!0);return t},_isPortalDomain:function(e){e=e.toLowerCase();var r=new o(e).authority,i=this._portalConfig,n=-1!==r.indexOf(this._agolSuffix);if(!n&&i&&(n=this._hasSameServerInstance(this._getServerInstanceRoot(i.restBaseUrl),e)),!n){if(!this._arcgisUrl){var a=t.getObject("esri.arcgis.utils.arcgisUrl");a&&(this._arcgisUrl=new o(a).authority)}this._arcgisUrl&&(n=this._arcgisUrl.toLowerCase()===r)}return n||(n=s.some(this._portals,function(r){return this._hasSameServerInstance(r,e)},this)),n=n||this._agsPortal.test(e)},_isIdProvider:function(e,r){var t=-1,i=-1;s.forEach(this._gwDomains,function(s,n){-1===t&&s.regex.test(e)&&(t=n),-1===i&&s.regex.test(r)&&(i=n)});var n=!1;if(t>-1&&i>-1&&(0===t||4===t?0!==i&&4!==i||(n=!0):1===t?1!==i&&2!==i||(n=!0):2===t?2===i&&(n=!0):3===t&&3===i&&(n=!0)),!n){var o=this.findServerInfo(r),a=o&&o.owningSystemUrl;a&&A(o)&&this._isPortalDomain(a)&&this._isIdProvider(e,a)&&(n=!0)}return n},_isPublic:function(e){return e=this._sanitizeUrl(e),s.some(this._publicUrls,function(r){return r.test(e)})},_getIdenticalSvcIdx:function(e,r){var t=-1;return s.some(r.resources,function(r,s){return!!this._isIdenticalService(e,r)&&(t=s,!0)},this),t},_getSuffix:function(e){return e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"$1")},_getTokenSvcUrl:function(e){var r,t,i;if(this._isRESTService(e)||this._isAdminResource(e)){var n=this._getServerInstanceRoot(e);return r=n+"/admin/generateToken",e=n+"/rest/info",t=m({url:e,content:{f:"json"},handleAs:"json",callbackParamName:"callback"}),t.adminUrl_=r,t}if(this._isPortalDomain(e)){var a="";if(s.some(this._gwDomains,function(r){return r.regex.test(e)&&(a=r.tokenServiceUrl),!!a}),a||s.some(this._portals,function(r){return this._hasSameServerInstance(r,e)&&(a=r+this._gwTokenUrl),!!a},this),a||-1!==(i=e.toLowerCase().indexOf("/sharing"))&&(a=e.substring(0,i)+this._gwTokenUrl),a||(a=this._getOrigin(e)+this._gwTokenUrl),a){var l=new o(e).port;/^http:\/\//i.test(e)&&"7080"===l&&(a=a.replace(/:7080/i,":7443")),a=a.replace(/http:/i,"https:")}return a}if(-1!==e.toLowerCase().indexOf("premium.arcgisonline.com"))return"https://premium.arcgisonline.com/server/tokens"},_getPortalSelf:function(e,r){return"https:"===window.location.protocol?e=e.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(r)&&(e=e.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),m({url:e,content:{f:"json"},handleAs:"json",callbackParamName:"callback"},{crossOrigin:!1,disableIdentityLookup:!0})},_hasPortalSession:function(){return!!this._getEsriAuthCookie()},_getEsriAuthCookie:function(){var e=null;if(l.isSupported()){var r,t=this._getAllCookies("esri_auth");for(r=0;r<t.length;r++){var s=n.fromJson(t[r]);if(s.portalApp){e=s;break}}}if(e){var i=null;e.expires&&("number"==typeof e.expires?i=e.expires:"string"==typeof e.expires&&(i=Date.parse(e.expires)),isNaN(i)&&(i=null),e.expires=i),i&&i<(new Date).getTime()&&(e=null)}return e},_getAllCookies:function(e){var r,t=[],s=document.cookie,i=s.match(new RegExp("(?:^|; )"+u.escapeString(e)+"=([^;]*)","g"));if(i)for(r=0;r<i.length;r++){var n=i[r],o=n.indexOf("=");o>-1&&(n=n.substring(o+1),t.push(decodeURIComponent(n)))}return t},_doPortalSignIn:function(e,r){if(l.isSupported()){var t=this._getEsriAuthCookie(),s=this._portalConfig,i=window.location.href,n=this.findServerInfo(e);if((r||this.useSignInPage)&&(s||this._isPortalDomain(i)||t)&&(n?n.hasPortal||n.owningSystemUrl&&this._isPortalDomain(n.owningSystemUrl):this._isPortalDomain(e))&&(this._isIdProvider(i,e)||s&&(this._hasSameServerInstance(this._getServerInstanceRoot(s.restBaseUrl),e)||this._isIdProvider(s.restBaseUrl,e))||v.hasSameOrigin(i,e,!0)))return!0}return!1},_canUsePortalSignInWorkflow:function(e){return this._doPortalSignIn(e)&&(window===window.top||this._hasPortalSession())},_checkProtocol:function(e,s,i,n){var o=!0,a=n?s.adminTokenServiceUrl:s.tokenServiceUrl;if(!(0!==t.trim(a).toLowerCase().indexOf("https:")||0===window.location.href.toLowerCase().indexOf("https:")||f.defaults.io.useCors&&(v.canUseXhr(a)||v.canUseXhr(v.getProxyUrl(!0).path))||(o=!!this._protocolFunc&&!!this._protocolFunc({resourceUrl:e,serverInfo:s})))){var l=new Error("Aborted the Sign-In process to avoid sending password over insecure connection.");l.code="IdentityManagerBase.4",l.log=!!r.isDebug,console.log(l.message),i(l)}return o},_enqueue:function(e,r,t,s,n,o){return s||(s=new i(p._dfdCanceller)),s.resUrl_=e,s.sinfo_=r,s.options_=t,s.admin_=n,s.refresh_=o,this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(e),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(s)):this._xoReqs.push(s):this._doSignIn(s),s},_doSignIn:function(e){this._busy=e,this._rejectOnPersistedPageShow=!1;var i=this,n=function(r){var t=e.options_&&e.options_.resource,n=e.resUrl_,o=e.refresh_,a=!1;-1===s.indexOf(i.credentials,r)&&(o&&-1!==s.indexOf(i.credentials,o)?(o.userId=r.userId,o.token=r.token,o.expires=r.expires,o.validity=r.validity,o.ssl=r.ssl,o.creationTime=r.creationTime,a=!0,r=o):i.credentials.push(r)),r.resources||(r.resources=[]),r.resources.push(t||n),r.scope=i._isServerRsrc(n)?"server":"portal",r.onTokenChange();var l=i._soReqs,c={};i._soReqs=[],s.forEach(l,function(e){if(!this._isIdenticalService(n,e.resUrl_)){var t=this._getSuffix(e.resUrl_);c[t]||(c[t]=!0,r.resources.push(e.resUrl_))}},i),e.callback(r),s.forEach(l,function(e){this._hasSameServerInstance(this._getServerInstanceRoot(n),e.resUrl_)?e.callback(r):this._soReqs.push(e)},i),i._busy=e.resUrl_=e.sinfo_=e.refresh_=null,a||i.onCredentialCreate({credential:r}),i._soReqs.length?i._doSignIn(i._soReqs.shift()):i._xoReqs.length&&i._doSignIn(i._xoReqs.shift())},o=function(r){e.errback(r),i._busy=e.resUrl_=e.sinfo_=e.refresh_=null,i._soReqs.length?i._doSignIn(i._soReqs.shift()):i._xoReqs.length&&i._doSignIn(i._xoReqs.shift())},a=function(t,s,a,l){var c,h,u=e.sinfo_,d=!e.options_||!1!==e.options_.prompt,f=u.hasPortal&&i._findOAuthInfo(e.resUrl_);if(i._canUsePortalSignInWorkflow(e.resUrl_)){var g=i._getEsriAuthCookie(),v=i._portalConfig;if(g){if(!u.webTierAuth){"web"===(g.auth_tier&&g.auth_tier.toLowerCase())&&(u.webTierAuth=!0)}return void n(new k({userId:g.email,server:u.server,token:u.webTierAuth?null:g.token,expires:g.expires}))}if(d){var p="",m=window.location.href;return p=i.signInPage?i.signInPage:v?v.baseUrl+v.signin:i._isIdProvider(m,e.resUrl_)?i._getOrigin(m)+"/home/signin.html":u.tokenServiceUrl.replace(i._rePortalTokenSvc,"")+"/home/signin.html",p=p.replace(/http:/i,"https:"),v&&!1===v.useSSL&&(p=p.replace(/https:/i,"http:")),void(0===m.toLowerCase().replace("https","http").indexOf(p.toLowerCase().replace("https","http"))?(h=new Error("Cannot redirect to Sign-In page from within Sign-In page. URL of the resource that triggered this workflow: "+e.resUrl_),h.code="IdentityManagerBase.5",h.log=!!r.isDebug,o(h)):(i._rejectOnPersistedPageShow=!0,i._redirectFunc?i._redirectFunc({signInPage:p,returnUrlParamName:"returnUrl",returnUrl:m,resourceUrl:e.resUrl_,serverInfo:u}):window.location=p+"?returnUrl="+window.escape(m)))}h=new Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!r.isDebug,o(h)}else if(t)n(new k({userId:t,server:u.server,token:a,expires:_.isDefined(l)?Number(l):null,ssl:!!s}));else if(f){var S=f._oAuthCred;if(!S){var w=new I(f,window.localStorage),U=new I(f,window.sessionStorage);w.isValid()&&U.isValid()?w.expires>U.expires?(S=w,U.destroy()):(S=U,w.destroy()):S=w.isValid()?w:U,f._oAuthCred=S}if(S.isValid())n(new k({userId:S.userId,server:u.server,token:S.token,expires:S.expires,ssl:S.ssl,_oAuthCred:S}));else if(i._oAuthHash&&i._oAuthHash.state.portalUrl===f.portalUrl){var A=i._oAuthHash;c=new k({userId:A.username,server:u.server,token:A.access_token,expires:(new Date).getTime()+1e3*Number(A.expires_in),ssl:"true"===A.ssl,oAuthState:A.state,_oAuthCred:S}),S.storage=A.persist?window.localStorage:window.sessionStorage,S.token=c.token,S.expires=c.expires,S.userId=c.userId,S.ssl=c.ssl,S.save(),i._oAuthHash=null,n(c)}else d?e._pendingDfd=i.oAuthSignIn(e.resUrl_,u,f,e.options_).addCallbacks(n,o):(h=new Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!r.isDebug,o(h))}else if(d){if(i._checkProtocol(e.resUrl_,u,o,e.admin_)){var T=e.options_;e.admin_&&(T=T||{},T.isAdmin=!0),e._pendingDfd=i.signIn(e.resUrl_,u,T).addCallbacks(n,o)}}else h=new Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!r.isDebug,o(h)},l=function(){var r,t,a,l,c=e.sinfo_,h=c.owningSystemUrl,u=e.options_;if(u&&(r=u.token,t=u.error,a=u.prompt),l=i._findCredential(h,{token:r,resource:e.resUrl_}),l||s.some(i.credentials,function(e){return this._isIdProvider(h,e.server)&&(l=e),!!l},i),l){var d=i.findCredential(e.resUrl_,l.userId);if(d)n(d);else if(T(c,i._legacyFed)){var f=l.toJson();f.server=c.server,f.resources=null,n(new k(f))}else{var g=e._pendingDfd=i.generateToken(i.findServerInfo(l.server),null,{serverUrl:e.resUrl_,token:l.token,ssl:l.ssl});g.addCallbacks(function(r){n(new k({userId:l.userId,server:c.server,token:r.token,expires:_.isDefined(r.expires)?Number(r.expires):null,ssl:!!r.ssl,isAdmin:e.admin_,validity:r.validity}))},o)}}else{i._busy=null,r&&(e.options_.token=null);(e._pendingDfd=i.getCredential(h.replace(/\/?$/,"/sharing"),{resource:e.resUrl_,owningTenant:c.owningTenant,token:r,error:t,prompt:a})).addCallbacks(function(r){i._enqueue(e.resUrl_,e.sinfo_,e.options_,e,e.admin_)},function(e){o(e)})}};this._errbackFunc=o;var c=e.sinfo_.owningSystemUrl,h=this._isServerRsrc(e.resUrl_),u=e.sinfo_._restInfoDfd;u?u.addCallbacks(function(r){var s=e.sinfo_;s.adminTokenServiceUrl=s._restInfoDfd.adminUrl_,s._restInfoDfd=null,s.tokenServiceUrl=t.getObject("authInfo.tokenServicesUrl",!1,r)||t.getObject("authInfo.tokenServiceUrl",!1,r)||t.getObject("tokenServiceUrl",!1,r),s.shortLivedTokenValidity=t.getObject("authInfo.shortLivedTokenValidity",!1,r),s.currentVersion=r.currentVersion,s.owningTenant=r.owningTenant;var n=s.owningSystemUrl=r.owningSystemUrl;n&&i._portals.push(n),h&&n?l():a()},function(){e.sinfo_._restInfoDfd=null;var t=new Error("Unknown resource - could not find token service endpoint.");t.code="IdentityManagerBase.2",t.log=!!r.isDebug,o(t)}):h&&c?l():e.sinfo_._selfReq?e.sinfo_._selfReq.selfDfd.then(function(r){var t,s,n,o,a={};return r&&(t=r.user&&r.user.username,a.username=t,a.allSSL=r.allSSL,s=r.supportsOAuth,n=r.currentVersion,"multitenant"===r.portalMode&&(o=r.customBaseUrl)),e.sinfo_.webTierAuth=!!t,t&&i.normalizeWebTierAuth?i.generateToken(e.sinfo_,null,{ssl:a.allSSL}).addBoth(function(e){return a.portalToken=e&&e.token,a.tokenExpiration=e&&e.expires,a}):!t&&s&&parseFloat(n)>=4.4&&!i._canUsePortalSignInWorkflow(e.resUrl_)?i._generateOAuthInfo({portalUrl:e.sinfo_.server,customBaseUrl:o,owningTenant:e.sinfo_._selfReq.owningTenant}).always(function(){return a}):a}).always(function(r){e.sinfo_._selfReq=null,r?a(r.username,r.allSSL,r.portalToken,r.tokenExpiration):a()}):a()},_generateOAuthInfo:function(e){var r,t,s=this,n=e.portalUrl,o=e.customBaseUrl,a=e.owningTenant,l=!this.defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal;if(l){t=window.location.href;var c=t.indexOf("?");c>-1&&(t=t.slice(0,c)),c=t.search(/\/(apps|home)\//),t=c>-1?t.slice(0,c):null}return l&&t?(this._hasTestedIfAppIsOnPortal=!0,r=m({url:t+"/sharing/rest",content:{f:"json"},handleAs:"json"}).then(function(){s.defaultOAuthInfo=new w({appId:"arcgisonline",popup:!0,popupCallbackUrl:t+"/home/oauth-callback.html"})})):(r=new i,r.resolve(),r=r.promise),r.then(function(){if(s.defaultOAuthInfo)return n=n.replace(/^http:/i,"https:"),m({url:n+"/sharing/rest/oauth2/validateRedirectUri",content:{accountId:a,client_id:s.defaultOAuthInfo.appId,redirect_uri:v.getAbsoluteUrl(s.defaultOAuthInfo.popupCallbackUrl),f:"json"},handleAs:"json",callbackParamName:"callback"}).then(function(e){if(e.valid){var r=s.defaultOAuthInfo.clone();e.urlKey&&o?r.portalUrl="https://"+e.urlKey+"."+o:r.portalUrl=n,s.oAuthInfos.push(r)}})})}});return k=e(S,{declaredClass:"esri.Credential",tokenRefreshBuffer:2,constructor:function(e){t.mixin(this,e),this.resources=this.resources||[],_.isDefined(this.creationTime)||(this.creationTime=(new Date).getTime())},_oAuthCred:null,refreshToken:function(){var e,r,t=this,i=this.resources&&this.resources[0],n=d.id.findServerInfo(this.server),o=n&&n.owningSystemUrl,a=!!o&&"server"===this.scope,l=a&&T(n,d.id._legacyFed),c=a&&d.id.findServerInfo(o),h=n.webTierAuth,u=h&&d.id.normalizeWebTierAuth,f=U[this.server],g=f&&f[this.userId],v={username:this.userId,password:g};if((!h||u)&&(a&&!c&&s.some(d.id.serverInfos,function(e){return d.id._isIdProvider(o,e.server)&&(c=e),!!c}),e=c&&d.id.findCredential(c.server,this.userId),!a||e)){if(l)return void e.refreshToken();if(a)r={serverUrl:i,token:e&&e.token,ssl:e&&e.ssl};else if(u)v=null,r={ssl:this.ssl};else{if(!g){var p;return i&&(i=d.id._sanitizeUrl(i),this._enqueued=1,p=d.id._enqueue(i,n,null,null,this.isAdmin,this),p.addCallback(function(){t._enqueued=0,t.refreshServerTokens()}).addErrback(function(){t._enqueued=0})),p}this.isAdmin&&(r={isAdmin:!0})}return d.id.generateToken(a?c:n,a?null:v,r).addCallback(function(e){t.token=e.token,t.expires=_.isDefined(e.expires)?Number(e.expires):null,t.creationTime=(new Date).getTime(),t.validity=e.validity,t.onTokenChange(),t.refreshServerTokens()}).addErrback(function(){})}},refreshServerTokens:function(){"portal"===this.scope&&s.forEach(d.id.credentials,function(e){var r=d.id.findServerInfo(e.server),t=r&&r.owningSystemUrl;e!==this&&e.userId===this.userId&&t&&"server"===e.scope&&(d.id._hasSameServerInstance(this.server,t)||d.id._isIdProvider(t,this.server))&&(T(r,d.id._legacyFed)?(e.token=this.token,e.expires=this.expires,e.creationTime=this.creationTime,e.validity=this.validity,e.onTokenChange()):e.refreshToken())},this)},onTokenChange:function(e){clearTimeout(this._refreshTimer);var r=this.server&&d.id.findServerInfo(this.server),t=r&&r.owningSystemUrl,s=t&&d.id.findServerInfo(t);!1!==e&&(!t||"portal"===this.scope||s&&s.webTierAuth&&!d.id.normalizeWebTierAuth)&&(_.isDefined(this.expires)||_.isDefined(this.validity))&&this._startRefreshTimer()},onDestroy:function(){},destroy:function(){this.userId=this.server=this.token=this.expires=this.validity=this.resources=this.creationTime=null,this._oAuthCred&&(this._oAuthCred.destroy(),this._oAuthCred=null);var e=s.indexOf(d.id.credentials,this);e>-1&&d.id.credentials.splice(e,1),this.onTokenChange(),this.onDestroy()},toJson:function(){return this._toJson()},_toJson:function(){var e=_.fixJson({userId:this.userId,server:this.server,token:this.token,expires:this.expires,validity:this.validity,ssl:this.ssl,isAdmin:this.isAdmin,creationTime:this.creationTime,scope:this.scope}),r=this.resources;return r&&r.length>0&&(e.resources=r.slice()),e},_startRefreshTimer:function(){clearTimeout(this._refreshTimer);var e=6e4*this.tokenRefreshBuffer,r=this.validity?this.creationTime+6e4*this.validity:this.expires,s=r-(new Date).getTime();s<0&&(s=0),this._refreshTimer=setTimeout(t.hitch(this,this.refreshToken),s>e?s-e:s)}}),b.Credential=k,a("extend-esri")&&(d.IdentityManagerBase=b),b});