Redirect user to previously visited page after login When a user logs in from any page, it expectes to be back on the same page after the successful login. Gerrit's `/login` endpoint already supports redirecting to the previously visited page, but that information was not forwarded from the frontend. To update the `href` in the login URL, we need to subscribe for `nav-report` events. But as the event is emitted, before `window.location` is updated, we also need to delay reading of the current browser URL, until all other events are processed. This way, by using `setTimeout`, we can reliably update the login link `href`. But: Issue 325838103 Change-Id: Icc6498b48fac011a2bc2e92700ff216d781eb993
diff --git a/github-plugin/src/main/ts/gr-github-oauth-progress.ts b/github-plugin/src/main/ts/gr-github-oauth-progress.ts index 3b53d47..8ed9e07 100644 --- a/github-plugin/src/main/ts/gr-github-oauth-progress.ts +++ b/github-plugin/src/main/ts/gr-github-oauth-progress.ts
@@ -14,6 +14,8 @@ @state() loggedIn?: boolean + @state() currentNavigationPath?: string; + override connectedCallback() { super.connectedCallback(); const restApi = this.plugin.restApi(); @@ -21,6 +23,13 @@ restApi.getConfig().then(config => this.authInfo = config?.auth); } restApi.getLoggedIn().then(loggedIn => this.loggedIn = loggedIn); + document.addEventListener( + 'nav-report', + // the `nav-report` event is emitted before `window.location` is updated, in order + // to get the current location, we need to delay `this.updateLocationPath` execution + // by putting it on the end of processing queue + () => setTimeout(() => this.updateLocationPath(), 0)); + this.updateLocationPath(); } static override get styles() { @@ -52,9 +61,13 @@ if (!this.authInfo || this.loggedIn !== false) { return } + const loginWithRedirect = new URL(this.authInfo.login_url ?? "/", window.location.origin); + if (this.currentNavigationPath) { + loginWithRedirect.pathname = loginWithRedirect.pathname + this.currentNavigationPath; + } return html` - <a class="loginButton" href=${this.authInfo.login_url} @click=${this.showModal}> + <a class="loginButton" href="${loginWithRedirect}" @click=${this.showModal}> ${this.authInfo.login_text} </a> <dialog id="gitHubOAuthProgress"> @@ -66,6 +79,10 @@ ` } + private updateLocationPath() { + this.currentNavigationPath = window.location.pathname; + } + private showModal() { setTimeout(() => this.gitHubOAuthProgress?.showModal(), 550); }