You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.7 KiB

import React, { useEffect, useState } from 'react';
import { Alert, Box, Button, Collapse, Paper, TextField, Toolbar, Typography } from "@mui/material";
import { LoadingButton } from "@mui/lab";
import { useForm } from "react-hook-form";
import { useSignInMutation } from "../graphql/tscode";
import { Link, useLocation } from "react-router-dom";
import { observer } from "mobx-react";
import { useInjection } from "inversify-react";
import { AuthStore } from "../stores/AuthStore";
import SetTitle from "../components/SetTitle";
type LoginPageProps = {}
type Inputs = {
username: string,
password: string,
}
const SignInPage = observer(({}: LoginPageProps) => {
const authStore = useInjection(AuthStore);
const location = useLocation();
const { register, handleSubmit, formState: { errors } } = useForm<Inputs>()
const [ signUpSuccess, setSignUpSuccess ] = useState(false);
const [ notSignedIn, setNotSignedIn ] = useState(false);
useEffect(() => {
switch (location.state) {
case 'not_signed_in':
setNotSignedIn(true)
setTimeout(() => {
setNotSignedIn(false)
}, 5000)
break
case 'signup_success':
setSignUpSuccess(true)
setTimeout(() => {
setSignUpSuccess(false)
}, 5000)
}
}, [])
const [ signInFunction, {
data,
loading,
error
} ] = useSignInMutation({ onCompleted: (result) => authStore.setToken(result.signIn) })
const onSubmit = async (data: Inputs) => {
try {
await signInFunction({ variables: data })
} catch (e) {
console.log(e)
}
}
return (
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
<SetTitle>Signing In</SetTitle>
<Paper
onSubmit={handleSubmit(onSubmit)}
component='form'
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: 2,
width: {
xs: '90vw',
md: 400,
}
}}
>
<TextField
label='Username'
variant='standard'
error={!!errors.username}
helperText={errors.username?.message}
{...register('username', { required: 'Username is required' })}
/>
<TextField
label='Password'
type='password'
variant='standard'
margin='normal'
sx={{ mb: 3 }}
error={!!errors.password}
helperText={errors.password?.message}
{...register('password', { required: 'Password is required' })}
/>
{error && <Alert sx={{ mb: 2, maxWidth: '199px' }} variant='filled' severity='error'>{error?.message}</Alert>}
<Collapse in={signUpSuccess}><Alert sx={{ mb: 2, maxWidth: '300px' }} variant='filled' severity='success'>You have signed up!</Alert></Collapse>
<Collapse in={notSignedIn}><Alert sx={{ mb: 2, maxWidth: '300 px' }} variant='filled' severity='error'>You should sign in motherfucker!</Alert></Collapse>
<LoadingButton loading={loading} variant='outlined' type='submit' sx={{ mb: 1 }}>Sign In</LoadingButton>
<div>{authStore.token}</div>
</Paper>
</Box>
)
});
export default SignInPage;