88 lines
2.2 KiB
TypeScript
88 lines
2.2 KiB
TypeScript
import React, {
|
|
useState,
|
|
useEffect,
|
|
} from "react";
|
|
import { NextPage } from "next";
|
|
import { useRouter } from "next/router";
|
|
import styled from "styled-components";
|
|
import { authenticate, login } from "@api/auth";
|
|
import AdminPageWrapper from "@views/common/AdminPageWrapper";
|
|
|
|
const Main = styled.div`
|
|
input {
|
|
display: block;
|
|
}
|
|
`;
|
|
|
|
const DEFAULT_REDIRECT = "/admin";
|
|
const AdminLoginPage: NextPage = () => {
|
|
const [username, setUsername] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
const [error, setError] = useState("");
|
|
const router = useRouter();
|
|
const next = router.query.next as string || DEFAULT_REDIRECT;
|
|
|
|
useEffect(() => {
|
|
authenticate().then((authResult) => {
|
|
if (authResult) {
|
|
router.push(next);
|
|
}
|
|
});
|
|
}, [router, next]);
|
|
|
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
try {
|
|
await login(username, password);
|
|
router.push(next);
|
|
} catch (err) {
|
|
setError("Failed to log in!");
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AdminPageWrapper requiresAuthentication={false}>
|
|
<Main>
|
|
<h1>Log in to SIK Admin</h1>
|
|
{next && next !== DEFAULT_REDIRECT && (
|
|
<div className="error">You have to log in first.</div>
|
|
)}
|
|
<form className="admin-login-form" onSubmit={handleSubmit}>
|
|
<label>
|
|
Username
|
|
<input
|
|
id="login-username"
|
|
type="text"
|
|
name="username"
|
|
value={username}
|
|
onChange={(e) => {
|
|
setUsername(e.target.value);
|
|
}}
|
|
/>
|
|
</label>
|
|
<label>
|
|
Password
|
|
<input
|
|
id="login-password"
|
|
type="password"
|
|
name="password"
|
|
value={password}
|
|
onChange={(e) => {
|
|
setPassword(e.target.value);
|
|
}}
|
|
/>
|
|
</label>
|
|
<input id="login-submit" type="submit" value="Log in" />
|
|
</form>
|
|
{error && (
|
|
<div className="error">
|
|
{error}
|
|
</div>
|
|
)}
|
|
</Main>
|
|
</AdminPageWrapper>
|
|
);
|
|
};
|
|
|
|
export default AdminLoginPage;
|