Skip to content

Commit 492d628

Browse files
committed
refactor: nuxt type based auth
1 parent 0210308 commit 492d628

File tree

5 files changed

+81
-33
lines changed

5 files changed

+81
-33
lines changed

nuxt.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ export default defineNuxtConfig({
9797
runtimeConfig: {
9898
apiLocal: import.meta.env.API_LOCAL_URL,
9999
public: {
100+
authGuard: import.meta.env.AUTH_GUARD,
100101
apiBase: import.meta.env.APP_URL,
101102
apiPrefix: '/api/v1',
102103
storageBase: import.meta.env.APP_URL + '/storage/',

nuxt/components/auth/Login.vue

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const { refresh: onSubmit, status: loginStatus } = useHttp<any>("login", {
2323
if (response?.status === 422) {
2424
form.value.setErrors(response._data?.errors);
2525
} else if (response._data?.ok) {
26-
await auth.fetchUser();
26+
await auth.login(response._data.token ?? null);
2727
await router.push("/");
2828
}
2929
}
@@ -34,10 +34,10 @@ const providers = ref<AuthProviders>(config.public.providers);
3434
async function handleMessage(event: { data: any }): Promise<void> {
3535
const provider = event.data.provider as string;
3636
37-
if (Object.keys(providers.value).includes(provider) && event.data.token) {
37+
if (Object.keys(providers.value).includes(provider)) {
3838
providers.value[provider].loading = false;
3939
40-
await auth.fetchUser();
40+
await auth.login(event.data.token ?? null);
4141
await router.push("/");
4242
} else if (event.data.message) {
4343
toast.add({

nuxt/plugins/app.ts

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,27 @@
11
import type { NitroFetchRequest } from 'nitropack/types';
22
import type { HttpFetchOptions, HttpFetchContext } from '~';
33

4-
async function callHooks(context, hooks) {
5-
if (Array.isArray(hooks)) {
6-
for (const hook of hooks) {
7-
await hook(context);
8-
}
9-
} else if (hooks) {
10-
await hooks(context);
11-
}
12-
}
13-
144
export default defineNuxtPlugin((nuxtApp) => {
5+
const toast = useToast();
156
const config = useRuntimeConfig();
167
const requestUrl = useRequestURL();
178
const requestHeaders = useRequestHeaders(['cookie', 'x-forwarded-for', 'user-agent']);
18-
const toast = useToast();
19-
const xsrfToken = useCookie('XSRF-TOKEN');
20-
21-
function storage(path: string): string {
22-
if (!path) return '';
23-
return path.startsWith('http://') || path.startsWith('https://')
24-
? path
25-
: config.public.storageBase + path;
26-
}
9+
const xsrf = useCookie('XSRF-TOKEN');
10+
const auth = useAuthStore();
2711

2812
function buildHeaders(headers: any): Headers {
13+
let authHeaders = {};
14+
15+
if (config.public.authGuard === 'web') {
16+
authHeaders['X-XSRF-TOKEN'] = xsrf.value;
17+
} else if (config.public.authGuard === 'api' && auth.token) {
18+
authHeaders['Authorization'] = `Bearer ${auth.token}`;
19+
}
20+
2921
return {
3022
Accept: 'application/json',
31-
'X-XSRF-TOKEN': xsrfToken.value,
3223
...headers,
24+
...authHeaders,
3325
...(
3426
import.meta.server
3527
? {
@@ -64,6 +56,16 @@ export default defineNuxtPlugin((nuxtApp) => {
6456
&& !path.startsWith('https://');
6557
}
6658

59+
async function callHooks(context, hooks) {
60+
if (Array.isArray(hooks)) {
61+
for (const hook of hooks) {
62+
await hook(context);
63+
}
64+
} else if (hooks) {
65+
await hooks(context);
66+
}
67+
}
68+
6769
const http = $fetch.create<unknown, NitroFetchRequest>(<HttpFetchOptions>{
6870
baseURL: '',
6971
retry: false,
@@ -110,7 +112,6 @@ export default defineNuxtPlugin((nuxtApp) => {
110112

111113
return {
112114
provide: {
113-
storage,
114115
http
115116
}
116117
}

nuxt/plugins/auth.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@ export default defineNuxtPlugin(async (nuxtApp) => {
22
const auth = useAuthStore();
33
const config = useRuntimeConfig();
44

5-
if (import.meta.client) {
6-
$fetch('/sanctum/csrf-cookie', {
7-
baseURL: config.public.apiBase,
8-
credentials: 'include',
9-
});
5+
if (config.public.authGuard === 'web' && import.meta.client) {
6+
auth.fetchCsrf();
107
}
118

12-
await auth.fetchUser();
9+
if (auth.logged) {
10+
await auth.fetchUser();
11+
}
1312
})

nuxt/stores/auth.ts

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,23 @@ export type User = {
1212
}
1313

1414
export const useAuthStore = defineStore('auth', () => {
15+
const config = useRuntimeConfig();
16+
17+
const tokenCookie = useCookie('token', {
18+
path: '/',
19+
sameSite: 'strict',
20+
secure: config.public.apiBase.startsWith('https://'),
21+
maxAge: 60 * 60 * 24 * 365
22+
});
23+
24+
const loggedCookie = useCookie('logged', {
25+
path: '/',
26+
sameSite: 'strict',
27+
secure: config.public.apiBase.startsWith('https://'),
28+
maxAge: 60 * 60 * 24 * 365
29+
});
30+
1531
const user = ref(<User>{});
16-
const logged = computed(() => !!user.value?.ulid);
1732

1833
const { refresh: logout } = useHttp<any>('logout', {
1934
method: 'POST',
@@ -35,13 +50,45 @@ export const useAuthStore = defineStore('auth', () => {
3550
}
3651
});
3752

53+
function fetchCsrf(): void {
54+
$http('/sanctum/csrf-cookie', {
55+
baseURL: config.public.apiBase,
56+
credentials: 'include',
57+
headers: { Accept: 'application/json' }
58+
});
59+
}
60+
61+
async function login(token?: string | null): Promise<void> {
62+
if (config.public.authGuard === 'api') {
63+
tokenCookie.value = token || null;
64+
}
65+
66+
loggedCookie.value = '1';
67+
await fetchUser();
68+
}
69+
3870
function reset(): void {
71+
if (config.public.authGuard === 'api') {
72+
tokenCookie.value = null;
73+
}
74+
75+
loggedCookie.value = null;
3976
user.value = <User>{}
4077
}
4178

4279
function hasRole(name: string): boolean {
43-
return user.value.roles?.includes(name);
80+
return (user.value.roles ?? []).includes(name);
4481
}
4582

46-
return { user, logged, logout, fetchUser, reset, hasRole }
83+
return {
84+
user,
85+
token: tokenCookie,
86+
logged: loggedCookie,
87+
login,
88+
logout,
89+
fetchUser,
90+
fetchCsrf,
91+
reset,
92+
hasRole,
93+
}
4794
})

0 commit comments

Comments
 (0)