Skip to content

Commit

Permalink
Merge pull request #8 from manchenkoff/7-redirect-if-the-state-was-a-…
Browse files Browse the repository at this point in the history
…401-response

Reset user identity when API returns 401
  • Loading branch information
manchenkoff authored Nov 23, 2023
2 parents 99c0a85 + 4c4599f commit ea3453d
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/runtime/httpFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ import {
useRequestHeaders,
useRuntimeConfig,
navigateTo,
useNuxtApp,
} from '#app';
import { SanctumModuleOptions } from '../types';
import { useSanctumUser } from './composables/useSanctumUser';

export const SECURE_METHODS = new Set(['post', 'delete', 'put', 'patch']);

export function createHttpClient(): $Fetch {
const options = useRuntimeConfig().public.sanctum as SanctumModuleOptions;
const event = useRequestEvent();
const user = useSanctumUser();
const nuxtApp = useNuxtApp();

/**
* Request a new CSRF cookie from the API and pass it to the headers collection
Expand Down Expand Up @@ -101,7 +105,25 @@ export function createHttpClient(): $Fetch {

// follow redirects on client
if (response.redirected) {
await navigateTo(response.url);
await nuxtApp.runWithContext(() => navigateTo(response.url));
}
},

async onResponseError({ request, 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)
);
}
}
},
};
Expand Down

0 comments on commit ea3453d

Please sign in to comment.