Skip to content

Commit

Permalink
feat: configure redirect if unauthenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
manchenkoff committed Jun 26, 2024
1 parent 782af6a commit 9574818
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const defaultModuleOptions: Partial<SanctumModuleOptions> = {
mode: 'cookie',
userStateKey: 'sanctum.user.identity',
redirectIfAuthenticated: false,
redirectIfUnauthenticated: false,
endpoints: {
csrf: '/sanctum/csrf-cookie',
login: '/login',
Expand Down
31 changes: 20 additions & 11 deletions src/runtime/httpFactory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { $Fetch, FetchOptions, FetchContext } from 'ofetch';
import { useNuxtApp } from '#app';
import { navigateTo, useNuxtApp } from '#app';
import { useSanctumUser } from './composables/useSanctumUser';
import { useSanctumConfig } from './composables/useSanctumConfig';
import { type ConsolaInstance } from 'consola';
Expand Down Expand Up @@ -84,7 +84,7 @@ export function createHttpClient(logger: ConsolaInstance): $Fetch {
}
},

async onResponseError({ request, response }): Promise<void> {
async onResponseError({ response }): Promise<void> {
if (response.status === 419) {
logger.warn(
'CSRF token mismatch, check your API configuration'
Expand All @@ -93,15 +93,24 @@ export function createHttpClient(logger: ConsolaInstance): $Fetch {
return;
}

if (
response.status === 401 &&
request.toString().endsWith(options.endpoints.user) &&
user.value !== null
) {
logger.warn(
'User session is not set in API or expired, resetting identity'
);
user.value = null;
if (response.status === 401) {
if (user.value !== null) {
logger.warn(
'User session is not set in API or expired, resetting identity'
);

user.value = null;
}

if (
import.meta.client &&
options.redirectIfUnauthenticated &&
options.redirect.onAuthOnly
) {
await nuxtApp.runWithContext(() =>
navigateTo(options.redirect.onAuthOnly as string)
);
}
}
},
};
Expand Down
7 changes: 6 additions & 1 deletion src/runtime/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,15 @@ export interface SanctumModuleOptions {
*/
userStateKey: string;
/**
* Determine to redirect when user is authenticated.
* Determine whether to redirect when the user is authenticated when on login attempt.
* @default false
*/
redirectIfAuthenticated: boolean;
/**
* Determine whether to redirect when the user got unauthenticated on any API request.
* @default false
*/
redirectIfUnauthenticated: boolean;
/**
* Laravel Sanctum endpoints to be used by the client.
*/
Expand Down

0 comments on commit 9574818

Please sign in to comment.