forked from Esri/arcgis-js-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIdentityManagerBase.js
25 lines (24 loc) · 31.4 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 © 2021 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.36/esri/copyright.txt for details.
define(["dojo/_base/declare","dojo/_base/config","dojo/_base/lang","dojo/_base/array","dojo/_base/Deferred","dojo/_base/url","dojo/sniff","dojo/io-query","dojo/on","./kernel","./config","./lang","./ServerInfo","./urlUtils","./deferredUtils","./request","./Evented","./OAuthCredential","./arcgis/OAuthInfo"],(function(e,r,t,s,n,i,o,a,c,l,h,u,d,f,g,v,_,p,m){var S,w={},I=function(e){var r=new i(e.owningSystemUrl).host,t=new i(e.server).host,s=/.+\.arcgis\.com$/i;return s.test(r)&&s.test(t)},k=function(e,r){return!!(I(e)&&r&&s.some(r,(function(r){return r.test(e.server)})))},U=null,y=null;try{U=window.localStorage,y=window.sessionStorage}catch(e){}var b=e(_,{declaredClass:"esri.IdentityManagerBase",constructor:function(){this._portalConfig=t.getObject("esriGeowConfig"),this.serverInfos=[],this.oAuthInfos=[],this.credentials=[],this._soReqs=[],this._xoReqs=[],this._portals=[],this._getOAuthHash(),c(window,"pageshow",t.hitch(this,this._pageShowHandler))},defaultOAuthInfo:null,defaultTokenValidity:60,tokenValidity:null,normalizeWebTierAuth:!1,_appUrlObj:f.urlToObject(window.location.href),_postMessageAuthHandle:null,_busy:null,_rejectOnPersistedPageShow:!1,_oAuthHash:null,_gwTokenUrl:"/sharing/generateToken",_agsRest:"/rest/services",_agsPortal:/\/sharing(\/|$)/i,_agsAdmin:/(https?:\/\/[^\/]+\/[^\/]+)\/admin\/?(\/.*)?$/i,_adminSvcs:/\/rest\/admin\/services(\/|$)/i,_gwDomains:[{regex:/^https?:\/\/www\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com",tokenServiceUrl:"https://www.arcgis.com/sharing/generateToken"},{regex:/^https?:\/\/(?:dev|[a-z\d-]+\.mapsdev)\.arcgis\.com/i,customBaseUrl:"mapsdev.arcgis.com",tokenServiceUrl:"https://dev.arcgis.com/sharing/generateToken"},{regex:/^https?:\/\/(?:devext|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,customBaseUrl:"mapsdevext.arcgis.com",tokenServiceUrl:"https://devext.arcgis.com/sharing/generateToken"},{regex:/^https?:\/\/(?:qaext|[a-z\d-]+\.mapsqa)\.arcgis\.com/i,customBaseUrl:"mapsqa.arcgis.com",tokenServiceUrl:"https://qaext.arcgis.com/sharing/generateToken"},{regex:/^https?:\/\/[a-z\d-]+\.maps\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com",tokenServiceUrl:"https://www.arcgis.com/sharing/generateToken"}],_legacyFed:[],_regexSDirUrl:/http.+\/rest\/services\/?/gi,_regexServerType:/(\/(FeatureServer|GPServer|GeoDataServer|GeocodeServer|GeoenrichmentServer|GeometryServer|GlobeServer|ImageServer|MapServer|MobileServer|NAServer|NetworkDiagramServer|ParcelFabricServer|RelationalCatalogServer|SceneServer|StreamServer|UtilityNetworkServer|ValidationServer|VectorTileServer|VersionManagementServer)).*/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=h.defaults.io.corsEnabledServers,t=this._getOrigin(e.tokenServiceUrl);f.canUseXhr(e.server)||r.push(e.server.replace(/^https?:\/\//i,"")),f.canUseXhr(t)||r.push(t.replace(/^https?:\/\//i,""))}}),this)},registerOAuthInfos:function(e){var r=this.oAuthInfos;r?(s.forEach(e,(function(e){var t=this.findOAuthInfo(e.portalUrl);t&&r.splice(r.indexOf(t),1)}),this),this.oAuthInfos=r.concat(e)):this.oAuthInfos=e},registerToken:function(e){e=u.mixin({},e);var r,s=this._sanitizeUrl(e.server),n=this.findServerInfo(s),i=!0;n||((n=new d).server=this._getServerInstanceRoot(s),n.tokenServiceUrl=this._getTokenSvcUrl(s),n.hasPortal=!0,this.registerServers([n])),(r=this.findCredential(s,e.userId))?(delete e.server,t.mixin(r,e),i=!1):((r=new S({userId:e.userId,server:n.server,token:e.token,expires:e.expires,ssl:e.ssl,scope:this._isServerRsrc(s)?"server":"portal"})).resources=[s],this.credentials.push(r)),r.onTokenChange(!1),i||r.refreshServerTokens()},toJson:function(){return u.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=JSON.parse(e));var r=e.serverInfos,n=e.oAuthInfos,i=e.credentials;if(r){var o=[];s.forEach(r,(function(e){e.server&&e.tokenServiceUrl&&o.push(e.declaredClass?e:new d(e))})),o.length&&this.registerServers(o)}if(n){var a=[];s.forEach(n,(function(e){e.appId&&a.push(e.declaredClass?e:new m(e))})),a.length&&this.registerOAuthInfos(a)}i&&s.forEach(i,(function(e){e.userId&&e.server&&e.token&&e.expires&&e.expires>(new Date).getTime()&&((e=e.declaredClass?e:new S(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,n;return e=this._sanitizeUrl(e),n=this._isServerRsrc(e)?"server":"portal",r?s.some(this.credentials,(function(s){return this._hasSameServerInstance(s.server,e)&&r===s.userId&&s.scope===n&&(t=s),!!t}),this):s.some(this.credentials,(function(r){return this._hasSameServerInstance(r.server,e)&&-1!==this._getIdenticalSvcIdx(e,r)&&r.scope===n&&(t=r),!!t}),this),t},getCredential:function(e,s){var i,o,a=!0;u.isDefined(s)&&(t.isObject(s)?(i=!!s.token,o=s.error,a=!1!==s.prompt):i=s),e=this._sanitizeUrl(e);var c,l=new n(g._dfdCanceller),h=this._isAdminResource(e),v=i?this.findCredential(e):null;if(v&&o&&498===o.code)v.destroy();else if(v)return(c=new Error("You are currently signed in as: '"+v.userId+"'. You do not have access to this resource: "+e)).name="identity-manager:not-authorized",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,l.errback(c),l;var _=this._findCredential(e,s);if(_)return l.callback(_),l;var p=this.findServerInfo(e);if(p)!p.hasServer&&this._isServerRsrc(e)&&(p._restInfoDfd=this._getTokenSvcUrl(e,!0),p.hasServer=!0);else{var m=this._getTokenSvcUrl(e);if(!m)return(c=new Error("Unknown resource - could not find token service endpoint.")).name="identity-manager:unknown-resource",c.code="IdentityManagerBase.2",c.log=!!r.isDebug,l.errback(c),l;(p=new d).server=this._getServerInstanceRoot(e),t.isString(m)?(p.tokenServiceUrl=m,p.hasPortal=!0):(p._restInfoDfd=m,p.hasServer=!0),this.registerServers([p])}return p.hasPortal&&void 0===p._selfReq&&(a||f.hasSameOrigin(p.tokenServiceUrl,window.location.origin)||this._gwDomains.some((function(e){return e.tokenServiceUrl===p.tokenServiceUrl})))&&(p._selfReq={owningTenant:s&&s.owningTenant,selfDfd:this._getPortalSelf(p.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),e)}),this._enqueue(e,p,s,l,h)},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,n){var o,a,c,h,u,d,g,_,p,m=this._rePortalTokenSvc.test(e.tokenServiceUrl),S=new i(window.location.href.toLowerCase()),I=!s,k=e.shortLivedTokenValidity;s&&(p=l.id.tokenValidity||k||l.id.defaultTokenValidity)>k&&(p=k),n&&(o=n.isAdmin,a=n.serverUrl,c=n.token,d=n.ssl,e.customParameters=n.customParameters),o?h=e.adminTokenServiceUrl:(h=e.tokenServiceUrl,u=new i(h.toLowerCase()),e.webTierAuth&&n&&n.serverUrl&&!d&&"http"===S.scheme&&(f.hasSameOrigin(S.uri,h,!0)||"https"===u.scheme&&S.host===u.host&&"7080"===S.port&&"7443"===u.port)&&(h=h.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),I&&m&&(h=h.replace(/\/rest/i,""))),g=t.mixin({url:h,content:t.mixin({request:"getToken",username:s&&s.username,password:s&&s.password,serverUrl:a,token:c,expiration:p,referer:o||m?window.location.host:null,client:o?"referer":null,f:"json"},e.customParameters),handleAs:"json",callbackParamName:I?"callback":void 0},n&&n.ioArgs),_={usePost:!I,disableIdentityLookup:!0,useProxy:this._useProxy(e,n)},m||(g.withCredentials=!1);var U=v(g,_);return U.addCallback((function(t){if(!t||!t.token){var n=new Error("Unable to generate token");return n.name="identity-manager:authentication-failed",n.code="IdentityManagerBase.3",n.log=!!r.isDebug,n}var i=e.server;return w[i]||(w[i]={}),s&&(w[i][s.username]=s.password),t.validity=p,t})),U.addErrback((function(e){})),U},isBusy:function(){return!!this._busy},checkSignInStatus:function(e){var r=new n;return this.checkAppAccess(e,"").then((function(e){r.resolve(e.credential)})).catch((function(e){r.reject(e)})),r},checkAppAccess:function(e,t,s){var n=this,i=!1;return this.getCredential(e,{prompt:!1}).then((function(o){var a,c={f:"json"};if("portal"===o.scope)if(t&&(n._doPortalSignIn(e)||s&&s.force))a=o.server+"/sharing/rest/oauth2/validateAppAccess",c.client_id=t;else{if(!o.token)return{credential:o};a=o.server+"/sharing/rest"}else{if(!o.token)return{credential:o};a=o.server+"/rest/services"}return o.token&&(c.token=o.token),v({url:a,content:c,callbackParamName:"callback"},{disableIdentityLookup:!0}).then((function(e){if(!1===e.valid){var s=new Error("You are currently signed in as: '"+o.userId+"'. You do not have access to this app: '"+t+"'.");throw s.name="identity-manager:not-authorized",s.code="IdentityManagerBase.1",s.log=!!r.isDebug,s.details=e,s}return i=!!e.viewOnlyUserTypeApp,{credential:o}})).catch((function(e){if("IdentityManagerBase.1"===e.code||400===e.code)throw 400===e.code&&(e.name="identity-manager:invalid-request"),e;if(498===e.code){o.destroy();var t=new Error("User is not signed in.");throw t.name="identity-manager:not-authenticated",t.code="IdentityManagerBase.6",t.log=!!r.isDebug,t}return{credential:o}}))})).then((function(e){return{credential:e.credential,viewOnly:i}}))},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()},enablePostMessageAuth:function(e){e||(e="https://www.arcgis.com/sharing/rest"),this._postMessageAuthHandle&&this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=c(window,"message",function(r){(r.origin===window.location.origin||u.endsWith(r.origin,".arcgis.com"))&&r.data&&"arcgis:auth:requestCredential"===r.data.type&&this.getCredential(e).then((function(e){r.source.postMessage({type:"arcgis:auth:credential",credential:{expires:e.expires,server:e.server,ssl:e.ssl,token:e.token,userId:e.userId}},r.origin)})).catch((function(e){r.source.postMessage({type:"arcgis:auth:error",error:{name:e.name,message:e.message}},r.origin)}))}.bind(this))},disablePostMessageAuth:function(){this._postMessageAuthHandle&&(this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=null)},_getOAuthHash:function(){var e=window.location.hash;if(e){"#"===e.charAt(0)&&(e=e.substring(1));var r=a.queryToObject(e),t=!1;if(r.access_token&&r.expires_in&&r.state&&r.hasOwnProperty("username"))try{r.state=JSON.parse(r.state),"object"==typeof r.state&&r.state.portalUrl&&(this._oAuthHash=r,t=!0)}catch(e){}else r.error&&r.error_description&&(console.log("IdentityManager OAuth Error: ",r.error," - ",r.error_description),"access_denied"===r.error&&(t=!0));t&&(window.location.hash=r.state&&r.state.hash||"")}},_pageShowHandler:function(e){if(e.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow){var t=new Error("ABORTED");t.name="identity-manager:user-aborted",t.code="IdentityManager.2",t.log=!!r.isDebug,this._errbackFunc(t)}},_findCredential:function(e,r){var t,n,i,o,a=-1,c=r&&r.token,l=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=l||e,u.length)if(1===u.length){if(t=u[0],o=this.findServerInfo(t.server),n=o&&o.owningSystemUrl,i=n&&this.findCredential(n,t.userId),a=this._getIdenticalSvcIdx(e,t),!c)return-1===a&&t.resources.push(e),this._addResource(e,i),t;-1!==a&&(t.resources.splice(a,1),this._removeResource(e,i))}else{var d,f;if(s.some(u,(function(r){return-1!==(f=this._getIdenticalSvcIdx(e,r))&&(d=r,o=this.findServerInfo(d.server),n=o&&o.owningSystemUrl,i=n&&this.findCredential(n,d.userId),a=f,!0)}),this),c)d&&(d.resources.splice(a,1),this._removeResource(e,i));else if(d)return this._addResource(e,i),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&&!f.hasSameOrigin(e.adminTokenServiceUrl,window.location.href)||!this._isPortalDomain(e.tokenServiceUrl)&&10.1==e.currentVersion&&!f.hasSameOrigin(e.tokenServiceUrl,window.location.href)},_getOrigin:function(e){var r=new i(e);return r.scheme+"://"+r.host+(u.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(":")))},_normalizeAGOLorgDomain:function(e){var r=/^https?:\/\/(?:cdn|[a-z\d-]+\.maps)\.arcgis\.com/i,t=/^https?:\/\/(?:cdndev|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,s=/^https?:\/\/(?:cdnqa|[a-z\d-]+\.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=(h.defaults.io.proxyUrl||"").toLowerCase(),t=r?e.toLowerCase().indexOf(r+"?"):-1;return-1!==t&&(e=e.substring(t+r.length+1)),e=f.normalize(e),f.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(),n=this._getSuffix(r).toLowerCase();if(!(t=s===n)){var i=/(.*)\/(MapServer|FeatureServer).*/gi;t=s.replace(i,"$1")===n.replace(i,"$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){var r=new i(e.toLowerCase()),n=this._portalConfig,o=s.some(this._gwDomains,(function(e){return e.regex.test(r.uri)}));if(!o&&n&&(o=this._hasSameServerInstance(this._getServerInstanceRoot(n.restBaseUrl),r.uri)),!o){if(!this._arcgisUrl){var a=t.getObject("esri.arcgis.utils.arcgisUrl");a&&(this._arcgisUrl=new i(a).authority)}this._arcgisUrl&&(o=this._arcgisUrl.toLowerCase()===r.authority)}return o||(o=s.some(this._portals,(function(e){return this._hasSameServerInstance(e,r.uri)}),this)),o=o||this._agsPortal.test(r.path)},_isIdProvider:function(e,r){var t=-1,n=-1;s.forEach(this._gwDomains,(function(s,i){-1===t&&s.regex.test(e)&&(t=i),-1===n&&s.regex.test(r)&&(n=i)}));var i=!1;if(t>-1&&n>-1&&(0===t||4===t?0!==n&&4!==n||(i=!0):1===t?1!==n&&2!==n||(i=!0):2===t?2===n&&(i=!0):3===t&&3===n&&(i=!0)),!i){var o=this.findServerInfo(r),a=o&&o.owningSystemUrl;a&&I(o)&&this._isPortalDomain(a)&&this._isIdProvider(e,a)&&(i=!0)}return i},_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,n;if(this._isRESTService(e)||this._isAdminResource(e)){var o=this._getServerInstanceRoot(e);return r=o+"/admin/generateToken",(t=v({url:e=o+"/rest/info",content:{f:"json"},handleAs:"json",callbackParamName:"callback"})).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!==(n=e.toLowerCase().indexOf("/sharing"))&&(a=e.substring(0,n)+this._gwTokenUrl),a||(a=this._getOrigin(e)+this._gwTokenUrl),a){var c=new i(e).port;/^http:\/\//i.test(e)&&"7080"===c&&(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"},_exchangeToken:function(e,r,t){return v({url:e+"/sharing/rest/oauth2/exchangeToken",content:{f:"json",client_id:r,token:t}},{disableIdentityLookup:!0,usePost:!0}).then((function(e){return e.token}))},_getPlatformSelf:function(e,r){return v({url:e+"/sharing/rest/oauth2/platformSelf",content:{f:"json"},headers:{"X-Esri-Auth-Client-Id":r,"X-Esri-Auth-Redirect-Uri":window.location.href.replace(/#.*$/,"")},withCredentials:!0},{disableIdentityLookup:!0,usePost:!0})},_getPortalSelf:function(e,r){var t="";if(s.some(this._gwDomains,(function(r){return r.regex.test(e)&&(t=r.customBaseUrl),!!t})),t){var i=new n;return i.resolve({allSSL:!0,currentVersion:"4.4",customBaseUrl:t,portalMode:"multitenant",supportsOAuth:!0}),i}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")),v({url:e,content:{f:"json"},handleAs:"json",callbackParamName:"callback"},{crossOrigin:!1,disableIdentityLookup:!0})},_doPortalSignIn:function(e){var r=this._portalConfig,t=window.location.href,s=this.findServerInfo(e);return!(!r&&!this._isPortalDomain(t)||!(s?s.hasPortal||s.owningSystemUrl&&this._isPortalDomain(s.owningSystemUrl):this._isPortalDomain(e))||!(this._isIdProvider(t,e)||r&&(this._hasSameServerInstance(this._getServerInstanceRoot(r.restBaseUrl),e)||this._isIdProvider(r.restBaseUrl,e))||f.hasSameOrigin(t,e,!0)))},_checkProtocol:function(e,s,n,i){var o=!0,a=i?s.adminTokenServiceUrl:s.tokenServiceUrl;if(!(0!==t.trim(a).toLowerCase().indexOf("https:")||0===window.location.href.toLowerCase().indexOf("https:")||h.defaults.io.useCors&&(f.canUseXhr(a)||f.canUseXhr(f.getProxyUrl(!0).path))||(o=!!this._protocolFunc&&!!this._protocolFunc({resourceUrl:e,serverInfo:s})))){var c=new Error("Aborted the Sign-In process to avoid sending password over insecure connection.");c.name="identity-manager:aborted",c.code="IdentityManagerBase.4",c.log=!!r.isDebug,console.log(c.message),n(c)}return o},_enqueue:function(e,r,t,s,i,o){return s||(s=new n(g._dfdCanceller)),s.resUrl_=e,s.sinfo_=r,s.options_=t,s.admin_=i,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 n=this,i=function(r){var t=e.options_&&e.options_.resource,i=e.resUrl_,o=e.refresh_,a=!1;-1===s.indexOf(n.credentials,r)&&(o&&-1!==s.indexOf(n.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):n.credentials.push(r)),r.resources||(r.resources=[]),r.resources.push(t||i),r.scope=n._isServerRsrc(i)?"server":"portal",r.onTokenChange();var c=n._soReqs,l={};n._soReqs=[],s.forEach(c,(function(e){if(!this._isIdenticalService(i,e.resUrl_)){var t=this._getSuffix(e.resUrl_);l[t]||(l[t]=!0,r.resources.push(e.resUrl_))}}),n),e.callback(r),s.forEach(c,(function(e){this._hasSameServerInstance(this._getServerInstanceRoot(i),e.resUrl_)?e.callback(r):this._soReqs.push(e)}),n),n._busy=e.resUrl_=e.sinfo_=e.refresh_=null,a||n.onCredentialCreate({credential:r}),n._soReqs.length?n._doSignIn(n._soReqs.shift()):n._xoReqs.length&&n._doSignIn(n._xoReqs.shift())},o=function(r){e.errback(r),n._busy=e.resUrl_=e.sinfo_=e.refresh_=null,n._soReqs.length?n._doSignIn(n._soReqs.shift()):n._xoReqs.length&&n._doSignIn(n._xoReqs.shift())},a=function(t,s,a,l){var h,d,g=e.sinfo_,v=!e.options_||!1!==e.options_.prompt,_=g.hasPortal&&n._findOAuthInfo(e.resUrl_);if(t)i(new S({userId:t,server:g.server,token:a||null,expires:u.isDefined(l)?Number(l):null,ssl:!!s}));else if(window!==window.parent&&n._appUrlObj.query&&n._appUrlObj.query["arcgis-auth-origin"]&&n._appUrlObj.query["arcgis-auth-portal"]&&n._hasSameServerInstance(n._getServerInstanceRoot(n._appUrlObj.query["arcgis-auth-portal"]),e.resUrl_)){window.parent.postMessage({type:"arcgis:auth:requestCredential"},n._appUrlObj.query["arcgis-auth-origin"]);var m=c(window,"message",(function(e){if(e.source===window.parent&&e.data)if("arcgis:auth:credential"===e.data.type)m.remove(),i(new S(e.data.credential));else if("arcgis:auth:error"===e.data.type){m.remove();var t,s=e.data.error;switch(s.name){case"identity-manager:busy":case"identity-manager:not-authorized":t="IdentityManager.1";break;case"identity-manager:server-identification-failed":case"identity-manager:unknown-resource":case"identity-manager:user-aborted":t="IdentityManager.2";break;case"identity-manager:authentication-failed":t="IdentityManager.3";break;case"identity-manager:aborted":t="IdentityManager.4";break;case"identity-manager:not-authenticated":t="IdentityManager.6";break;case"identity-manager:invalid-request":t=400}var n=new Error(s.message);n.name=s.name,n.code=t,n.log=!!r.isDebug,o(n)}}))}else if(_){var w=_._oAuthCred;if(!w){var I=new p(_,U),k=new p(_,y);I.isValid()&&k.isValid()?I.expires>k.expires?(w=I,k.destroy()):(w=k,I.destroy()):w=I.isValid()?I:k,_._oAuthCred=w}if(w.isValid())h=new S({userId:w.userId,server:g.server,token:w.token,expires:w.expires,ssl:w.ssl,_oAuthCred:w}),_.appId!==w.appId&&n._doPortalSignIn(e.resUrl_)?e._pendingDfd=n._exchangeToken(h.server,_.appId,h.token).then((function(e){h.token=e,w.token=e,w.save(),i(h)})).catch((function(){i(h)})):i(h);else if(n._oAuthHash&&n._hasSameServerInstance(_.portalUrl,n._oAuthHash.state.portalUrl)){var b=n._oAuthHash;h=new S({userId:b.username,server:g.server,token:b.access_token,expires:(new Date).getTime()+1e3*Number(b.expires_in),ssl:"true"===b.ssl,oAuthState:b.state,_oAuthCred:w}),w.storage=b.persist?U:y,w.token=h.token,w.expires=h.expires,w.userId=h.userId,w.ssl=h.ssl,w.save(),n._oAuthHash=null,i(h)}else{var A=function(){v?e._pendingDfd=n.oAuthSignIn(e.resUrl_,g,_,e.options_).addCallbacks(i,o):((d=new Error("User is not signed in.")).name="identity-manager:not-authenticated",d.code="IdentityManagerBase.6",d.log=!!r.isDebug,o(d))};n._doPortalSignIn(e.resUrl_)?e._pendingDfd=n._getPlatformSelf(g.server,_.appId).then((function(e){var r=e.portalUrl;!r||f.hasSameOrigin(r,window.location.origin,!0)?(h=new S({server:g.server,userId:e.username,token:e.token}),i(h)):A()})).catch(A):A()}}else if(v){if(n._checkProtocol(e.resUrl_,g,o,e.admin_)){var T=e.options_;e.admin_&&((T=T||{}).isAdmin=!0),e._pendingDfd=n.signIn(e.resUrl_,g,T).addCallbacks(i,o)}}else(d=new Error("User is not signed in.")).name="identity-manager:not-authenticated",d.code="IdentityManagerBase.6",d.log=!!r.isDebug,o(d)},l=function(){var r,t,a,c,l=e.sinfo_,h=l.owningSystemUrl,d=e.options_;if(d&&(r=d.token,t=d.error,a=d.prompt),(c=n._findCredential(h,{token:r,resource:e.resUrl_}))||s.some(n.credentials,(function(e){return this._isIdProvider(h,e.server)&&(c=e),!!c}),n),c){var f=n.findCredential(e.resUrl_,c.userId);if(f)i(f);else if(k(l,n._legacyFed)){var g=c.toJson();g.server=l.server,g.resources=null,i(new S(g))}else{(e._pendingDfd=n.generateToken(n.findServerInfo(c.server),null,{serverUrl:e.resUrl_,token:c.token,ssl:c.ssl})).addCallbacks((function(r){i(new S({userId:c.userId,server:l.server,token:r.token,expires:u.isDefined(r.expires)?Number(r.expires):null,ssl:!!r.ssl,isAdmin:e.admin_,validity:r.validity}))}),o)}}else{n._busy=null,r&&(e.options_.token=null),(e._pendingDfd=n.getCredential(h.replace(/\/?$/,"/sharing"),{resource:e.resUrl_,owningTenant:l.owningTenant,token:r,error:t,prompt:a})).addCallbacks((function(r){n._enqueue(e.resUrl_,e.sinfo_,e.options_,e,e.admin_)}),(function(e){o(e)}))}};this._errbackFunc=o;var h=e.sinfo_.owningSystemUrl,d=this._isServerRsrc(e.resUrl_),g=e.sinfo_._restInfoDfd;g?g.addCallbacks((function(r){var s=e.sinfo_;if(s._restInfoDfd){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 i=s.owningSystemUrl=r.owningSystemUrl;i&&n._portals.push(i)}d&&s.owningSystemUrl?l():a()}),(function(){e.sinfo_._restInfoDfd=null;var t=new Error("Unknown resource - could not find token service endpoint.");t.name="identity-manager:server-identification-failed",t.code="IdentityManagerBase.2",t.log=!!r.isDebug,o(t)})):d&&h?l():e.sinfo_._selfReq?e.sinfo_._selfReq.selfDfd.then((function(r){var t,s,i,o,a={};return r&&(t=r.user&&r.user.username,a.username=t,a.allSSL=r.allSSL,s=r.supportsOAuth,i=r.currentVersion,"multitenant"===r.portalMode&&(o=r.customBaseUrl)),e.sinfo_.webTierAuth=!!t,t&&n.normalizeWebTierAuth?n.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(i)>=4.4&&!n._findOAuthInfo(e.resUrl_)?n._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,i=e.portalUrl,o=e.customBaseUrl,a=e.owningTenant,c=!this.defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal;if(c){var l=(t=window.location.href).indexOf("?");l>-1&&(t=t.slice(0,l)),l=t.search(/\/(apps|home)\//),t=l>-1?t.slice(0,l):null}return c&&t?(this._hasTestedIfAppIsOnPortal=!0,r=v({url:t+"/sharing/rest",content:{f:"json"},handleAs:"json"}).then((function(){s.defaultOAuthInfo=new m({appId:"arcgisonline",popupCallbackUrl:t+"/home/oauth-callback.html"})}))):((r=new n).resolve(),r=r.promise),r.then((function(){if(s.defaultOAuthInfo)return i=i.replace(/^http:/i,"https:"),v({url:i+"/sharing/rest/oauth2/validateRedirectUri",content:{accountId:a,client_id:s.defaultOAuthInfo.appId,redirect_uri:f.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.toLowerCase()+"."+o:r.portalUrl=i,r.popup=window!==window.top||!(f.hasSameOrigin(i,window.location.origin)||s._gwDomains.some((function(e){return e.regex.test(i)&&e.regex.test(window.location.origin)}))),s.oAuthInfos.push(r)}}))}))}});return S=e(_,{declaredClass:"esri.Credential",tokenRefreshBuffer:2,constructor:function(e){t.mixin(this,e),this.resources=this.resources||[],u.isDefined(this.creationTime)||(this.creationTime=(new Date).getTime())},_oAuthCred:null,refreshToken:function(){var e,r,t=this,n=this.resources&&this.resources[0],i=l.id.findServerInfo(this.server),o=i&&i.owningSystemUrl,a=!!o&&"server"===this.scope,c=a&&k(i,l.id._legacyFed),h=a&&l.id.findServerInfo(o),d=i.webTierAuth,f=d&&l.id.normalizeWebTierAuth,g=w[this.server],v=g&&g[this.userId],_={username:this.userId,password:v};if((!d||f)&&(a&&!h&&s.some(l.id.serverInfos,(function(e){return l.id._isIdProvider(o,e.server)&&(h=e),!!h})),e=h&&l.id.findCredential(h.server,this.userId),!a||e)){if(!c){if(a)r={serverUrl:n,token:e&&e.token,ssl:e&&e.ssl};else if(f)_=null,r={ssl:this.ssl};else{var p;if(!v)return n&&(n=l.id._sanitizeUrl(n),this._enqueued=1,(p=l.id._enqueue(n,i,null,null,this.isAdmin,this)).addCallback((function(){t._enqueued=0,t.refreshServerTokens()})).addErrback((function(){t._enqueued=0}))),p;this.isAdmin&&(r={isAdmin:!0})}return l.id.generateToken(a?h:i,a?null:_,r).addCallback((function(e){t.token=e.token,t.expires=u.isDefined(e.expires)?Number(e.expires):null,t.creationTime=(new Date).getTime(),t.validity=e.validity,t.onTokenChange(),t.refreshServerTokens()})).addErrback((function(){}))}e.refreshToken()}},refreshServerTokens:function(){"portal"===this.scope&&s.forEach(l.id.credentials,(function(e){var r=l.id.findServerInfo(e.server),t=r&&r.owningSystemUrl;e!==this&&e.userId===this.userId&&t&&"server"===e.scope&&(l.id._hasSameServerInstance(this.server,t)||l.id._isIdProvider(t,this.server))&&(k(r,l.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&&l.id.findServerInfo(this.server),t=r&&r.owningSystemUrl,s=t&&l.id.findServerInfo(t);!1!==e&&(!t||"portal"===this.scope||s&&s.webTierAuth&&!l.id.normalizeWebTierAuth)&&(u.isDefined(this.expires)||u.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(l.id.credentials,this);e>-1&&l.id.credentials.splice(e,1),this.onTokenChange(),this.onDestroy()},toJson:function(){return this._toJson()},_toJson:function(){var e=u.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=Math.pow(2,31)-1,s=(this.validity?this.creationTime+6e4*this.validity:this.expires)-(new Date).getTime();s<0?s=0:s>r&&(s=r),this._refreshTimer=setTimeout(t.hitch(this,this.refreshToken),s>e?s-e:s)}}),b.Credential=S,o("extend-esri")&&(l.IdentityManagerBase=b),b}));