Skip to content

Commit

Permalink
Merge pull request #61 from manchenkoff/44-bug-incorrect-redirect-on-…
Browse files Browse the repository at this point in the history
…login-if-response-is-401

fix: prevent redirects to the same page
  • Loading branch information
manchenkoff authored Mar 31, 2024
2 parents 8c3c5c3 + 9166a5b commit e19f1a7
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 39 deletions.
17 changes: 6 additions & 11 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
export default defineNuxtConfig({
modules: ['../src/module'],
devtools: { enabled: true },
ssr: true,
typescript: {
strict: true,
typeCheck: true,
},
ssr: true,
runtimeConfig: {
public: {
sanctum: {
baseUrl: 'http://localhost:80',
userStateKey: 'sanctum.user.identity',
},
},
},

modules: ['../src/module'],

sanctum: {
baseUrl: 'http://localhost:80',
redirect: {
keepRequestedRoute: true,
onAuthOnly: '/login',
Expand All @@ -28,5 +24,4 @@ export default defineNuxtConfig({
user: '/api/user',
},
},
devtools: { enabled: true },
});
51 changes: 36 additions & 15 deletions src/runtime/composables/useSanctumAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,23 @@ export const useSanctumAuth = <T>(): SanctumAuth<T> => {
* @param credentials Credentials to pass to the login endpoint
*/
async function login(credentials: Record<string, any>) {
const currentRoute = useRoute();

if (isAuthenticated.value === true) {
if (options.redirectIfAuthenticated === false) {
throw new Error('User is already authenticated');
}

if (options.redirect.onLogin === false) {
if (
options.redirect.onLogin === false ||
options.redirect.onLogin === currentRoute.path
) {
return;
}

const redirect = options.redirect.onLogin as string;

await nuxtApp.runWithContext(() => navigateTo(redirect));
await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onLogin as string)
);
}

await client(options.endpoints.login, {
Expand All @@ -60,18 +65,27 @@ export const useSanctumAuth = <T>(): SanctumAuth<T> => {
await refreshIdentity();

if (options.redirect.keepRequestedRoute) {
const route = useRoute();
const requestedRoute = route.query.redirect as string | undefined;
if (requestedRoute) {
await nuxtApp.runWithContext(() => navigateTo(requestedRoute));
const requestedRoute = currentRoute.query.redirect;

if (requestedRoute && requestedRoute !== currentRoute.path) {
await nuxtApp.runWithContext(() =>
navigateTo(requestedRoute as string)
);

return;
}
}

if (options.redirect.onLogin) {
const redirect = options.redirect.onLogin as string;
await nuxtApp.runWithContext(() => navigateTo(redirect));
if (
options.redirect.onLogin === false ||
currentRoute.path === options.redirect.onLogin
) {
return;
}

await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onLogin as string)
);
}

/**
Expand All @@ -82,15 +96,22 @@ export const useSanctumAuth = <T>(): SanctumAuth<T> => {
throw new Error('User is not authenticated');
}

const currentRoute = useRoute();

await client(options.endpoints.logout, { method: 'post' });

user.value = null;

if (options.redirect.onLogout) {
const redirect = options.redirect.onLogout as string;

await nuxtApp.runWithContext(() => navigateTo(redirect));
if (
options.redirect.onLogout === false ||
currentRoute.path === options.redirect.onLogout
) {
return;
}

await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onLogout as string)
);
}

return {
Expand Down
27 changes: 14 additions & 13 deletions src/runtime/httpFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ export function createHttpClient(): $Fetch {
const serverCookieName = 'set-cookie';
const cookie = response.headers.get(serverCookieName);

if (cookie === null) {
if (cookie === null || event === undefined) {
return;
}

event?.headers.append(serverCookieName, cookie);
event.headers.append(serverCookieName, cookie);
}

// follow redirects on client
Expand All @@ -114,21 +114,22 @@ export function createHttpClient(): $Fetch {
}
},

async onResponseError({ request, response }): Promise<void> {
async onResponseError({ response }): Promise<void> {
if (response.status === 401) {
// do not redirect when requesting the user endpoint
// this prevents an infinite loop (ERR_TOO_MANY_REDIRECTS)
if (request.toString().endsWith(options.endpoints.user)) {
return;
}

user.value = null;

if (options.redirect.onLogout) {
await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onLogout as string)
);
const currentRoute = nuxtApp.$router.currentRoute.value;

if (
options.redirect.onLogout === false ||
options.redirect.onLogout === currentRoute.path
) {
return;
}

await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onLogout as string)
);
}
},
};
Expand Down

0 comments on commit e19f1a7

Please sign in to comment.