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

45 lines
1.2 KiB
JavaScript
Raw Normal View History

import * as API from "../api"
import { getAppId } from "../utils/getAppId"
import { writable } from "svelte/store"
import { initialise } from "./initialise"
import { routeStore } from "./routes"
2020-11-11 13:25:50 +01:00
const createAuthStore = () => {
const store = writable("")
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("/")
}
2020-12-04 13:22:45 +01:00
const logIn = async ({ email, password }) => {
const user = await API.logIn({ email, password })
2020-11-11 13:25:50 +01:00
if (!user.error) {
store.set(user.token)
await initialise()
goToDefaultRoute()
2020-11-11 13:25:50 +01:00
}
}
const logOut = async () => {
store.set("")
const appId = getAppId()
if (appId) {
for (let environment of ["local", "cloud"]) {
window.document.cookie = `budibase:${appId}:${environment}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`
}
}
await initialise()
goToDefaultRoute()
2020-11-11 13:25:50 +01:00
}
return {
subscribe: store.subscribe,
actions: { logIn, logOut },
2020-11-11 13:25:50 +01:00
}
}
2020-11-11 13:25:50 +01:00
export const authStore = createAuthStore()