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.
91 lines
2.0 KiB
91 lines
2.0 KiB
import {setGlobal, useGlobal} from "reactn";
|
|
import {fetchGet, fetchPost} from "../Helpers/fetcher";
|
|
|
|
setGlobal({
|
|
"auth/login": false,
|
|
"auth/checked": false,
|
|
"auth/users/me": null,
|
|
"auth/users/all": [],
|
|
});
|
|
|
|
export default function useAuth() {
|
|
const [isLoggedIn, setIsLoggedIn] = useGlobal("auth/login");
|
|
const [isChecked, setIsChecked] = useGlobal("auth/checked");
|
|
const [user, setUser] = useGlobal("auth/users/me");
|
|
const [users, setUsers] = useGlobal("auth/users/all");
|
|
|
|
function fetchUsers() {
|
|
fetchGet("/user/").then(({data, error}) => {
|
|
if (error === null) {
|
|
setUsers(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
function verify() {
|
|
setIsChecked(false);
|
|
|
|
fetchGet("/user/session").then(({data, error}) => {
|
|
const validSession = error === null && data.loggedIn;
|
|
|
|
setIsLoggedIn(validSession);
|
|
|
|
if (validSession) {
|
|
setUser(data.user);
|
|
fetchUsers();
|
|
}
|
|
|
|
setIsChecked(true);
|
|
})
|
|
}
|
|
|
|
function login(username, password) {
|
|
setIsChecked(false);
|
|
|
|
fetchPost("/user/login", {username, password}).then(({data, error}) => {
|
|
setIsChecked(true);
|
|
|
|
if (error !== null) {
|
|
setIsLoggedIn(false);
|
|
return;
|
|
}
|
|
|
|
setIsLoggedIn(true);
|
|
setIsLoggedIn(data);
|
|
fetchUsers();
|
|
});
|
|
}
|
|
|
|
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, user, users, verify, login, logout, register};
|
|
}
|