first commit
This commit is contained in:
38
src/stores/auth.store.js
Normal file
38
src/stores/auth.store.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import { fetchWrapper } from '@/helpers';
|
||||
import { router } from '@/router';
|
||||
|
||||
|
||||
const baseUrl = `${import.meta.env.VITE_BASE_URL}/users`;
|
||||
|
||||
export const useAuthStore = defineStore({
|
||||
id: 'auth',
|
||||
state: () => ({
|
||||
// initialize state from local storage to enable user to stay logged in
|
||||
user: JSON.parse(localStorage.getItem('user')),
|
||||
returnUrl: null
|
||||
}),
|
||||
actions: {
|
||||
async login(username, password) {
|
||||
|
||||
const user = await fetchWrapper.post(`${baseUrl}/authenticate`,
|
||||
{ username, password });
|
||||
|
||||
// update pinia state
|
||||
this.user = user;
|
||||
|
||||
// store user details and jwt in local storage to keep user logged in between page refreshes
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
|
||||
// redirect to previous url or default to home page
|
||||
router.push(this.returnUrl || '/');
|
||||
|
||||
},
|
||||
logout() {
|
||||
this.user = null;
|
||||
localStorage.removeItem('user');
|
||||
router.push('/account/login');
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user