1
0
Fork 0
mirror of synced 2024-06-01 18:20:18 +12:00
budibase/packages/builder/src/stores/backend/auth.js

44 lines
1 KiB
JavaScript
Raw Normal View History

import { writable } from "svelte/store"
2021-04-11 22:35:55 +12:00
import api from "../../builderStore/api"
2021-04-12 22:20:01 +12:00
async function checkAuth() {
const response = await api.get("/api/self")
const user = await response.json()
if (response.status === 200) return user
return null
2021-04-12 22:20:01 +12:00
}
2021-04-11 22:35:55 +12:00
export function createAuthStore() {
const { subscribe, set } = writable(null)
2021-04-12 21:47:48 +12:00
checkAuth()
.then(user => set({ user }))
.catch(() => set({ user: null }))
2021-04-11 22:35:55 +12:00
return {
subscribe,
2021-04-12 21:47:48 +12:00
login: async creds => {
const response = await api.post(`/api/admin/auth`, creds)
2021-04-11 22:35:55 +12:00
const json = await response.json()
if (response.status === 200) {
set({ user: json.user })
} else {
throw "Invalid credentials"
}
return json
2021-04-11 22:35:55 +12:00
},
logout: async () => {
2021-04-14 00:56:28 +12:00
const response = await api.post(`/api/admin/auth/logout`)
await response.json()
set({ user: null })
2021-04-12 21:47:48 +12:00
},
createUser: async user => {
const response = await api.post(`/api/admin/users`, user)
await response.json()
2021-04-11 22:35:55 +12:00
},
}
}
export const auth = createAuthStore()