2024-01-18 11:13:05 +00:00
|
|
|
import { merge } from 'lodash'
|
|
|
|
import { http, localStorageService } from '@/services'
|
|
|
|
import { userStore } from '@/stores'
|
|
|
|
|
|
|
|
export interface UpdateCurrentProfileData {
|
|
|
|
current_password: string | null
|
|
|
|
name: string
|
|
|
|
email: string
|
|
|
|
avatar?: string
|
|
|
|
new_password?: string
|
|
|
|
}
|
|
|
|
|
|
|
|
interface CompositeToken {
|
|
|
|
'audio-token': string
|
|
|
|
'token': string
|
|
|
|
}
|
2022-04-24 08:50:45 +00:00
|
|
|
|
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
|
|
|
|
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) {
|
|
|
|
const token = await http.post<CompositeToken>('me', { email, password })
|
|
|
|
|
|
|
|
this.setAudioToken(token['audio-token'])
|
|
|
|
this.setApiToken(token.token)
|
|
|
|
},
|
|
|
|
|
|
|
|
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)))
|
|
|
|
},
|
|
|
|
|
2022-11-16 17:57:38 +00:00
|
|
|
getApiToken: () => localStorageService.get(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
|
|
|
},
|
|
|
|
|
2022-11-16 17:57:38 +00:00
|
|
|
setApiToken: (token: string) => localStorageService.set(API_TOKEN_STORAGE_KEY, token),
|
|
|
|
|
|
|
|
destroy: () => {
|
|
|
|
localStorageService.remove(API_TOKEN_STORAGE_KEY)
|
|
|
|
localStorageService.remove(AUDIO_TOKEN_STORAGE_KEY)
|
|
|
|
},
|
|
|
|
|
|
|
|
setAudioToken: (token: string) => localStorageService.set(AUDIO_TOKEN_STORAGE_KEY, token),
|
|
|
|
|
|
|
|
getAudioToken: () => {
|
|
|
|
// for backward compatibility, we first try to get the audio token, and fall back to the (full-privileged) API token
|
|
|
|
return localStorageService.get(AUDIO_TOKEN_STORAGE_KEY) || localStorageService.get(API_TOKEN_STORAGE_KEY)
|
|
|
|
}
|
2022-04-24 08:50:45 +00:00
|
|
|
}
|