Skip to content

Commit

Permalink
Handle better AuthProvider logout (#273)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesPeck authored Oct 25, 2024
1 parent 716f169 commit 0611bfb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
28 changes: 17 additions & 11 deletions src/lib/stores/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,25 +150,31 @@ export async function logout(authProvider?: AuthProvider, redirect = false) {
if (authProvider) {
authProvider
.logout()
.then((redirect) => {
user.set({});
if (typeof redirect === 'string') {
location.replace(redirect);
.then((redirectURL) => {
if (typeof redirectURL === 'string') {
user.set({});
location.replace(redirectURL);
} else {
// If no redirect is provided, go to the login page
console.error('Error logging out: ' + redirect);
goto('/login');
console.error('Error logging out: ' + redirectURL);
handleLogout(redirect);
}
})
.catch((error) => {
console.error('Error logging out: ' + error);
goto('/login');
handleLogout(redirect);
});
} else {
user.set({});
redirect
? goto(`/login?redirectTo=${encodeURIComponent(get(page).url.pathname)}`)
: goto('/login');
handleLogout(redirect);
}
}

function handleLogout(redirect: boolean) {
user.set({});
if (redirect) {
goto(`/login?redirectTo=${encodeURIComponent(get(page).url.pathname)}`);
} else {
goto('/login');
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/routes/(picsure)/+layout.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { LayoutLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { features } from '$lib/configuration';
import { isTokenExpired } from '$lib/stores/User';
import { isTokenExpired, user } from '$lib/stores/User';
import { browser } from '$app/environment';

export const load: LayoutLoad = ({ url }) => {
Expand All @@ -10,6 +10,7 @@ export const load: LayoutLoad = ({ url }) => {
browser &&
(!localStorage.getItem('token') || isTokenExpired(localStorage.getItem('token') || ''))
) {
user.set({});
throw redirect(302, `/login?redirectTo=${url.pathname}`);
}
};

0 comments on commit 0611bfb

Please sign in to comment.