// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.23/esri/copyright.txt for details.
//>>built
define("esri/IdentityManagerBase","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/regexp ./kernel ./config ./lang ./ServerInfo ./urlUtils ./deferredUtils ./request ./Evented ./OAuthCredential ./arcgis/OAuthInfo".split(" "),function(L,q,n,g,A,D,w,E,F,R,S,m,G,u,H,p,M,x,N,O,P){var B={},I=function(a){var b=(new w(a.owningSystemUrl)).host;a=(new w(a.server)).host;var c=/.+\.arcgis\.com$/i;
return c.test(b)&&c.test(a)},J=function(a,b){return!!(I(a)&&b&&g.some(b,function(b){return b.test(a.server)}))},v,K=L(N,{declaredClass:"esri.IdentityManagerBase",constructor:function(){this._portalConfig=n.getObject("esriGeowConfig");this.serverInfos=[];this.oAuthInfos=[];this.credentials=[];this._soReqs=[];this._xoReqs=[];this._portals=[];this._getOAuthHash()},defaultOAuthInfo:null,defaultTokenValidity:60,tokenValidity:null,signInPage:null,useSignInPage:!0,normalizeWebTierAuth:!1,_busy:null,_oAuthHash:null,
_gwTokenUrl:"/sharing/generateToken",_agsRest:"/rest/services",_agsPortal:/\/sharing(\/|$)/i,_agsAdmin:/https?:\/\/[^\/]+\/[^\/]+\/admin\/?(\/.*)?$/i,_adminSvcs:/\/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\/?/ig,_regexServerType:/(\/(MapServer|GeocodeServer|GPServer|GeometryServer|ImageServer|NAServer|FeatureServer|GeoDataServer|GlobeServer|MobileServer|GeoenrichmentServer|VectorTileServer)).*/ig,_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(a){var b=this.serverInfos;b?(a=g.filter(a,function(a){return!this.findServerInfo(a.server)},this),this.serverInfos=b.concat(a)):this.serverInfos=a;g.forEach(a,function(a){a.owningSystemUrl&&this._portals.push(a.owningSystemUrl);
if(a.hasPortal){this._portals.push(a.server);var b=G.defaults.io.corsEnabledServers,c=this._getOrigin(a.tokenServiceUrl);p.canUseXhr(a.server)||b.push(a.server.replace(/^https?:\/\//i,""));p.canUseXhr(c)||b.push(c.replace(/^https?:\/\//i,""))}},this)},registerOAuthInfos:function(a){var b=this.oAuthInfos;b?(a=g.filter(a,function(a){return!this.findOAuthInfo(a.portalUrl)},this),this.oAuthInfos=b.concat(a)):this.oAuthInfos=a},registerToken:function(a){var b=this._sanitizeUrl(a.server),c=this.findServerInfo(b),
d=!0,e;c||(c=new H,c.server=this._getServerInstanceRoot(b),c.tokenServiceUrl=this._getTokenSvcUrl(b),c.hasPortal=!0,this.registerServers([c]));(e=this.findCredential(b,a.userId))?(n.mixin(e,a),d=!1):(e=new v({userId:a.userId,server:c.server,token:a.token,expires:a.expires,ssl:a.ssl,scope:this._isServerRsrc(b)?"server":"portal"}),e.resources=[b],this.credentials.push(e));e.onTokenChange(!1);d||e.refreshServerTokens()},toJson:function(){return u.fixJson({serverInfos:g.map(this.serverInfos,function(a){return a.toJson()}),
oAuthInfos:g.map(this.oAuthInfos,function(a){return a.toJson()}),credentials:g.map(this.credentials,function(a){return a.toJson()})})},initialize:function(a){if(a){n.isString(a)&&(a=D.fromJson(a));var b=a.serverInfos,c=a.oAuthInfos;a=a.credentials;if(b){var d=[];g.forEach(b,function(a){a.server&&a.tokenServiceUrl&&d.push(a.declaredClass?a:new H(a))});d.length&&this.registerServers(d)}if(c){var e=[];g.forEach(c,function(a){a.appId&&e.push(a.declaredClass?a:new P(a))});e.length&&this.registerOAuthInfos(e)}a&&
g.forEach(a,function(a){a.userId&&a.server&&a.token&&a.expires&&a.expires>(new Date).getTime()&&(a=a.declaredClass?a:new v(a),a.onTokenChange(),this.credentials.push(a))},this)}},findServerInfo:function(a){var b;a=this._sanitizeUrl(a);g.some(this.serverInfos,function(c){this._hasSameServerInstance(c.server,a)&&(b=c);return!!b},this);return b},findOAuthInfo:function(a){var b;a=this._sanitizeUrl(a);g.some(this.oAuthInfos,function(c){this._hasSameServerInstance(c.portalUrl,a)&&(b=c);return!!b},this);
return b},findCredential:function(a,b){var c,d;a=this._sanitizeUrl(a);d=this._isServerRsrc(a)?"server":"portal";b?g.some(this.credentials,function(e){this._hasSameServerInstance(e.server,a)&&b===e.userId&&e.scope===d&&(c=e);return!!c},this):g.some(this.credentials,function(b){this._hasSameServerInstance(b.server,a)&&-1!==this._getIdenticalSvcIdx(a,b)&&b.scope===d&&(c=b);return!!c},this);return c},getCredential:function(a,b){var c,d,e=!0;u.isDefined(b)&&(n.isObject(b)?(c=!!b.token,d=b.error,e=!1!==
b.prompt):c=b);a=this._sanitizeUrl(a);var g=new A(M._dfdCanceller),f=this._isAdminResource(a),k=c&&this._doPortalSignIn(a)?this._getEsriAuthCookie():null;if((c=c?this.findCredential(a):null)&&d&&498===d.code)c.destroy(),k&&k.token===b.token&&F("esri_auth",null,{expires:-1,path:"/",domain:document.domain});else if(k||c)return e=Error("You are currently signed in as: '"+(k&&k.email||c&&c.userId)+"'. You do not have access to this resource: "+a),e.code="IdentityManagerBase.1",e.httpCode=d&&d.httpCode,
e.messageCode=d?d.messageCode:null,e.subcode=d?d.subcode:null,e.details=d?d.details:null,e.log=!!q.isDebug,g.errback(e),g;if(d=this._findCredential(a,b))return g.callback(d),g;d=this.findServerInfo(a);if(d)!d.hasServer&&this._isServerRsrc(a)&&(d._restInfoDfd=this._getTokenSvcUrl(a,!0),d.hasServer=!0);else{k=this._getTokenSvcUrl(a);if(!k)return e=Error("Unknown resource - could not find token service endpoint."),e.code="IdentityManagerBase.2",e.log=!!q.isDebug,g.errback(e),g;d=new H;d.server=this._getServerInstanceRoot(a);
n.isString(k)?(d.tokenServiceUrl=k,d.hasPortal=!0):(d._restInfoDfd=k,d.hasServer=!0);this.registerServers([d])}e&&d.hasPortal&&void 0===d._selfReq&&!this._findOAuthInfo(a)&&(d._selfReq={owningTenant:b&&b.owningTenant,selfDfd:this._getPortalSelf(d.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),a)});return this._enqueue(a,d,b,g,f)},getResourceName:function(a){return this._isRESTService(a)?a.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(a)&&
a.replace(this._gwUser,"$1")||this._gwItem.test(a)&&a.replace(this._gwItem,"$1")||this._gwGroup.test(a)&&a.replace(this._gwGroup,"$1")||""},generateToken:function(a,b,c){var d,e,g,f,k,Q,h=this._rePortalTokenSvc.test(a.tokenServiceUrl),l=new w(window.location.href.toLowerCase()),r=this._getEsriAuthCookie(),C,y=!b;f=a.shortLivedTokenValidity;var z;b&&(z=m.id.tokenValidity||f||m.id.defaultTokenValidity,z>f&&(z=f));c&&(d=c.isAdmin,e=c.serverUrl,g=c.token,Q=c.ssl,a.customParameters=c.customParameters);
d?f=a.adminTokenServiceUrl:(f=a.tokenServiceUrl,k=new w(f.toLowerCase()),r&&(C=(C=r.auth_tier)&&C.toLowerCase()),("web"===C||a.webTierAuth)&&c&&c.serverUrl&&!Q&&"http"===l.scheme&&(p.hasSameOrigin(l.uri,f,!0)||"https"===k.scheme&&l.host===k.host&&"7080"===l.port&&"7443"===k.port)&&(f=f.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),y&&h&&(f=f.replace(/\/rest/i,"")));d=n.mixin({url:f,content:n.mixin({request:"getToken",username:b&&b.username,password:b&&b.password,serverUrl:e,token:g,expiration:z,
referer:d||h?window.location.host:null,client:d?"referer":null,f:"json"},a.customParameters),handleAs:"json",callbackParamName:y?"callback":void 0},c&&c.ioArgs);c={usePost:!y,disableIdentityLookup:!0,useProxy:this._useProxy(a,c)};h||(d.withCredentials=!1);h=x(d,c);h.addCallback(function(c){if(!c||!c.token)return c=Error("Unable to generate token"),c.code="IdentityManagerBase.3",c.log=!!q.isDebug,c;var d=a.server;B[d]||(B[d]={});b&&(B[d][b.username]=b.password);c.validity=z;return c});h.addErrback(function(a){});
return h},isBusy:function(){return!!this._busy},checkSignInStatus:function(a){var b=new A;this.getCredential(a,{prompt:!1}).then(function(a){return a.token?x({url:a.server+("portal"===a.scope?"/sharing/rest":"/rest/services"),content:{f:"json",token:a.token},callbackParamName:"callback"},{disableIdentityLookup:!0}).then(function(){return a}).otherwise(function(b){if(498===b.code)throw a.destroy(),b=Error("User is not signed in."),b.code="IdentityManagerBase.6",b.log=!!q.isDebug,b;return a}):a}).then(function(a){b.resolve(a)}).otherwise(function(a){b.reject(a)});
return b},setRedirectionHandler:function(a){this._redirectFunc=a},setProtocolErrorHandler:function(a){this._protocolFunc=a},signIn:function(){},oAuthSignIn:function(){},onCredentialCreate:function(){},onCredentialsDestroy:function(){},destroyCredentials:function(){if(this.credentials){var a=this.credentials.slice();g.forEach(a,function(a){a.destroy()})}this.onCredentialsDestroy()},_getOAuthHash:function(){var a=window.location.hash;if(a){"#"===a.charAt(0)&&(a=a.substring(1));var a=R.queryToObject(a),
b=!1;a.access_token&&a.expires_in&&a.state&&a.hasOwnProperty("username")?(a.state=D.fromJson(a.state),this._oAuthHash=a,b=!0):a.error&&a.error_description&&(console.log("IdentityManager OAuth Error: ",a.error," - ",a.error_description),"access_denied"===a.error&&(b=!0));b&&(!E("ie")||8<E("ie"))&&(window.location.hash="")}},_findCredential:function(a,b){var c=-1,d,e,m,f,k=b&&b.token;d=b&&b.resource;var n=this._isServerRsrc(a)?"server":"portal",h=g.filter(this.credentials,function(b){return this._hasSameServerInstance(b.server,
a)&&b.scope===n},this);a=d||a;if(h.length)if(1===h.length)if(d=h[0],m=(e=(f=this.findServerInfo(d.server))&&f.owningSystemUrl)&&this.findCredential(e,d.userId),c=this._getIdenticalSvcIdx(a,d),k)-1!==c&&(d.resources.splice(c,1),this._removeResource(a,m));else return-1===c&&d.resources.push(a),this._addResource(a,m),d;else{var l,r;g.some(h,function(b){r=this._getIdenticalSvcIdx(a,b);return-1!==r?(l=b,m=(e=(f=this.findServerInfo(l.server))&&f.owningSystemUrl)&&this.findCredential(e,l.userId),c=r,!0):
!1},this);if(k)l&&(l.resources.splice(c,1),this._removeResource(a,m));else if(l)return this._addResource(a,m),l}},_findOAuthInfo:function(a){var b=this.findOAuthInfo(a);b||g.some(this.oAuthInfos,function(c){this._isIdProvider(c.portalUrl,a)&&(b=c);return!!b},this);return b},_addResource:function(a,b){b&&-1===this._getIdenticalSvcIdx(a,b)&&b.resources.push(a)},_removeResource:function(a,b){var c=-1;b&&(c=this._getIdenticalSvcIdx(a,b),-1<c&&b.resources.splice(c,1))},_useProxy:function(a,b){return b&&
b.isAdmin&&!p.hasSameOrigin(a.adminTokenServiceUrl,window.location.href)||!this._isPortalDomain(a.tokenServiceUrl)&&10.1==a.currentVersion&&!p.hasSameOrigin(a.tokenServiceUrl,window.location.href)},_getOrigin:function(a){a=new w(a);return a.scheme+"://"+a.host+(u.isDefined(a.port)?":"+a.port:"")},_getServerInstanceRoot:function(a){var b=a.toLowerCase(),c=b.indexOf(this._agsRest);-1===c&&this._isAdminResource(a)&&(c=b.indexOf("/admin"));-1===c&&(c=b.indexOf("/sharing"));-1===c&&"/"===b.substr(-1)&&
(c=b.length-1);return-1<c?a.substring(0,c):a},_hasSameServerInstance:function(a,b){"/"===a.substr(-1)&&(a=a.slice(0,-1));a=a.toLowerCase();b=this._getServerInstanceRoot(b).toLowerCase();a=a.substr(a.indexOf(":"));b=b.substr(b.indexOf(":"));return a===b},_sanitizeUrl:function(a){a=p.fixUrl(n.trim(a));var b=(G.defaults.io.proxyUrl||"").toLowerCase(),c=b?a.toLowerCase().indexOf(b+"?"):-1;-1!==c&&(a=a.substring(c+b.length+1));return p.urlToObject(a).path},_isRESTService:function(a){return-1<a.indexOf(this._agsRest)},
_isAdminResource:function(a){return this._agsAdmin.test(a)||this._adminSvcs.test(a)},_isServerRsrc:function(a){return this._isRESTService(a)||this._isAdminResource(a)},_isIdenticalService:function(a,b){var c;if(this._isRESTService(a)&&this._isRESTService(b)){var d=this._getSuffix(a).toLowerCase(),e=this._getSuffix(b).toLowerCase();c=d===e;c||(c=/(.*)\/(MapServer|FeatureServer).*/ig,c=d.replace(c,"$1")===e.replace(c,"$1"))}else this._isAdminResource(a)&&this._isAdminResource(b)?c=!0:this._isServerRsrc(a)||
this._isServerRsrc(b)||!this._isPortalDomain(a)||(c=!0);return c},_isPortalDomain:function(a){a=a.toLowerCase();var b=(new w(a)).authority,c=this._portalConfig,d=-1!==b.indexOf(this._agolSuffix);!d&&c&&(d=this._hasSameServerInstance(this._getServerInstanceRoot(c.restBaseUrl),a));d||(!this._arcgisUrl&&(c=n.getObject("esri.arcgis.utils.arcgisUrl"))&&(this._arcgisUrl=(new w(c)).authority),this._arcgisUrl&&(d=this._arcgisUrl.toLowerCase()===b));d||(d=g.some(this._portals,function(b){return this._hasSameServerInstance(b,
a)},this));return d=d||this._agsPortal.test(a)},_isIdProvider:function(a,b){var c=-1,d=-1;g.forEach(this._gwDomains,function(e,g){-1===c&&e.regex.test(a)&&(c=g);-1===d&&e.regex.test(b)&&(d=g)});var e=!1;if(-1<c&&-1<d)if(0===c||4===c){if(0===d||4===d)e=!0}else if(1===c){if(1===d||2===d)e=!0}else 2===c?2===d&&(e=!0):3===c&&3===d&&(e=!0);if(!e){var m=this.findServerInfo(b),f=m&&m.owningSystemUrl;f&&I(m)&&this._isPortalDomain(f)&&this._isIdProvider(a,f)&&(e=!0)}return e},_isPublic:function(a){a=this._sanitizeUrl(a);
return g.some(this._publicUrls,function(b){return b.test(a)})},_getIdenticalSvcIdx:function(a,b){var c=-1;g.some(b.resources,function(b,e){return this._isIdenticalService(a,b)?(c=e,!0):!1},this);return c},_getSuffix:function(a){return a.replace(this._regexSDirUrl,"").replace(this._regexServerType,"$1")},_getTokenSvcUrl:function(a){var b,c;if((b=this._isRESTService(a))||this._isAdminResource(a))return c=a.toLowerCase().indexOf(b?this._agsRest:"/admin/"),b=a.substring(0,c)+"/admin/generateToken",a=
a.substring(0,c)+"/rest/info",c=x({url:a,content:{f:"json"},handleAs:"json",callbackParamName:"callback"}),c.adminUrl_=b,c;if(this._isPortalDomain(a)){var d="";g.some(this._gwDomains,function(b){b.regex.test(a)&&(d=b.tokenServiceUrl);return!!d});d||g.some(this._portals,function(b){this._hasSameServerInstance(b,a)&&(d=b+this._gwTokenUrl);return!!d},this);d||(c=a.toLowerCase().indexOf("/sharing"),-1!==c&&(d=a.substring(0,c)+this._gwTokenUrl));d||(d=this._getOrigin(a)+this._gwTokenUrl);d&&(b=(new w(a)).port,
/^http:\/\//i.test(a)&&"7080"===b&&(d=d.replace(/:7080/i,":7443")),d=d.replace(/http:/i,"https:"));return d}if(-1!==a.toLowerCase().indexOf("premium.arcgisonline.com"))return"https://premium.arcgisonline.com/server/tokens"},_getPortalSelf:function(a,b){"https:"===window.location.protocol?a=a.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(b)&&(a=a.replace(/^https:/i,"http:").replace(/:7443/i,":7080"));return x({url:a,content:{f:"json"},handleAs:"json",callbackParamName:"callback"},
{crossOrigin:!1,disableIdentityLookup:!0})},_hasPortalSession:function(){return!!this._getEsriAuthCookie()},_getEsriAuthCookie:function(){var a=null;if(F.isSupported()){var b=this._getAllCookies("esri_auth"),c;for(c=0;c<b.length;c++){var d=D.fromJson(b[c]);if(d.portalApp){a=d;break}}}a&&(b=null,a.expires&&("number"===typeof a.expires?b=a.expires:"string"===typeof a.expires&&(b=Date.parse(a.expires)),isNaN(b)&&(b=null),a.expires=b),b&&b<(new Date).getTime()&&(a=null));return a},_getAllCookies:function(a){var b=
[],c=document.cookie.match(new RegExp("(?:^|; )"+S.escapeString(a)+"\x3d([^;]*)","g"));if(c)for(a=0;a<c.length;a++){var d=c[a],e=d.indexOf("\x3d");-1<e&&(d=d.substring(e+1),b.push(decodeURIComponent(d)))}return b},_doPortalSignIn:function(a){if(F.isSupported()){var b=this._getEsriAuthCookie(),c=this._portalConfig,d=window.location.href,e=this.findServerInfo(a);if(this.useSignInPage&&(c||this._isPortalDomain(d)||b)&&(e?e.hasPortal||e.owningSystemUrl&&this._isPortalDomain(e.owningSystemUrl):this._isPortalDomain(a))&&
(this._isIdProvider(d,a)||c&&(this._hasSameServerInstance(this._getServerInstanceRoot(c.restBaseUrl),a)||this._isIdProvider(c.restBaseUrl,a))||p.hasSameOrigin(d,a,!0)))return!0}return!1},_checkProtocol:function(a,b,c,d){var e=!0;d=d?b.adminTokenServiceUrl:b.tokenServiceUrl;0!==n.trim(d).toLowerCase().indexOf("https:")||0===window.location.href.toLowerCase().indexOf("https:")||G.defaults.io.useCors&&(p.canUseXhr(d)||p.canUseXhr(p.getProxyUrl(!0).path))||(e=this._protocolFunc?!!this._protocolFunc({resourceUrl:a,
serverInfo:b}):!1,e||(a=Error("Aborted the Sign-In process to avoid sending password over insecure connection."),a.code="IdentityManagerBase.4",a.log=!!q.isDebug,console.log(a.message),c(a)));return e},_enqueue:function(a,b,c,d,e,g){d||(d=new A(M._dfdCanceller));d.resUrl_=a;d.sinfo_=b;d.options_=c;d.admin_=e;d.refresh_=g;this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(a),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(d)):
this._xoReqs.push(d):this._doSignIn(d);return d},_doSignIn:function(a){this._busy=a;var b=this,c=function(c){var d=a.options_&&a.options_.resource,h=a.resUrl_,e=a.refresh_,y=!1;-1===g.indexOf(b.credentials,c)&&(e&&-1!==g.indexOf(b.credentials,e)?(e.userId=c.userId,e.token=c.token,e.expires=c.expires,e.validity=c.validity,e.ssl=c.ssl,e.creationTime=c.creationTime,y=!0,c=e):b.credentials.push(c));c.resources||(c.resources=[]);c.resources.push(d||h);c.scope=b._isServerRsrc(h)?"server":"portal";c.onTokenChange();
var d=b._soReqs,f={};b._soReqs=[];g.forEach(d,function(a){if(!this._isIdenticalService(h,a.resUrl_)){var b=this._getSuffix(a.resUrl_);f[b]||(f[b]=!0,c.resources.push(a.resUrl_))}},b);a.callback(c);g.forEach(d,function(a){this._hasSameServerInstance(this._getServerInstanceRoot(h),a.resUrl_)?a.callback(c):this._soReqs.push(a)},b);b._busy=a.resUrl_=a.sinfo_=a.refresh_=null;if(!y)b.onCredentialCreate({credential:c});b._soReqs.length?b._doSignIn(b._soReqs.shift()):b._xoReqs.length&&b._doSignIn(b._xoReqs.shift())},
d=function(c){a.errback(c);b._busy=a.resUrl_=a.sinfo_=a.refresh_=null;b._soReqs.length?b._doSignIn(b._soReqs.shift()):b._xoReqs.length&&b._doSignIn(b._xoReqs.shift())},e=function(e,g,f,m){var h=a.sinfo_,l=!a.options_||!1!==a.options_.prompt,k=h.hasPortal&&b._findOAuthInfo(a.resUrl_);b._doPortalSignIn(a.resUrl_)?(e=b._getEsriAuthCookie(),k=b._portalConfig,e?c(new v({userId:e.email,server:h.server,token:e.token,expires:e.expires})):l?(l="",e=window.location.href,l=b.signInPage?b.signInPage:k?k.baseUrl+
k.signin:b._isIdProvider(e,a.resUrl_)?b._getOrigin(e)+"/home/signin.html":h.tokenServiceUrl.replace(b._rePortalTokenSvc,"")+"/home/signin.html",l=l.replace(/http:/i,"https:"),k&&!1===k.useSSL&&(l=l.replace(/https:/i,"http:")),0===e.toLowerCase().replace("https","http").indexOf(l.toLowerCase().replace("https","http"))?(h=Error("Cannot redirect to Sign-In page from within Sign-In page. URL of the resource that triggered this workflow: "+a.resUrl_),h.code="IdentityManagerBase.5",h.log=!!q.isDebug,d(h)):
b._redirectFunc?b._redirectFunc({signInPage:l,returnUrlParamName:"returnUrl",returnUrl:e,resourceUrl:a.resUrl_,serverInfo:h}):window.location=l+"?returnUrl\x3d"+window.escape(e)):(h=Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!q.isDebug,d(h))):e?c(new v({userId:e,server:h.server,token:f,expires:u.isDefined(m)?Number(m):null,ssl:!!g})):k?(e=k._oAuthCred,e||(g=new O(k,window.localStorage),f=new O(k,window.sessionStorage),g.isValid()&&f.isValid()?g.expires>f.expires?(e=g,f.destroy()):
(e=f,g.destroy()):e=g.isValid()?g:f,k._oAuthCred=e),e.isValid()?c(new v({userId:e.userId,server:h.server,token:e.token,expires:e.expires,ssl:e.ssl,_oAuthCred:e})):b._oAuthHash&&b._oAuthHash.state.portalUrl===k.portalUrl?(l=b._oAuthHash,h=new v({userId:l.username,server:h.server,token:l.access_token,expires:(new Date).getTime()+1E3*Number(l.expires_in),ssl:"true"===l.ssl,oAuthState:l.state,_oAuthCred:e}),e.storage=l.persist?window.localStorage:window.sessionStorage,e.token=h.token,e.expires=h.expires,
e.userId=h.userId,e.ssl=h.ssl,e.save(),b._oAuthHash=null,c(h)):l?a._pendingDfd=b.oAuthSignIn(a.resUrl_,h,k,a.options_).addCallbacks(c,d):(h=Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!q.isDebug,d(h))):l?b._checkProtocol(a.resUrl_,h,d,a.admin_)&&(l=a.options_,a.admin_&&(l=l||{},l.isAdmin=!0),a._pendingDfd=b.signIn(a.resUrl_,h,l).addCallbacks(c,d)):(h=Error("User is not signed in."),h.code="IdentityManagerBase.6",h.log=!!q.isDebug,d(h))},m=function(){var e=a.sinfo_,l=e.owningSystemUrl,
f=a.options_,k,m,n,t;f&&(k=f.token,m=f.error,n=f.prompt);t=b._findCredential(l,{token:k,resource:a.resUrl_});!t&&I(e)&&g.some(b.credentials,function(a){this._isIdProvider(l,a.server)&&(t=a);return!!t},b);t?(f=b.findCredential(a.resUrl_,t.userId))?c(f):J(e,b._legacyFed)?(f=t.toJson(),f.server=e.server,f.resources=null,c(new v(f))):(a._pendingDfd=b.generateToken(b.findServerInfo(t.server),null,{serverUrl:a.resUrl_,token:t.token,ssl:t.ssl})).addCallbacks(function(b){c(new v({userId:t.userId,server:e.server,
token:b.token,expires:u.isDefined(b.expires)?Number(b.expires):null,ssl:!!b.ssl,isAdmin:a.admin_,validity:b.validity}))},d):(b._busy=null,k&&(a.options_.token=null),(a._pendingDfd=b.getCredential(l.replace(/\/?$/,"/sharing"),{resource:a.resUrl_,owningTenant:e.owningTenant,token:k,error:m,prompt:n})).addCallbacks(function(c){b._enqueue(a.resUrl_,a.sinfo_,a.options_,a,a.admin_)},function(a){d(a)}))},f=a.sinfo_.owningSystemUrl,k=this._isServerRsrc(a.resUrl_),p=a.sinfo_._restInfoDfd;p?p.addCallbacks(function(c){var d=
a.sinfo_;d.adminTokenServiceUrl=d._restInfoDfd.adminUrl_;d._restInfoDfd=null;d.tokenServiceUrl=n.getObject("authInfo.tokenServicesUrl",!1,c)||n.getObject("authInfo.tokenServiceUrl",!1,c)||n.getObject("tokenServiceUrl",!1,c);d.shortLivedTokenValidity=n.getObject("authInfo.shortLivedTokenValidity",!1,c);d.currentVersion=c.currentVersion;d.owningTenant=c.owningTenant;(c=d.owningSystemUrl=c.owningSystemUrl)&&b._portals.push(c);k&&c?m():e()},function(){a.sinfo_._restInfoDfd=null;var b=Error("Unknown resource - could not find token service endpoint.");
b.code="IdentityManagerBase.2";b.log=!!q.isDebug;d(b)}):k&&f?m():a.sinfo_._selfReq?a.sinfo_._selfReq.selfDfd.then(function(c){var d={},e,h,f,g;c&&(e=c.user&&c.user.username,d.username=e,d.allSSL=c.allSSL,h=c.supportsOAuth,f=c.currentVersion,"multitenant"===c.portalMode&&(g=c.customBaseUrl));a.sinfo_.webTierAuth=!!e;return e&&b.normalizeWebTierAuth?b.generateToken(a.sinfo_,null,{ssl:d.allSSL}).addBoth(function(a){d.portalToken=a&&a.token;d.tokenExpiration=a&&a.expires;return d}):!e&&h&&4.4<=parseFloat(f)&&
!b._doPortalSignIn(a.resUrl_)?b._generateOAuthInfo({portalUrl:a.sinfo_.server,customBaseUrl:g,owningTenant:a.sinfo_._selfReq.owningTenant}).always(function(){return d}):d}).always(function(b){a.sinfo_._selfReq=null;b?e(b.username,b.allSSL,b.portalToken,b.tokenExpiration):e()}):e()},_generateOAuthInfo:function(a){var b=this,c,d=a.portalUrl,e=a.customBaseUrl,g=a.owningTenant;if(a=!this.defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal){c=window.location.href;var f=c.indexOf("?");
-1<f&&(c=c.slice(0,f));f=c.search(/\/(apps|home)\//);c=-1<f?c.slice(0,f):null}a&&c?(this._hasTestedIfAppIsOnPortal=!0,a=x({url:c+"/sharing/rest",content:{f:"json"},handleAs:"json"}).then(function(){b.defaultOAuthInfo=new P({appId:"arcgisonline",popup:!0,popupCallbackUrl:c+"/home/oauth-callback.html"})})):(a=new A,a.resolve(),a=a.promise);return a.then(function(){if(b.defaultOAuthInfo)return d=d.replace(/^http:/i,"https:"),x({url:d+"/sharing/rest/oauth2/validateRedirectUri",content:{accountId:g,client_id:b.defaultOAuthInfo.appId,
redirect_uri:p.getAbsoluteUrl(b.defaultOAuthInfo.popupCallbackUrl),f:"json"},handleAs:"json",callbackParamName:"callback"}).then(function(a){if(a.valid){var c=b.defaultOAuthInfo.clone();c.portalUrl=a.urlKey&&e?"https://"+a.urlKey+"."+e:d;b.oAuthInfos.push(c)}})})}});v=L(N,{declaredClass:"esri.Credential",tokenRefreshBuffer:2,constructor:function(a){n.mixin(this,a);this.resources=this.resources||[];u.isDefined(this.creationTime)||(this.creationTime=(new Date).getTime())},_oAuthCred:null,refreshToken:function(){var a=
this,b=this.resources&&this.resources[0],c=m.id.findServerInfo(this.server),d=c&&c.owningSystemUrl,e=!!d&&"server"===this.scope,n=e&&J(c,m.id._legacyFed),f=e&&m.id.findServerInfo(d),k,p=(k=c.webTierAuth)&&m.id.normalizeWebTierAuth,h=B[this.server],h=h&&h[this.userId],l={username:this.userId,password:h},r;if(!k||p)if(e&&!f&&g.some(m.id.serverInfos,function(a){m.id._isIdProvider(d,a.server)&&(f=a);return!!f}),k=f&&m.id.findCredential(f.server,this.userId),!e||k)if(n)k.refreshToken();else{if(e)r={serverUrl:b,
token:k&&k.token,ssl:k&&k.ssl};else if(p)l=null,r={ssl:this.ssl};else if(h)this.isAdmin&&(r={isAdmin:!0});else{var q;b&&(b=m.id._sanitizeUrl(b),this._enqueued=1,q=m.id._enqueue(b,c,null,null,this.isAdmin,this),q.addCallback(function(){a._enqueued=0;a.refreshServerTokens()}).addErrback(function(){a._enqueued=0}));return q}return m.id.generateToken(e?f:c,e?null:l,r).addCallback(function(b){a.token=b.token;a.expires=u.isDefined(b.expires)?Number(b.expires):null;a.creationTime=(new Date).getTime();a.validity=
b.validity;a.onTokenChange();a.refreshServerTokens()}).addErrback(function(){})}},refreshServerTokens:function(){"portal"===this.scope&&g.forEach(m.id.credentials,function(a){var b=m.id.findServerInfo(a.server),c=b&&b.owningSystemUrl;a!==this&&a.userId===this.userId&&c&&"server"===a.scope&&(m.id._hasSameServerInstance(this.server,c)||m.id._isIdProvider(c,this.server))&&(J(b,m.id._legacyFed)?(a.token=this.token,a.expires=this.expires,a.creationTime=this.creationTime,a.validity=this.validity,a.onTokenChange()):
a.refreshToken())},this)},onTokenChange:function(a){clearTimeout(this._refreshTimer);var b=this.server&&m.id.findServerInfo(this.server),c=(b=b&&b.owningSystemUrl)&&m.id.findServerInfo(b);!1!==a&&(!b||"portal"===this.scope||c&&c.webTierAuth&&!m.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 a=g.indexOf(m.id.credentials,this);-1<a&&m.id.credentials.splice(a,1);this.onTokenChange();this.onDestroy()},toJson:function(){return this._toJson()},_toJson:function(){var a=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}),b=this.resources;b&&0<b.length&&(a.resources=b.slice());return a},_startRefreshTimer:function(){clearTimeout(this._refreshTimer);
var a=6E4*this.tokenRefreshBuffer,b=(this.validity?this.creationTime+6E4*this.validity:this.expires)-(new Date).getTime();0>b&&(b=0);this._refreshTimer=setTimeout(n.hitch(this,this.refreshToken),b>a?b-a:b)}});K.Credential=v;E("extend-esri")&&(m.IdentityManagerBase=K);return K});