implemented authentication
This commit is contained in:
65
store/auth.ts
Normal file
65
store/auth.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
userobject: null,
|
||||
username: 'user',
|
||||
token: 'token',
|
||||
authenticated: false,
|
||||
}),
|
||||
actions: {
|
||||
createNewSession( user: any, t: string ) {
|
||||
this.userobject = user;
|
||||
this.username = user.username;
|
||||
this.token = t;
|
||||
this.authenticated = true;
|
||||
},
|
||||
logUserOut() {
|
||||
this.username = 'user';
|
||||
this.token = 'token';
|
||||
this.authenticated = false;
|
||||
},
|
||||
},
|
||||
persist: true,
|
||||
});
|
||||
|
||||
|
||||
/*interface UserPayloadInterface {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
authenticated: false,
|
||||
loading: false,
|
||||
}),
|
||||
actions: {
|
||||
async authenticateUser({ username, password }: UserPayloadInterface) {
|
||||
// useFetch from nuxt 3
|
||||
const { data, pending }: any = await useFetch('https://dummyjson.com/auth/login', {
|
||||
method: 'post',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
});
|
||||
this.loading = pending;
|
||||
|
||||
if (data.value) {
|
||||
const token = useCookie('token'); // useCookie new hook in nuxt 3
|
||||
token.value = data?.value?.token; // set token to cookie
|
||||
this.authenticated = true; // set authenticated state value to true
|
||||
}
|
||||
},
|
||||
logUserOut() {
|
||||
const token = useCookie('token'); // useCookie new hook in nuxt 3
|
||||
this.authenticated = false; // set authenticated state value to false
|
||||
token.value = null; // clear the token cookie
|
||||
},
|
||||
},
|
||||
});*/
|
||||
|
||||
4
store/index.ts
Normal file
4
store/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import { createPinia } from "pinia";
|
||||
import piniaPluginPersistedState from "pinia-plugin-persistedstate"
|
||||
|
||||
export const pinia = createPinia().use(piniaPluginPersistedState);
|
||||
Reference in New Issue
Block a user