implemented token based login

This commit is contained in:
Sockenklaus
2021-10-22 05:28:51 +02:00
parent d5fdda6337
commit a323cf862a
8 changed files with 179 additions and 73 deletions

View File

@@ -10,7 +10,8 @@ type AuthSuccResult = {
text: string
}
user: string,
role: string
role: string,
token: string
}
type AuthErrResult = {
@@ -20,17 +21,34 @@ type AuthErrResult = {
}
}
export const useUser = defineStore('userStore', {
export const useUser = defineStore({
id: 'storeUser',
state: () => {
return {
user: '',
role: '',
isLoggedIn: false
isLoggedIn: false,
rememberMe: false,
token: ''
}
},
getters: {
isAdmin: (state) => state.role === 'admin',
preferredStorage: (state) => {
return localStorage
/* if (state.rememberMe) return localStorage
else return sessionStorage */
}
},
actions: {
async login(username: string, password: string) : Promise<boolean> {
async login(username: string, password: string, rememberMe: boolean): Promise<boolean> {
const { notifications } = storeToRefs(useNotifications())
try {
@@ -38,10 +56,13 @@ export const useUser = defineStore('userStore', {
username: username,
password: password
})
console.log(response)
this.isLoggedIn = true
this.user = response.data.user
this.role = response.data.role
this.token = response.data.token
notifications.value.push({
type: response.data.notification.type,
@@ -67,6 +88,54 @@ export const useUser = defineStore('userStore', {
return false
}
},
async logout(): Promise<boolean> {
const { notifications } = storeToRefs(useNotifications())
try {
const ai = axios.create({
baseURL: 'http://localhost:3333/api/v1/',
headers: {
'Authorization': 'Bearer '+this.token
}
})
await ai.post('/logout')
notifications.value.push({
type: 'success',
text: 'Logged out successfully',
randomKey: getUnixTime(new Date()).toString()
})
this.$reset()
return true
}
catch(error) {
if(error instanceof Error) {
const notification = {
type: 'danger',
text: error.message,
randomKey: getUnixTime(new Date()).toString()
/**TODO #19 Generate randomKey in notification-store! */
}
notifications.value.push(notification)
}
return false
}
}
},
persist: {
enabled: true,
strategies: [
{
storage: localStorage
}
]
}
})