All files / src/app/(auth)/login LoginForm.tsx

86.95% Statements 20/23
75% Branches 6/8
100% Functions 3/3
86.95% Lines 20/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 1671x                                                     1x 36x 36x 36x 36x   36x                 36x 5x 5x 5x             3x                     3x 3x           3x     1x         1x           36x   36x                                                                                                     3x                                                          
'use client';
 
import {
  Anchor,
  Button,
  Checkbox,
  Container,
  Group,
  Paper,
  PasswordInput,
  Text,
  TextInput,
  Title,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import { useTranslations } from 'next-intl';
import type { FC } from 'react';
import { useState } from 'react';
import { zodResolver } from '@/lib/validation/zodResolver';
import { loginValidationSchema } from '../../../lib/validation';
import { AUTH_ROUTES } from '../../../types/routes';
import type { LoginFormValues } from './types';
 
export const LoginForm: FC = () => {
  const translate = useTranslations();
  const router = useRouter();
  const [rememberMe, setRememberMe] = useState(false);
  const [isSigningIn, setIsSigningIn] = useState(false);
 
  const form = useForm<LoginFormValues>({
    mode: 'controlled',
    initialValues: {
      email: '',
      password: '',
    },
    validate: zodResolver(loginValidationSchema),
  });
 
  const handleLogin = async (values: LoginFormValues) => {
    try {
      setIsSigningIn(true);
      const result = await signIn('credentials', {
        email: values.email,
        password: values.password,
        redirect: false,
        rememberMe,
      });
 
      Iif (result?.error) {
        notifications.show({
          title: translate('response.error'),
          message: translate('auth.invalidCredentials'),
          color: 'red',
          position: 'top-right',
        });
        setIsSigningIn(false);
        return;
      }
 
      Eif (result?.ok) {
        notifications.show({
          title: translate('response.success'),
          message: translate('auth.loginSuccess'),
          color: 'green',
        });
        // Navigation will unmount component, keep loading state
        router.push('/');
      }
    } catch {
      notifications.show({
        title: translate('response.error'),
        message: translate('auth.loginError'),
        color: 'red',
      });
      setIsSigningIn(false);
    }
  };
 
  // Keep submit disabled while an auth request is in flight.
  // Field-level validation still runs on blur and on submit.
  const isLoginDisabled = form.submitting || isSigningIn;
 
  return (
    <Container maw={520} my={40} id="login-page">
      <Title ta="center" c="var(--mantine-color-gray-8)">
        {translate('auth.welcomeBack')}
      </Title>
      <Group mt={5} justify="center" align="center">
        <Text c="dimmed" size="sm" ta="center">
          {translate('auth.dontYouHaveAnAccount')}
        </Text>
        <Button
          variant="transparent"
          size="sm"
          component={Link}
          href={AUTH_ROUTES.SIGNUP}
          data-testid="create-account"
        >
          {translate('auth.createAccountButton')}
        </Button>
      </Group>
      <Paper
        component="form"
        withBorder
        shadow="md"
        p={30}
        mt={30}
        radius="md"
        onSubmit={form.onSubmit(handleLogin)}
      >
        <TextInput
          label={translate('user.email')}
          placeholder={translate('auth.emailPlaceholder')}
          required
          id="email"
          type="email"
          autoComplete="email"
          {...form.getInputProps('email')}
        />
        <PasswordInput
          placeholder={translate('user.password')}
          required
          mt="md"
          id="password"
          label={translate('user.password')}
          autoComplete="current-password"
          {...form.getInputProps('password')}
        />
        <Group justify="space-between" mt="lg">
          <Checkbox
            data-testid="remember-me"
            label={translate('auth.rememberMe')}
            checked={rememberMe}
            onChange={(e) => setRememberMe(e.currentTarget.checked)}
          />
          <Anchor
            variant="gradient"
            gradient={{ from: 'blue', to: 'cyan', deg: 90 }}
            component={Link}
            size="sm"
            href={AUTH_ROUTES.RESET_PASSWORD}
            data-testid="forgot-password"
          >
            {translate('auth.forgotPassword')}
          </Anchor>
        </Group>
        <Button
          id="login-button"
          data-testid="login-button"
          fullWidth
          mt="xl"
          type="submit"
          disabled={isLoginDisabled}
          loading={form.submitting || isSigningIn}
          loaderProps={{ type: 'dots' }}
        >
          {translate('auth.signIn')}
        </Button>
      </Paper>
    </Container>
  );
};