TTime/frontend/src/Components/LoginCheck.tsx
2024-03-19 17:12:09 +01:00

53 lines
1.6 KiB
TypeScript

import { NewUser } from "../Types/goTypes";
import { api, APIResponse } from "../API/API";
import { Dispatch, SetStateAction } from "react";
/*
* Checks if user is in database with api.login and then sets proper authority level
* TODO: change so that it checks for user type (admin, user, pm) somehow instead
**/
function LoginCheck(props: {
username: string;
password: string;
setAuthority: Dispatch<SetStateAction<number>>;
}): void {
const user: NewUser = {
username: props.username,
password: props.password,
};
localStorage.clear();
api
.login(user)
.then((response: APIResponse<string>) => {
if (response.success) {
if (response.data !== undefined) {
const token = response.data;
localStorage.setItem("accessToken", token);
localStorage.setItem("username", props.username);
//TODO: change so that it checks for user type (admin, user, pm) instead
if (token !== "" && props.username === "admin") {
props.setAuthority((prevAuth) => {
prevAuth = 1;
return prevAuth;
});
} else if (token !== "") {
props.setAuthority((prevAuth) => {
prevAuth = 2;
return prevAuth;
});
}
} else {
console.error("Token was undefined");
}
} else {
console.error("Token could not be fetched/No such user");
}
})
.catch((error) => {
console.error("An error occurred during login:", error);
});
}
export default LoginCheck;