budibase/packages/client/src/store/auth.js

62 lines
1.7 KiB
JavaScript
Raw Normal View History

import * as API from "../api"
import { writable, get } from "svelte/store"
import { initialise } from "./initialise"
import { routeStore } from "./routes"
import { builderStore } from "./builder"
import { TableNames } from "../constants"
2020-11-11 13:25:50 +01:00
const createAuthStore = () => {
const store = writable(null)
2020-11-11 13:25:50 +01:00
const goToDefaultRoute = () => {
// Setting the active route forces an update of the active screen ID,
// even if we're on the same URL
routeStore.actions.setActiveRoute("/")
// Navigating updates the URL to reflect this route
routeStore.actions.navigate("/")
}
// Logs a user in
2020-12-04 13:22:45 +01:00
const logIn = async ({ email, password }) => {
const auth = await API.logIn({ email, password })
if (auth.success) {
await fetchUser()
await initialise()
goToDefaultRoute()
2020-11-11 13:25:50 +01:00
}
}
// Logs a user out
const logOut = async () => {
store.set(null)
window.document.cookie = `budibase:auth=; budibase:currentapp=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`
await initialise()
goToDefaultRoute()
2020-11-11 13:25:50 +01:00
}
// Fetches the user object if someone is logged in and has reloaded the page
const fetchUser = async () => {
// Fetch the first user if inside the builder
if (get(builderStore).inBuilder) {
const users = await API.fetchTableData(TableNames.USERS)
if (!users.error && users[0] != null) {
store.set(users[0])
}
}
// Or fetch the current user from localstorage in a real app
else {
const user = await API.fetchSelf()
store.set(user)
}
}
return {
subscribe: store.subscribe,
actions: { logIn, logOut, fetchUser },
2020-11-11 13:25:50 +01:00
}
}
2020-11-11 13:25:50 +01:00
export const authStore = createAuthStore()