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

41 lines
859 B
JavaScript
Raw Normal View History

2020-11-11 13:25:50 +01:00
import * as api from "../api"
import { getAppId } from "../utils"
import { writable } from "svelte/store"
2020-11-11 13:25:50 +01:00
const createAuthStore = () => {
const store = writable("")
2020-11-11 13:25:50 +01:00
/**
* Logs a user in.
*/
const logIn = async ({ username, password }) => {
const user = await api.logIn({ username, password })
if (!user.error) {
store.set(user.token)
2020-11-11 13:25:50 +01:00
}
return !user.error
2020-11-11 13:25:50 +01:00
}
/**
* Logs a user out.
*/
const logOut = () => {
store.set("")
// Expire any cookies
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;`
}
}
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()