1
0
Fork 0
mirror of synced 2024-06-13 16:05:06 +12:00
budibase/packages/builder/src/stores/backend/auth.js

57 lines
1.4 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()
2021-05-04 22:32:22 +12:00
.then(user => set({ user }))
.catch(() => set({ user: null }))
2021-04-11 22:35:55 +12:00
return {
subscribe,
2021-05-04 22:32:22 +12:00
login: async creds => {
2021-04-12 21:47:48 +12:00
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`)
if (response.status !== 200) {
throw "Unable to create logout"
}
await response.json()
set({ user: null })
2021-04-12 21:47:48 +12:00
},
2021-05-04 22:32:22 +12:00
createUser: async user => {
2021-04-12 21:47:48 +12:00
const response = await api.post(`/api/admin/users`, user)
if (response.status !== 200) {
throw "Unable to create user"
}
await response.json()
},
firstUser: async () => {
const response = await api.post(`/api/admin/users/first`)
if (response.status !== 200) {
throw "Unable to create test user"
}
await response.json()
2021-04-11 22:35:55 +12:00
},
}
}
export const auth = createAuthStore()