implement user authorization functionality
create the Auth class for authentication handling
import type { Context } from '@nuxt/types';
export class Auth {
public ctx: Context;
constructor(ctx: Context) {
this.ctx = ctx;
}
async login(data: any): Promise<any> {
return await this.ctx.app.$projectServices.repository.login(data);
}
async fetchUser() {
return await this.ctx.app.$projectServices.repository.getAuthUser();
}
}
generate a plugin to inject the global variable $auth
import { Plugin } from '@nuxt/types';
import { Auth } from '~/services/auth/auth';
const auth: Plugin = (context, inject) => {
const auth = new Auth(context);
inject('auth', auth);
};
export default auth;
during Nuxt initialization, check if there is a token in localStorage, and if present, fetch user data
nuxtClientInit plugin
export default async function (context: any) {
await context.store.dispatch('nuxtClientInit');
}
store implementation
import { getToken } from '~/services/auth/token';
export const actions = {
async nuxtClientInit({ commit }: any) {
const token = getToken();
if (token) {
commit('auth/setToken', { token });
await this.$auth
.fetchUser()
.then((response: any) => {
commit('setItem', response);
})
.catch((e: any) => {
if (e.status === 401) {
commit('auth/clear');
}
});
}
},
};
error in the store related to this.$auth usage
TS2339: Property '$auth' does not exist on type '{ nuxtClientInit({ commit }: any): Promise ; }'
what is the solution to this issue?