75 lines
2.2 KiB
JavaScript
75 lines
2.2 KiB
JavaScript
import {toast} from "react-toastify";
|
|
|
|
// export const SERVER_URL = "http://192.168.1.8:8080/api"
|
|
export const SERVER_URL = "http://dev.teamortix.com:4290/api"
|
|
|
|
export const defaultAuth = () => ({
|
|
loggedIn: window.localStorage.getItem("authtoken") !== null,
|
|
token: window.localStorage.getItem("authtoken"),
|
|
username: '',
|
|
email: '',
|
|
admin: false,
|
|
})
|
|
|
|
|
|
export const reducer = (state, action) => {
|
|
return {...state, ...action.response}
|
|
}
|
|
|
|
export async function authenticate(token) {
|
|
if (token == null)
|
|
return defaultAuth()
|
|
|
|
const {status, json} = await query("/account/info", {token}).catch(() => {
|
|
toast.error("The authentication server is offline!")
|
|
return defaultAuth()
|
|
})
|
|
|
|
if (status !== 200) {
|
|
window.localStorage.removeItem("authtoken")
|
|
toast.warn("You have been logged out.")
|
|
return defaultAuth()
|
|
}
|
|
console.debug("Authentication Response:", json)
|
|
|
|
const {email, username, admin} = json;
|
|
return {username, email, admin, loggedIn: true}
|
|
}
|
|
|
|
export async function registration(username, email, password) {
|
|
const {status, json} = await query("/register", {username, email, password}).catch(() => {
|
|
return {status: 500, json: {reason: "The authentication server is offline!"}}
|
|
})
|
|
|
|
console.debug("Registration Response:", json)
|
|
return {status, json}
|
|
}
|
|
|
|
export async function login(usernameOrEmail, password) {
|
|
const {status, json} = await query("/login", {usernameOrEmail, password}).catch(() => {
|
|
return {status: 500, json: {reason: "The authentication server is offline!"}}
|
|
})
|
|
console.debug("Login Response:", json)
|
|
|
|
return {status, json}
|
|
}
|
|
|
|
export function logout(token) {
|
|
window.localStorage.removeItem("authtoken")
|
|
query("/logout", {token}).then(() => {
|
|
toast.warn("You have been logged out.")
|
|
})
|
|
return defaultAuth()
|
|
}
|
|
|
|
export async function query(url, data) {
|
|
console.debug("FETCH: " + SERVER_URL + url + " - " + JSON.stringify(data))
|
|
let response = await fetch(SERVER_URL + url, {
|
|
method: "POST",
|
|
headers: {"Content-Type": "application/json"},
|
|
body: JSON.stringify(data)
|
|
})
|
|
const json = await response.json()
|
|
console.debug(json)
|
|
return {status: response.status, json}
|
|
} |