I have this class which is supposed to authenticate a user (in this case a moderator)
import Cookie from "universal-cookie";
import { promiseNotification, updateNotification } from "./addNotification";
const cookies = new Cookie();
class Authentication {
token;
role;
login = (username, password) => {
const id = promiseNotification("Login...")
fetch("auth/get-token", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username: username, password: password})
})
.then(res => res.json())
.then(data => {
updateNotification(id, data);
if (data.token) {
cookies.set("token", data.token);
this.setToken();
return this.setRole(); //If I understand correctly this returns a promise
}
}).then(() => window.location.replace("/mod")) //and this handles the setRole promise
.catch((error) => {alert("Error occurred login in"); console.log(error)});
}
setRole = async () => {
return fetch(`/auth/get-role/${this.token}`, {method: 'GET'}).then(res => res.json())
.then(data => this.role = data.role);
}
setToken = () => {
this.token = cookies.get("token") || "";
}
}
export default new Authentication();
When I call the login function the role and token should be set in the class instance and after it finishes it should redirect the user to the mods page. In the mods page I have this logic to prevent non moderators from accessing it.
useEffect(() => {
console.log(JSON.stringify(auth)); //This prints an empty object, meaning that none of the actions that happened in login had any effect
if (!["administrator", "moderator"].includes(auth.role)) {
createNotification("You are not a moderator", "error");
history.push("/admin-login");
}
}, []);
Why aren't any of the properties in the auth object being update?