opnform-host-nginx/client/stores/auth.js

90 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-12-14 16:53:05 +01:00
import {defineStore} from 'pinia'
2024-02-10 13:43:49 +01:00
import * as Sentry from "@sentry/vue";
2023-12-09 15:47:03 +01:00
export const useAuthStore = defineStore('auth', {
2023-12-14 16:53:05 +01:00
state: () => {
return {
token: null,
admin_token: null,
user: null,
}
},
2023-12-09 15:47:03 +01: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 16:53:05 +01:00
startImpersonating() {
this.setAdminToken(this.token)
2023-12-09 15:47:03 +01:00
},
// Stop admin impersonation
2023-12-14 16:53:05 +01:00
stopImpersonating() {
2024-01-16 11:23:16 +01:00
this.setToken(this.admin_token)
2023-12-09 15:47:03 +01:00
this.admin_token = null
},
2023-12-14 16:53:05 +01:00
setToken(token) {
2023-12-16 19:21:03 +01:00
this.setCookie('token', token)
2023-12-09 15:47:03 +01:00
this.token = token
},
2023-12-14 16:53:05 +01:00
setAdminToken(token) {
2023-12-16 19:21:03 +01:00
this.setCookie('admin_token', token)
2023-12-14 16:53:05 +01:00
this.admin_token = token
},
2023-12-16 19:21:03 +01:00
setCookie(name, value) {
if (process.client) {
useCookie(name).value = value
}
2023-12-14 16:53:05 +01:00
},
2023-12-16 19:21:03 +01:00
initStore(token, adminToken) {
this.token = token
this.admin_token = adminToken
2023-12-09 15:47:03 +01:00
},
2023-12-16 19:21:03 +01:00
setUser(user) {
if (!user) {
2024-01-02 18:31:31 +01:00
console.error('No user, logging out.')
2023-12-16 19:21:03 +01:00
this.setToken(null)
2023-12-14 16:53:05 +01:00
}
2023-12-16 19:21:03 +01:00
this.user = user
this.initServiceClients()
2023-12-14 16:53:05 +01:00
},
updateUser(payload) {
2023-12-09 15:47:03 +01:00
this.user = payload
2023-12-11 11:56:21 +01:00
this.initServiceClients()
2023-12-09 15:47:03 +01:00
},
initServiceClients() {
if (!this.user) return
useAmplitude().setUser(this.user)
useCrisp().setUser(this.user)
2023-12-14 16:53:05 +01:00
// Init sentry
2024-02-10 13:43:49 +01:00
Sentry.setUser({
2024-02-10 12:20:45 +01:00
id: this.user.id,
email: this.user.email,
subscription: this.user?.is_subscribed
})
},
2023-12-09 15:47:03 +01:00
logout() {
2024-02-10 12:20:45 +01:00
opnFetch('logout', {method: 'POST'}).catch((error) => {
})
2023-12-09 15:47:03 +01:00
this.user = null
2023-12-14 16:53:05 +01:00
this.setToken(null)
2023-12-09 15:47:03 +01:00
},
2023-12-14 16:53:05 +01:00
async fetchOauthUrl(provider) {
// const {data} = await axios.post(`/api/oauth/${provider}`)
// return data.url
2023-12-09 15:47:03 +01:00
}
}
})