koel/resources/assets/js/services/authService.ts

66 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-01-18 11:13:05 +00:00
import { merge } from 'lodash'
2024-03-15 15:09:50 +00:00
import { http } from '@/services'
2024-01-18 11:13:05 +00:00
import { userStore } from '@/stores'
2024-03-15 15:09:50 +00:00
import { useLocalStorage } from '@/composables'
2024-01-18 11:13:05 +00:00
export interface UpdateCurrentProfileData {
current_password: string | null
name: string
email: string
avatar?: string
new_password?: string
}
2022-11-16 17:57:38 +00:00
const API_TOKEN_STORAGE_KEY = 'api-token'
const AUDIO_TOKEN_STORAGE_KEY = 'audio-token'
2022-04-24 08:50:45 +00:00
2024-03-15 15:09:50 +00:00
const { get: lsGet, set: lsSet, remove: lsRemove } = useLocalStorage(false) // authentication local storage data aren't namespaced
2022-05-14 18:49:45 +00:00
export const authService = {
2024-01-18 11:13:05 +00:00
async login (email: string, password: string) {
2024-03-30 16:49:25 +00:00
this.setTokensUsingCompositeToken(await http.post<CompositeToken>('me', { email, password }))
2024-01-18 11:13:05 +00:00
},
async logout () {
await http.delete('me')
this.destroy()
},
getProfile: async () => await http.get<User>('me'),
updateProfile: async (data: UpdateCurrentProfileData) => {
merge(userStore.current, (await http.put<User>('me', data)))
},
2024-03-15 15:09:50 +00:00
getApiToken: () => lsGet(API_TOKEN_STORAGE_KEY),
2022-04-24 08:50:45 +00:00
2022-11-16 17:57:38 +00:00
hasApiToken () {
return Boolean(this.getApiToken())
2022-04-24 08:50:45 +00:00
},
2024-03-15 15:09:50 +00:00
setApiToken: (token: string) => lsSet(API_TOKEN_STORAGE_KEY, token),
2022-11-16 17:57:38 +00:00
2024-03-30 16:49:25 +00:00
setTokensUsingCompositeToken (compositeToken: CompositeToken) {
this.setApiToken(compositeToken.token)
this.setAudioToken(compositeToken['audio-token'])
},
2022-11-16 17:57:38 +00:00
destroy: () => {
2024-03-15 15:09:50 +00:00
lsRemove(API_TOKEN_STORAGE_KEY)
lsRemove(AUDIO_TOKEN_STORAGE_KEY)
2022-11-16 17:57:38 +00:00
},
2024-03-15 15:09:50 +00:00
setAudioToken: (token: string) => lsSet(AUDIO_TOKEN_STORAGE_KEY, token),
2022-11-16 17:57:38 +00:00
getAudioToken: () => {
// for backward compatibility, we first try to get the audio token, and fall back to the (full-privileged) API token
2024-03-15 15:09:50 +00:00
return lsGet(AUDIO_TOKEN_STORAGE_KEY) || lsGet(API_TOKEN_STORAGE_KEY)
2024-02-25 19:32:53 +00:00
},
requestResetPasswordLink: async (email: string) => await http.post('forgot-password', { email }),
resetPassword: async (email: string, password: string, token: string) => {
await http.post('reset-password', { email, password, token })
2022-11-16 17:57:38 +00:00
}
2022-04-24 08:50:45 +00:00
}