wrbapp/frontend/stores/userStore.js

94 lines
2.6 KiB
JavaScript
Raw Normal View History

2023-03-20 11:23:46 +01:00
import { onAuthStateChanged, getAuth } from 'firebase/auth'
import { getDoc, doc, getFirestore } from 'firebase/firestore'
export const useUserStore = defineStore('user', () => {
const db = getFirestore()
const route = useRoute()
const auth = ref(null)
auth.value = getAuth()
const user = ref(null)
const isAuthenticated = ref(false)
const userData = ref(false)
const userPersons = ref([])
const userLoaded = ref(false)
const registrationToken = ref('')
const userAllPersons = ref([])
const init = () => {
onAuthStateChanged(auth.value, async (usr) => {
if (usr) {
user.value = usr
let docRef = doc(db, "users", user.value.uid);
let docSnap = await getDoc(docRef);
if (docSnap.exists()) {
const data = docSnap.data()
userData.value = data
getPersons(userData.value.relatiecodes)
} else {
setTimeout(() => window.location.reload(true), 1000)
}
if (!userData.value.sendNews && route.path === '/news/newmessage') navigateTo('/')
if (!userData.value.admin && route.path.startsWith('/settings/admin')) navigateTo('/')
isAuthenticated.value = true
setupNotifications()
} else {
isAuthenticated.value = false
user.value = null
userData.value = null
userPersons.value = []
}
userLoaded.value = true
})
}
const getPersons = async (persons) => {
userPersons.value = [];
for (let i = 0; i < persons.length; i++) {
const docRef = doc(db, "ledenlijst", persons[i]);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
userPersons.value.push(docSnap.data())
}
}
}
const getAllPersons = async () => {
if (userPersons.value.length === 0) return setTimeout(() => getAllPersons(), 50)
const idToken = await auth.value.currentUser.getIdToken(true)
const { data: response, error } = await useFetch('/api/getrelatiecodes', {
method: 'post',
body: { email: user.value.email, token: idToken }
})
if (error.value) {
console.log(error.value)
return toast.error('Error tijdens het krijgen van relateicodes')
}
response.value.persons.forEach(person => {
if (userPersons.value.map(a => a.relatiecode).includes(person.relatiecode)) {
person.checked = true
} else {
person.checked = false
}
})
userAllPersons.value = response.value.persons
}
return { init, auth, isAuthenticated, userData, userPersons, userAllPersons, getAllPersons, registrationToken, getPersons, userLoaded, user }
})