umami/components/forms/LoginForm.js

69 lines
1.7 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-08 05:36:57 +02:00
import Button from '../common/Button';
2020-08-07 11:27:12 +02:00
import FormLayout, { FormButtons, FormError, FormMessage, FormRow } from '../layout/FormLayout';
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 {
2020-08-09 11:03:37 +02:00
setMessage('Incorrect username/password');
2020-07-24 04:56:55 +02:00
}
};
return (
2020-08-07 07:03:02 +02:00
<FormLayout>
<Formik
initialValues={{
username: '',
password: '',
}}
validate={validate}
onSubmit={handleSubmit}
>
{() => (
<Form>
2020-08-08 05:36:57 +02:00
<h1 className="center">umami</h1>
2020-08-07 07:03:02 +02:00
<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>
<Button type="submit" variant="action">
2020-08-07 09:24:01 +02:00
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
);
}