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

66 lines
1.8 KiB
JavaScript
Raw Normal View History

import { writable } from "svelte/store"
2021-04-11 22:35:55 +12:00
import api from "../../builderStore/api"
export function createAuthStore() {
const store = writable({ user: null })
2021-04-11 22:35:55 +12:00
return {
subscribe: store.subscribe,
checkAuth: async () => {
const response = await api.get("/api/self")
const user = await response.json()
if (response.status === 200) {
store.update(state => ({ ...state, user }))
} else {
store.update(state => ({ ...state, user: null }))
}
},
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) {
store.update(state => ({ ...state, 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()
store.update(state => ({ ...state, user: null }))
2021-04-12 21:47:48 +12:00
},
forgotPassword: async email => {
const response = await api.post(`/api/admin/auth/reset`, {
email,
})
if (response.status !== 200) {
throw "Unable to send email with reset link"
}
await response.json()
},
resetPassword: async (password, code) => {
const response = await api.post(`/api/admin/auth/reset/update`, {
password,
resetCode: code,
})
if (response.status !== 200) {
throw "Unable to reset password"
}
await response.json()
},
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()
},
2021-04-11 22:35:55 +12:00
}
}
export const auth = createAuthStore()