import { createSignal, Show } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { useUserInfo, Whoami } from '../user_info';
import { roles } from '../roles';
export default function Login() {
const [username, setUsername] = createSignal('');
const [password, setPassword] = createSignal('');
const [email, setEmail] = createSignal('');
const [error, setError] = createSignal('');
const navigate = useNavigate();
const userInfo = useUserInfo();
function login(e: MouseEvent) {
e.preventDefault();
fetch(
"/api/v1/user/login",
{
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
username: username(),
password: password(),
email: email(),
})
})
.then((response) => {
if (response.status === 400) {
setError('Bad request signing up')
}
if (response.status === 200) {
return response.json()
}
})
.then((body) => {
if (body && body.userId) {
const whoami: Whoami = body;
console.log(whoami);
userInfo?.[1]?.setUser(whoami);
localStorage.setItem("ALLREDLIB_USERINFO", JSON.stringify(whoami))
if (body.roles?.some((x: string) => x === roles.VIEWER || x === roles.SERVER_ADMIN)) {
navigate('/books');
} else {
navigate('/about');
}
} else {
console.error('expected body to contain user info, but was', JSON.stringify(body))
}
});
return false;
}
return (
<div class="wrapper">
<form>
<input placeholder="username" value={username()} onInput={(e) => {setUsername(e.target.value)}}></input>
<input placeholder="password" value={password()} type="password" onInput={(e) => {setPassword(e.target.value)}}></input>
<input placeholder="email (optional)" value={email()} onInput={(e) => {setEmail(e.target.value)}}></input>
<button onClick={login}>Login</button>
<Show when={error() != ""}>
<p style='color:red;'>here error here</p>
</Show>
</form>
</div>
)
}