chore: implemented login version (#4)
Reviewed-on: #4 Co-authored-by: Janis <janis.e.20@gmx.de> Co-committed-by: Janis <janis.e.20@gmx.de>
This commit is contained in:
60
src/stores/auth.ts
Normal file
60
src/stores/auth.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import {type credentials, type token, type user} from '@/types/authTypes'
|
||||
import { defineStore } from 'pinia'
|
||||
import {ref, computed, type Ref} from 'vue'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const user: Ref<user | null> = ref(null)
|
||||
const token = ref(localStorage.getItem('token') || null)
|
||||
|
||||
const isAuthenticated = computed(() => !!token.value)
|
||||
|
||||
async function login(credentials: credentials) {
|
||||
const response = await fakeLoginApi(credentials)
|
||||
|
||||
token.value = response.token
|
||||
user.value = response.user
|
||||
|
||||
localStorage.setItem('token', token.value)
|
||||
}
|
||||
|
||||
function setToken(newToken: string) {
|
||||
token.value = newToken
|
||||
localStorage.setItem('token', newToken)
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = null
|
||||
user.value = null
|
||||
localStorage.removeItem('token')
|
||||
}
|
||||
|
||||
async function fetchUser() {
|
||||
if (!token.value) return
|
||||
|
||||
const response = await fakeFetchUserApi(token.value)
|
||||
user.value = response.user
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
token,
|
||||
isAuthenticated,
|
||||
login,
|
||||
setToken,
|
||||
logout,
|
||||
fetchUser,
|
||||
}
|
||||
})
|
||||
|
||||
async function fakeLoginApi(credentials: credentials): Promise<token> {
|
||||
return {
|
||||
token: 'abc123',
|
||||
user: { id: 1, name: 'John Doe' }
|
||||
}
|
||||
}
|
||||
|
||||
async function fakeFetchUserApi(token: string): Promise<{ user: user }> {
|
||||
return {
|
||||
user: { id: 1, name: 'John Doe' }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user