implemented authentication

This commit is contained in:
Johanna Kuehner
2024-02-29 21:05:08 +01:00
parent 601449d7e0
commit 7c19ee9215
12 changed files with 277 additions and 36 deletions

65
store/auth.ts Normal file
View 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
View File

@ -0,0 +1,4 @@
import { createPinia } from "pinia";
import piniaPluginPersistedState from "pinia-plugin-persistedstate"
export const pinia = createPinia().use(piniaPluginPersistedState);