Skip to content

Commit

Permalink
feat: remember authenticated redirect URL after login (#7832)
Browse files Browse the repository at this point in the history
* feat: remember authenticated redirect URL after login

* feat: remember authenticated redirect URL after login
  • Loading branch information
kamranahmedse authored Dec 3, 2024
1 parent a81c435 commit 4c05f13
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/components/Authenticator/authenticator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import Cookies from 'js-cookie';
import { TOKEN_COOKIE_NAME } from '../../lib/jwt';

export const REDIRECT_PAGE_AFTER_AUTH = 'redirect_page_after_auth';

function easeInElement(el: Element) {
el.classList.add('opacity-0', 'transition-opacity', 'duration-300');
el.classList.remove('hidden');
Expand Down Expand Up @@ -56,7 +58,8 @@ function handleGuest() {

// If the user is on an authenticated route, redirect them to the home page
if (authenticatedRoutes.includes(window.location.pathname)) {
window.location.href = '/';
localStorage.setItem(REDIRECT_PAGE_AFTER_AUTH, window.location.pathname);
window.location.href = '/login';
}
}

Expand Down Expand Up @@ -86,6 +89,14 @@ function handleAuthenticated() {
export function handleAuthRequired() {
const token = Cookies.get(TOKEN_COOKIE_NAME);
if (token) {
const pageAfterAuth = localStorage.getItem(REDIRECT_PAGE_AFTER_AUTH);
if (pageAfterAuth) {
localStorage.removeItem(REDIRECT_PAGE_AFTER_AUTH);
window.location.href = pageAfterAuth;

return;
}

handleAuthenticated();
} else {
handleGuest();
Expand Down
4 changes: 3 additions & 1 deletion src/components/Navigation/navigation.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import Cookies from 'js-cookie';
import { TOKEN_COOKIE_NAME, removeAuthToken } from '../../lib/jwt';
import { REDIRECT_PAGE_AFTER_AUTH } from '../Authenticator/authenticator.ts';

export function logout() {
localStorage.removeItem(REDIRECT_PAGE_AFTER_AUTH);
removeAuthToken();

// Reloading will automatically redirect the user if required
window.location.reload();
window.location.href = '/';
}

function bindEvents() {
Expand Down

0 comments on commit 4c05f13

Please sign in to comment.