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