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

100 lines
2.6 KiB
JavaScript
Raw Normal View History

import { derived, writable, get } from "svelte/store"
2021-04-11 22:35:55 +12:00
import api from "../../builderStore/api"
export function createAuthStore() {
2021-08-04 21:02:24 +12:00
const user = writable(null)
const store = derived(user, $user => {
let initials = null
let isAdmin = false
let isBuilder = false
2021-08-04 21:02:24 +12:00
if ($user) {
if ($user.firstName) {
initials = $user.firstName[0]
if ($user.lastName) {
initials += $user.lastName[0]
}
2021-08-04 21:02:24 +12:00
} else if ($user.email) {
initials = $user.email[0]
} else {
initials = "Unknown"
}
2021-08-04 21:02:24 +12:00
isAdmin = !!$user.admin?.global
isBuilder = !!$user.builder?.global
}
return {
2021-08-04 21:02:24 +12:00
user: $user,
initials,
isAdmin,
isBuilder,
}
})
2021-04-11 22:35:55 +12:00
return {
subscribe: store.subscribe,
checkAuth: async () => {
2021-08-04 21:02:24 +12:00
const response = await api.get("/api/admin/users/self")
if (response.status !== 200) {
2021-08-04 21:02:24 +12:00
user.set(null)
} else {
const json = await response.json()
2021-08-04 21:02:24 +12:00
user.set(json)
}
},
2021-05-04 22:32:22 +12:00
login: async creds => {
2021-08-04 21:02:24 +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) {
2021-08-04 21:02:24 +12:00
user.set(json.user)
} else {
throw "Invalid credentials"
}
return json
2021-04-11 22:35:55 +12:00
},
logout: async () => {
2021-08-04 21:02:24 +12:00
const response = await api.post(`/api/admin/auth/logout`)
if (response.status !== 200) {
throw "Unable to create logout"
}
await response.json()
2021-08-04 21:02:24 +12:00
user.set(null)
2021-04-12 21:47:48 +12:00
},
updateSelf: async fields => {
2021-08-04 21:02:24 +12:00
const newUser = { ...get(user), ...fields }
const response = await api.post("/api/admin/users/self", newUser)
if (response.status === 200) {
2021-08-04 21:02:24 +12:00
user.set(newUser)
} else {
throw "Unable to update user details"
}
},
forgotPassword: async email => {
2021-08-04 21:02:24 +12:00
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) => {
2021-08-04 21:02:24 +12:00
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-08-04 21:02:24 +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()