IdentityManagerBase.js 26.6 KB
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.6/esri/copyright.txt for details.
//>>built
define("../core/declare dojo/_base/config dojo/_base/lang dojo/_base/array dojo/Deferred dojo/_base/url dojo/sniff dojo/cookie dojo/io-query dojo/regexp ../kernel ../config ../core/lang ./ServerInfo ../core/urlUtils ../core/deferredUtils ../core/Accessor ../request ../core/Error ../core/Evented ./OAuthCredential ./OAuthInfo".split(" "),function(z,N,q,h,O,w,H,C,P,Q,p,D,v,E,r,I,R,y,u,J,K,L){var A={},F=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)},G=function(a,b){return!!(F(a)&&b&&h.some(b,function(b){return b.test(a.server)}))},t;z=z(J,{declaredClass:"esri.identity.IdentityManagerBase",constructor:function(){this._portalConfig=q.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|SceneServer)).*/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=h.filter(a,function(a){return!this.findServerInfo(a.server)},this),this.serverInfos=b.concat(a)):this.serverInfos=a;h.forEach(a,function(a){a.owningSystemUrl&&
this._portals.push(a.owningSystemUrl);if(a.hasPortal){this._portals.push(a.server);var b=D.request.corsEnabledServers,c=this._getOrigin(a.tokenServiceUrl);r.canUseXhr(a.server)||b.push(a.server.replace(/^https?:\/\//i,""));r.canUseXhr(c)||b.push(c.replace(/^https?:\/\//i,""))}},this)},registerOAuthInfos:function(a){var b=this.oAuthInfos;b?(a=h.filter(a,function(a){return!this.findOAuthInfo(a.portalUrl)},this),this.oAuthInfos=b.concat(a)):this.oAuthInfos=a},registerToken:function(a){a=q.mixin({},a);
var b=this._sanitizeUrl(a.server),c=this.findServerInfo(b),d=this._isServerRsrc(b),e=!0,k;c||(c=new E,c.server=this._getServerInstanceRoot(b),d?c.hasServer=!0:(c.tokenServiceUrl=this._getTokenSvcUrl(b),c.hasPortal=!0),this.registerServers([c]));(k=this._findCredential(b))?(delete a.server,q.mixin(k,a),e=!1):(k=new t({userId:a.userId,server:c.server,token:a.token,expires:a.expires,ssl:a.ssl,scope:d?"server":"portal"}),k.resources=[b],this.credentials.push(k));k.emitTokenChange(!1);e||k.refreshServerTokens()},
toJSON:function(){return v.fixJson({serverInfos:h.map(this.serverInfos,function(a){return a.toJSON()}),oAuthInfos:h.map(this.oAuthInfos,function(a){return a.toJSON()}),credentials:h.map(this.credentials,function(a){return a.toJSON()})})},initialize:function(a){if(a){q.isString(a)&&(a=JSON.parse(a));var b=a.serverInfos,c=a.oAuthInfos;a=a.credentials;if(b){var d=[];h.forEach(b,function(a){a.server&&a.tokenServiceUrl&&d.push(a.declaredClass?a:new E(a))});d.length&&this.registerServers(d)}if(c){var e=
[];h.forEach(c,function(a){a.appId&&e.push(a.declaredClass?a:new L(a))});e.length&&this.registerOAuthInfos(e)}a&&h.forEach(a,function(a){a.server&&a.token&&a.expires&&a.expires>(new Date).getTime()&&(a=a.declaredClass?a:new t(a),a.emitTokenChange(),this.credentials.push(a))},this)}},findServerInfo:function(a){var b;a=this._sanitizeUrl(a);h.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);
h.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?h.some(this.credentials,function(e){this._hasSameServerInstance(e.server,a)&&b===e.userId&&e.scope===d&&(c=e);return!!c},this):h.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;v.isDefined(b)&&(q.isObject(b)?(c=!!b.token,d=b.error,e=!1!==b.prompt):c=b);a=this._sanitizeUrl(a);var k=I.makeDeferredCancellingPending(),g=this._isAdminResource(a),l=c&&this._doPortalSignIn(a)?this._getEsriAuthCookie():null;if((c=c?this.findCredential(a):null)&&d&&498===d.code)c.destroy(),l&&l.token===b.token&&C("esri_auth",null,{expires:-1,path:"/",domain:document.domain});else if(l||c)return a=new u("identity-manager:not-authorized","You are currently signed in as: '"+
(l&&l.email||c&&c.userId)+"'. You do not have access to this resource: "+a,{error:d}),k.reject(a),k.promise;if(d=this._findCredential(a,b))return k.resolve(d),k.promise;d=this.findServerInfo(a);if(d)!d.hasServer&&this._isServerRsrc(a)&&(d._restInfoPms=this._getTokenSvcUrl(a),d.hasServer=!0);else{l=this._getTokenSvcUrl(a);if(!l)return a=new u("identity-manager:unknown-resource","Unknown resource - could not find token service endpoint."),k.reject(a),k.promise;d=new E;d.server=this._getServerInstanceRoot(a);
q.isString(l)?(d.tokenServiceUrl=l,d.hasPortal=!0):(d._restInfoPms=l,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,k,g)},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,k,g,l,h,f=this._rePortalTokenSvc.test(a.tokenServiceUrl),x=new w(window.location.href.toLowerCase()),M=this._getEsriAuthCookie(),B,m=!b;g=a.shortLivedTokenValidity;var n;b&&(n=p.id.tokenValidity||g||p.id.defaultTokenValidity,n>g&&0<g&&(n=g));c&&(d=c.isAdmin,e=c.serverUrl,k=c.token,h=c.ssl,a.customParameters=c.customParameters);
d?g=a.adminTokenServiceUrl:(g=a.tokenServiceUrl,l=new w(g.toLowerCase()),M&&(B=(B=M.auth_tier)&&B.toLowerCase()),("web"===B||a.webTierAuth)&&c&&c.serverUrl&&!h&&"http"===x.scheme&&(r.hasSameOrigin(x.uri,g,!0)||"https"===l.scheme&&x.host===l.host&&"7080"===x.port&&"7443"===l.port)&&(g=g.replace(/^https:/i,"http:").replace(/:7443/i,":7080")),m&&f&&(g=g.replace(/\/rest/i,"")));c=q.mixin({query:q.mixin({request:"getToken",username:b&&b.username,password:b&&b.password,serverUrl:e,token:k,expiration:n,
referer:d||f?window.location.host:null,client:d?"referer":null,f:"json"},a.customParameters),method:m?"auto":"post",authMode:"anonymous",useProxy:this._useProxy(a,c),responseType:"json",callbackParamName:m?"callback":void 0},c&&c.ioArgs);f||(c.withCredentials=!1);return y(g,c).then(function(c){c=c.data;if(!c||!c.token)return new u("identity-manager:authentication-failed","Unable to generate token");var d=a.server;A[d]||(A[d]={});b&&(A[d][b.username]=b.password);c.validity=n;return c})},isBusy:function(){return!!this._busy},
checkSignInStatus:function(a){return this.getCredential(a,{prompt:!1}).then(function(a){return a.token?y(a.server+("portal"===a.scope?"/sharing/rest":"/rest/services"),{query:{f:"json",token:a.token},callbackParamName:"callback",authMode:"anonymous"}).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=!!N.isDebug,b;return a}):a})},setRedirectionHandler:function(a){this._redirectFunc=a},setProtocolErrorHandler:function(a){this._protocolFunc=
a},signIn:function(){},oAuthSignIn:function(){},destroyCredentials:function(){if(this.credentials){var a=this.credentials.slice();h.forEach(a,function(a){a.destroy()})}this.emit("credentials-destroy")},_getOAuthHash:function(){var a=window.location.hash;if(a){"#"===a.charAt(0)&&(a=a.substring(1));var a=P.queryToObject(a),b=!1;a.access_token&&a.expires_in&&a.state&&a.hasOwnProperty("username")?(a.state=JSON.parse(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&&(!H("ie")||8<H("ie"))&&(window.location.hash="")}},_findCredential:function(a,b){var c=-1,d,e,k,g=b&&b.token;b=b&&b.resource;var l=this._isServerRsrc(a)?"server":"portal",p=h.filter(this.credentials,function(b){return this._hasSameServerInstance(b.server,a)&&b.scope===l},this);a=b||a;if(p.length)if(1===p.length)if(b=p[0],e=(d=(k=this.findServerInfo(b.server))&&k.owningSystemUrl)&&this.findCredential(d,b.userId),c=this._getIdenticalSvcIdx(a,
b),g)-1!==c&&(b.resources.splice(c,1),this._removeResource(a,e));else return-1===c&&b.resources.push(a),this._addResource(a,e),b;else{var f,x;h.some(p,function(b){x=this._getIdenticalSvcIdx(a,b);return-1!==x?(f=b,e=(d=(k=this.findServerInfo(f.server))&&k.owningSystemUrl)&&this.findCredential(d,f.userId),c=x,!0):!1},this);if(g)f&&(f.resources.splice(c,1),this._removeResource(a,e));else if(f)return this._addResource(a,e),f}},_findOAuthInfo:function(a){var b=this.findOAuthInfo(a);b||h.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&&!r.hasSameOrigin(a.adminTokenServiceUrl,window.location.href)||!this._isPortalDomain(a.tokenServiceUrl)&&10.1==a.currentVersion&&!r.hasSameOrigin(a.tokenServiceUrl,window.location.href)},
_getOrigin:function(a){a=new w(a);return a.scheme+"://"+a.host+(v.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=r.normalize(q.trim(a));var b=(D.request.proxyUrl||"").toLowerCase(),c=b?a.toLowerCase().indexOf(b+"?"):-1;-1!==c&&(a=a.substring(c+b.length+1));return r.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;this._isRESTService(a)&&this._isRESTService(b)?(a=this._getSuffix(a).toLowerCase(),b=this._getSuffix(b).toLowerCase(),c=a===b,c||(c=/(.*)\/(MapServer|FeatureServer).*/ig,c=a.replace(c,"$1")===b.replace(c,"$1"))):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=q.getObject("esri.arcgis.utils.arcgisUrl"))&&(this._arcgisUrl=(new w(c)).authority),this._arcgisUrl&&(d=this._arcgisUrl.toLowerCase()===b));d||(d=h.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;h.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 k=this.findServerInfo(b),g=k&&k.owningSystemUrl;g&&F(k)&&this._isPortalDomain(g)&&this._isIdProvider(a,g)&&(e=!0)}return e},_isPublic:function(a){a=this._sanitizeUrl(a);return h.some(this._publicUrls,function(b){return b.test(a)})},_getIdenticalSvcIdx:function(a,b){var c=-1;h.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=y(a,{query:{f:"json"},responseType:"json",callbackParamName:"callback"}).then(function(a){return a.data}),{adminUrl:b,promise:c};if(this._isPortalDomain(a)){var d=
"";h.some(this._gwDomains,function(b){b.regex.test(a)&&(d=b.tokenServiceUrl);return!!d});d||h.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 y(a,{query:{f:"json"},responseType:"json",callbackParamName:"callback",crossOrigin:!1,authMode:"anonymous"}).then(function(a){return a.data})},_hasPortalSession:function(){return!!this._getEsriAuthCookie()},_getEsriAuthCookie:function(){var a=null;if(C.isSupported()){var b=this._getAllCookies("esri_auth"),
c;for(c=0;c<b.length;c++){var d=JSON.parse(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<Date.now()&&(a=null));return a},_getAllCookies:function(a){var b=[],c=document.cookie.match(new RegExp("(?:^|; )"+Q.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(C.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))||r.hasSameOrigin(d,a,!0)))return!0}return!1},_checkProtocol:function(a,
b,c,d){var e=!0;d=d?b.adminTokenServiceUrl:b.tokenServiceUrl;0!==q.trim(d).toLowerCase().indexOf("https:")||0===window.location.href.toLowerCase().indexOf("https:")||D.request.useCors&&(r.canUseXhr(d)||r.canUseXhr(r.getProxyUrl(!0).path))||(e=this._protocolFunc?!!this._protocolFunc({resourceUrl:a,serverInfo:b}):!1,e||(a=new u("identity-manager:aborted","Aborted the Sign-In process to avoid sending password over insecure connection."),c(a)));return e},_enqueue:function(a,b,c,d,e,k){d||(d=I.makeDeferredCancellingPending());
d.resUrl_=a;d.sinfo_=b;d.options_=c;d.admin_=e;d.refresh_=k;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.promise},_doSignIn:function(a){this._busy=a;var b=this,c=function(c){var d=a.options_&&a.options_.resource,f=a.resUrl_,e=a.refresh_,m=!1;-1===h.indexOf(b.credentials,c)&&(e&&-1!==h.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,m=!0,c=e):b.credentials.push(c));c.resources||(c.resources=[]);c.resources.push(d||f);c.scope=b._isServerRsrc(f)?"server":"portal";c.emitTokenChange();var d=b._soReqs,g={};b._soReqs=[];h.forEach(d,function(a){if(!this._isIdenticalService(f,a.resUrl_)){var b=this._getSuffix(a.resUrl_);g[b]||(g[b]=!0,c.resources.push(a.resUrl_))}},b);a.resolve(c);h.forEach(d,function(a){this._hasSameServerInstance(this._getServerInstanceRoot(f),
a.resUrl_)?a.resolve(c):this._soReqs.push(a)},b);b._busy=a.resUrl_=a.sinfo_=a.refresh_=null;m||b.emit("credential-create",{credential:c});b._soReqs.length?b._doSignIn(b._soReqs.shift()):b._xoReqs.length&&b._doSignIn(b._xoReqs.shift())},d=function(c){a.reject(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(f,e,g,k){var m=a.sinfo_,n=!a.options_||!1!==a.options_.prompt,h=m.hasPortal&&b._findOAuthInfo(a.resUrl_);
b._doPortalSignIn(a.resUrl_)?(f=b._getEsriAuthCookie(),h=b._portalConfig,f?(m.webTierAuth||"web"!==(f.auth_tier&&f.auth_tier.toLowerCase())||(m.webTierAuth=!0),c(new t({userId:f.email,server:m.server,token:f.token,expires:f.expires}))):n?(n="",f=window.location.href,n=b.signInPage?b.signInPage:h?h.baseUrl+h.signin:b._isIdProvider(f,a.resUrl_)?b._getOrigin(f)+"/home/signin.html":m.tokenServiceUrl.replace(b._rePortalTokenSvc,"")+"/home/signin.html",n=n.replace(/http:/i,"https:"),h&&!1===h.useSSL&&(n=
n.replace(/https:/i,"http:")),0===f.toLowerCase().replace("https","http").indexOf(n.toLowerCase().replace("https","http"))?(m=new u("identity-manager:unexpected-error","Cannot redirect to Sign-In page from within Sign-In page. URL of the resource that triggered this workflow: "+a.resUrl_),d(m)):b._redirectFunc?b._redirectFunc({signInPage:n,returnUrlParamName:"returnUrl",returnUrl:f,resourceUrl:a.resUrl_,serverInfo:m}):window.location=n+"?returnUrl\x3d"+window.escape(f)):(m=new u("identity-manager:not-authenticated",
"User is not signed in."),d(m))):f?c(new t({userId:f,server:m.server,token:g,expires:v.isDefined(k)?Number(k):null,ssl:!!e})):h?(f=h._oAuthCred,f||(e=new K(h,window.localStorage),g=new K(h,window.sessionStorage),e.isValid()&&g.isValid()?e.expires>g.expires?(f=e,g.destroy()):(f=g,e.destroy()):f=e.isValid()?e:g,h._oAuthCred=f),f.isValid()?c(new t({userId:f.userId,server:m.server,token:f.token,expires:f.expires,ssl:f.ssl,_oAuthCred:f})):b._oAuthHash&&b._oAuthHash.state.portalUrl===h.portalUrl?(n=b._oAuthHash,
m=new t({userId:n.username,server:m.server,token:n.access_token,expires:(new Date).getTime()+1E3*Number(n.expires_in),ssl:"true"===n.ssl,oAuthState:n.state,_oAuthCred:f}),f.storage=n.persist?window.localStorage:window.sessionStorage,f.token=m.token,f.expires=m.expires,f.userId=m.userId,f.ssl=m.ssl,f.save(),b._oAuthHash=null,c(m)):n?a._pendingDfd=b.oAuthSignIn(a.resUrl_,m,h,a.options_).then(c,d):(m=new u("identity-manager:not-authenticated","User is not signed in."),d(m))):n?b._checkProtocol(a.resUrl_,
m,d,a.admin_)&&(n=a.options_,a.admin_&&(n=n||{},n.isAdmin=!0),a._pendingDfd=b.signIn(a.resUrl_,m,n).then(c,d)):(m=new u("identity-manager:not-authenticated","User is not signed in."),d(m))},k=function(){var f=a.sinfo_,e=f.owningSystemUrl,g=a.options_,k,m,n,l;g&&(k=g.token,m=g.error,n=g.prompt);l=b._findCredential(e,{token:k,resource:a.resUrl_});!l&&F(f)&&h.some(b.credentials,function(a){this._isIdProvider(e,a.server)&&(l=a);return!!l},b);l?(g=b.findCredential(a.resUrl_,l.userId))?c(g):G(f,b._legacyFed)?
(g=l.toJSON(),g.server=f.server,g.resources=null,c(new t(g))):(a._pendingDfd=b.generateToken(b.findServerInfo(l.server),null,{serverUrl:a.resUrl_,token:l.token,ssl:l.ssl})).then(function(b){c(new t({userId:l.userId,server:f.server,token:b.token,expires:v.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(e.replace(/\/?$/,"/sharing"),{resource:a.resUrl_,owningTenant:f.owningTenant,
token:k,error:m,prompt:n})).then(function(c){b._enqueue(a.resUrl_,a.sinfo_,a.options_,a,a.admin_)},function(a){d(a)}))},g=a.sinfo_.owningSystemUrl,l=this._isServerRsrc(a.resUrl_),p=a.sinfo_._restInfoPms;p?p.promise.then(function(c){var d=a.sinfo_;d.adminTokenServiceUrl=d._restInfoPms.adminUrl;d._restInfoPms=null;d.tokenServiceUrl=q.getObject("authInfo.tokenServicesUrl",!1,c)||q.getObject("authInfo.tokenServiceUrl",!1,c)||q.getObject("tokenServiceUrl",!1,c);d.shortLivedTokenValidity=q.getObject("authInfo.shortLivedTokenValidity",
!1,c);d.currentVersion=c.currentVersion;d.owningTenant=c.owningTenant;(c=d.owningSystemUrl=c.owningSystemUrl)&&b._portals.push(c);l&&c?k():e()},function(){a.sinfo_._restInfoPms=null;var b=new u("identity-manager:server-identification-failed","Unknown resource - could not find token service endpoint.");d(b)}):l&&g?k():a.sinfo_._selfReq?a.sinfo_._selfReq.selfDfd.then(function(c){var d={},e,f,g,h;c&&(e=c.user&&c.user.username,d.username=e,d.allSSL=c.allSSL,f=c.supportsOAuth,g=c.currentVersion,"multitenant"===
c.portalMode&&(h=c.customBaseUrl));a.sinfo_.webTierAuth=!!e;return e&&b.normalizeWebTierAuth?b.generateToken(a.sinfo_,null,{ssl:d.allSSL}).always(function(a){d.portalToken=a&&a.token;d.tokenExpiration=a&&a.expires;return d}):!e&&f&&4.4<=parseFloat(g)&&!b._doPortalSignIn(a.resUrl_)?b._generateOAuthInfo({portalUrl:a.sinfo_.server,customBaseUrl:h,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,h=a.owningTenant;if(a=!this.defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal){c=window.location.href;var g=c.indexOf("?");-1<g&&(c=c.slice(0,g));g=c.search(/\/(apps|home)\//);c=-1<g?c.slice(0,g):null}a&&c?(this._hasTestedIfAppIsOnPortal=!0,a=y(c+"/sharing/rest",{query:{f:"json"},responseType:"json"}).then(function(){b.defaultOAuthInfo=new L({appId:"arcgisonline",
popup:!0,popupCallbackUrl:c+"/home/oauth-callback.html"})})):(a=new O,a.resolve(),a=a.promise);return a.then(function(){if(b.defaultOAuthInfo)return d=d.replace(/^http:/i,"https:"),y(d+"/sharing/rest/oauth2/validateRedirectUri",{query:{accountId:h,client_id:b.defaultOAuthInfo.appId,redirect_uri:r.makeAbsolute(b.defaultOAuthInfo.popupCallbackUrl),f:"json"},responseType:"json",callbackParamName:"callback"}).then(function(a){if(a.data.valid){var c=b.defaultOAuthInfo.clone();c.portalUrl=a.data.urlKey&&
e?"https://"+a.data.urlKey+"."+e:d;b.oAuthInfos.push(c)}})})}});t=R.createSubclass([J],{declaredClass:"esri.identity.Credential",constructor:function(a){a&&a._oAuthCred&&(this._oAuthCred=a._oAuthCred)},initialize:function(){this.resources=this.resources||[];v.isDefined(this.creationTime)||(this.creationTime=(new Date).getTime())},_oAuthCred:null,properties:{creationTime:{},expires:{},isAdmin:{},oAuthState:{},resources:{},scope:{},server:{},ssl:{},token:{},tokenRefreshBuffer:2,userId:{},validity:{}},
refreshToken:function(){var a=this,b=this.resources&&this.resources[0],c=p.id.findServerInfo(this.server),d=c&&c.owningSystemUrl,e=!!d&&"server"===this.scope,k=e&&G(c,p.id._legacyFed),g=e&&p.id.findServerInfo(d),l,q=(l=c.webTierAuth)&&p.id.normalizeWebTierAuth,f=A[this.server],f=f&&f[this.userId],r={username:this.userId,password:f},t;if(!l||q)if(e&&!g&&h.some(p.id.serverInfos,function(a){p.id._isIdProvider(d,a.server)&&(g=a);return!!g}),l=g&&p.id.findCredential(g.server,this.userId),!e||l)if(k)l.refreshToken();
else{if(e)t={serverUrl:b,token:l&&l.token,ssl:l&&l.ssl};else if(q)r=null,t={ssl:this.ssl};else if(f)this.isAdmin&&(t={isAdmin:!0});else{var u;b&&(b=p.id._sanitizeUrl(b),this._enqueued=1,u=p.id._enqueue(b,c,null,null,this.isAdmin,this),u.then(function(){a._enqueued=0;a.refreshServerTokens()}).then(null,function(){a._enqueued=0}));return u}return p.id.generateToken(e?g:c,e?null:r,t).then(function(b){a.token=b.token;a.expires=v.isDefined(b.expires)?Number(b.expires):null;a.creationTime=(new Date).getTime();
a.validity=b.validity;a.emitTokenChange();a.refreshServerTokens()}).then(null,function(){})}},refreshServerTokens:function(){"portal"===this.scope&&h.forEach(p.id.credentials,function(a){var b=p.id.findServerInfo(a.server),c=b&&b.owningSystemUrl;a!==this&&a.userId===this.userId&&c&&"server"===a.scope&&(p.id._hasSameServerInstance(this.server,c)||p.id._isIdProvider(c,this.server))&&(G(b,p.id._legacyFed)?(a.token=this.token,a.expires=this.expires,a.creationTime=this.creationTime,a.validity=this.validity,
a.emitTokenChange()):a.refreshToken())},this)},emitTokenChange:function(a){clearTimeout(this._refreshTimer);var b=this.server&&p.id.findServerInfo(this.server),c=(b=b&&b.owningSystemUrl)&&p.id.findServerInfo(b);!1!==a&&(!b||"portal"===this.scope||c&&c.webTierAuth&&!p.id.normalizeWebTierAuth)&&(v.isDefined(this.expires)||v.isDefined(this.validity))&&this._startRefreshTimer();this.emit("token-change")},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=h.indexOf(p.id.credentials,this);-1<a&&p.id.credentials.splice(a,1);this.emitTokenChange();this.emit("destroy")},toJSON:function(){var a=v.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(q.hitch(this,this.refreshToken),b>a?b-a:b)}});z.Credential=t;return z});