1
0
Fork 0
mirror of synced 2024-09-19 02:39:37 +12:00
budibase/packages/client/src/stores/auth.js

49 lines
1.2 KiB
JavaScript
Raw Normal View History

import { API } from "api"
import { writable } from "svelte/store"
2020-11-12 01:25:50 +13:00
const createAuthStore = () => {
const store = writable(null)
2020-11-12 01:25:50 +13:00
// Fetches the user object if someone is logged in and has reloaded the page
const fetchUser = async () => {
let globalSelf = null
let appSelf = null
// First try and get the global user, to see if we are logged in at all
try {
globalSelf = await API.fetchBuilderSelf()
} catch (error) {
store.set(null)
return
}
// Then try and get the user for this app to provide via context
try {
appSelf = await API.fetchSelf()
} catch (error) {
// Swallow
}
// Use the app self if present, otherwise fallback to the global self
store.set(appSelf || globalSelf || null)
}
2021-07-25 23:07:25 +12:00
const logOut = async () => {
try {
await API.logOut()
} catch (error) {
// Do nothing
}
// Manually destroy cookie to be sure
2021-07-25 23:07:25 +12:00
window.document.cookie = `budibase:auth=; budibase:currentapp=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`
}
return {
subscribe: store.subscribe,
2021-07-25 23:07:25 +12:00
actions: { fetchUser, logOut },
2020-11-12 01:25:50 +13:00
}
}
2020-11-12 01:25:50 +13:00
export const authStore = createAuthStore()