opnform/client/stores/auth.js

101 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-12-14 15:53:05 +00:00
import {defineStore} from 'pinia'
2023-12-09 14:47:03 +00:00
import axios from 'axios'
2023-12-15 11:32:17 +00:00
import {useOpnFetch} from "~/composables/useOpnFetch.js";
2023-12-09 14:47:03 +00:00
export const useAuthStore = defineStore('auth', {
2023-12-14 15:53:05 +00:00
state: () => {
return {
token: null,
admin_token: null,
user: null,
}
},
2023-12-09 14:47:03 +00:00
getters: {
check: (state) => (state.user !== null && state.user !== undefined),
isImpersonating: (state) => (state.admin_token !== null && state.admin_token !== undefined)
},
actions: {
// Stores admin token temporarily for impersonation
2023-12-14 15:53:05 +00:00
startImpersonating() {
this.setAdminToken(this.token)
2023-12-09 14:47:03 +00:00
},
// Stop admin impersonation
2023-12-14 15:53:05 +00:00
stopImpersonating() {
2023-12-09 14:47:03 +00:00
this.token = this.admin_token
this.admin_token = null
this.fetchUser()
},
2023-12-14 15:53:05 +00:00
setToken(token) {
useCookie('token', {maxAge: 60 * 60 * 24 * 30}).value = token
2023-12-09 14:47:03 +00:00
this.token = token
},
2023-12-14 15:53:05 +00:00
setAdminToken(token) {
useCookie('admin_token', {maxAge: 60 * 60 * 24 * 30}).value = token
this.admin_token = token
},
loadTokenFromCookie() {
this.token = useCookie('token').value
this.admin_token = useCookie('admin_token').value
},
async fetchUser() {
2023-12-15 11:32:17 +00:00
useOpnFetch('/user').then(({data, error}) => {
console.log('fetch user', data,error)
if (error.value) {
console.error('Error fetching user', error.value)
this.setToken(null)
}
this.user = data.value
this.initServiceClients()
2023-12-09 14:47:03 +00:00
2023-12-15 11:32:17 +00:00
return this.user
})
2023-12-09 14:47:03 +00:00
},
2023-12-14 15:53:05 +00:00
async fetchUserIfNotFetched() {
if (this.user === null && this.token) {
await this.fetchUser()
}
},
updateUser(payload) {
2023-12-09 14:47:03 +00:00
this.user = payload
2023-12-11 10:56:21 +00:00
this.initServiceClients()
2023-12-09 14:47:03 +00:00
},
initServiceClients() {
if (!this.user) return
useAmplitude().setUser(this.user)
useCrisp().setUser(this.user)
2023-12-14 15:53:05 +00:00
// Init sentry
Sentry.configureScope((scope) => {
scope.setUser({
id: this.user.id,
email: this.user.email,
subscription: this.user?.is_subscribed
})
})
},
2023-12-09 14:47:03 +00:00
2023-12-14 15:53:05 +00:00
async logout() {
2023-12-09 14:47:03 +00:00
try {
await axios.post('/api/logout')
2023-12-14 15:53:05 +00:00
} catch (e) {
}
2023-12-09 14:47:03 +00:00
this.user = null
2023-12-14 15:53:05 +00:00
this.setToken(null)
2023-12-09 14:47:03 +00:00
},
2023-12-14 15:53:05 +00:00
async fetchOauthUrl(provider) {
const {data} = await axios.post(`/api/oauth/${provider}`)
2023-12-09 14:47:03 +00:00
return data.url
}
}
})