You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.4 KiB
65 lines
1.4 KiB
import {useGlobal} from "reactn";
|
|
import {fetchGet, fetchPost} from "../Helpers/fetcher";
|
|
|
|
export default function useAuth() {
|
|
const [isLoggedIn, setIsLoggedIn] = useGlobal("auth/login");
|
|
const [isChecked, setIsChecked] = useGlobal("auth/checked");
|
|
|
|
function verify() {
|
|
setIsChecked(false);
|
|
|
|
fetchGet("/user/session").then(({data, error}) => {
|
|
setIsLoggedIn(error === null && data.loggedIn);
|
|
setIsChecked(true);
|
|
})
|
|
}
|
|
|
|
function login(username, password) {
|
|
setIsChecked(false);
|
|
|
|
fetchPost("/user/login", {username, password}).then(({data, error}) => {
|
|
setIsChecked(true);
|
|
|
|
console.dir({data, error});
|
|
if (error !== null) {
|
|
setIsLoggedIn(false);
|
|
return;
|
|
}
|
|
|
|
setIsLoggedIn(true);
|
|
});
|
|
}
|
|
|
|
function logout() {
|
|
setIsChecked(false);
|
|
|
|
fetchPost("/user/logout").then(({data, error}) => {
|
|
setIsChecked(true);
|
|
|
|
if (error !== null) {
|
|
setIsLoggedIn(false);
|
|
return;
|
|
// TODO: Show errors ¿?
|
|
}
|
|
|
|
setIsLoggedIn(false);
|
|
});
|
|
}
|
|
|
|
function register(username, password, repeated) {
|
|
setIsChecked(false);
|
|
|
|
if (password !== repeated) {
|
|
alert("Passordene er ikke like");
|
|
return;
|
|
}
|
|
|
|
fetchPost("/user/register", {username, password}).then(({data, error}) => {
|
|
if (error !== null) {
|
|
login(username, password);
|
|
}
|
|
})
|
|
}
|
|
|
|
return {isLoggedIn, isChecked, verify, login, logout, register};
|
|
}
|