budibase/packages/component-sdk/src/store/auth.js

43 lines
927 B
JavaScript
Raw Normal View History

2020-11-11 13:25:50 +01:00
import { localStorageStore } from "../../../builder/src/builderStore/store/localStorage"
import * as api from "../api"
import { getAppId } from "../utils"
2020-11-11 13:25:50 +01:00
const initialState = ""
2020-11-11 13:25:50 +01:00
export const createAuthStore = () => {
const store = localStorageStore("budibase:token", initialState)
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(initialState)
// 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
}
store.actions = {
logIn,
logOut,
}
return store
}