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

74 lines
2.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"
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/admin/users/self")
if (response.status !== 200) {
store.update(state => ({ ...state, user: null }))
} else {
const user = await response.json()
store.update(state => ({ ...state, user }))
}
},
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
},
updateSelf: async user => {
const response = await api.post("/api/admin/users/self", user)
if (response.status === 200) {
store.update(state => ({ ...state, user: { ...state.user, ...user } }))
} else {
throw "Unable to update user details"
}
},
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()