umami/components/forms/LoginForm.js

70 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-07-24 04:56:55 +02:00
import React, { useState } from 'react';
2020-08-07 07:03:02 +02:00
import { Formik, Form, Field } from 'formik';
2020-07-24 04:56:55 +02:00
import Router from 'next/router';
import { post } from 'lib/web';
2020-08-07 11:27:12 +02:00
import Button from '../interface/Button';
import FormLayout, { FormButtons, FormError, FormMessage, FormRow } from '../layout/FormLayout';
import styles from './LoginForm.module.css';
2020-07-24 04:56:55 +02:00
const validate = ({ username, password }) => {
const errors = {};
if (!username) {
errors.username = 'Required';
}
if (!password) {
errors.password = 'Required';
}
return errors;
};
2020-08-07 11:27:12 +02:00
export default function LoginForm() {
2020-07-24 04:56:55 +02:00
const [message, setMessage] = useState();
const handleSubmit = async ({ username, password }) => {
2020-08-05 07:45:05 +02:00
const response = await post('/api/auth/login', { username, password });
2020-07-24 04:56:55 +02:00
if (response?.token) {
2020-07-26 01:31:07 +02:00
await Router.push('/');
2020-07-24 04:56:55 +02:00
} else {
setMessage('Incorrect username/password.');
}
};
return (
2020-08-07 07:03:02 +02:00
<FormLayout>
<Formik
initialValues={{
username: '',
password: '',
}}
validate={validate}
onSubmit={handleSubmit}
>
{() => (
<Form>
<h1 className={styles.title}>umami</h1>
<FormRow>
<label htmlFor="username">Username</label>
<Field name="username" type="text" />
<FormError name="username" />
</FormRow>
<FormRow>
<label htmlFor="password">Password</label>
<Field name="password" type="password" />
<FormError name="password" />
</FormRow>
<FormButtons>
2020-08-07 09:24:01 +02:00
<Button className={styles.button} type="submit">
Login
</Button>
2020-08-07 07:03:02 +02:00
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
2020-07-24 04:56:55 +02:00
);
}