Refine auth error handling

This commit is contained in:
Sam Becker 2024-01-14 18:40:51 -06:00
parent 4d32e763d1
commit 34b9d3d93c
3 changed files with 27 additions and 9 deletions

View File

@ -7,9 +7,12 @@ import { useLayoutEffect, useRef, useState } from 'react';
import { signInAction } from './actions';
import { useFormState } from 'react-dom';
import ErrorNote from '@/components/ErrorNote';
import { CREDENTIALS_SIGN_IN_ERROR } from '.';
import { KEY_CALLBACK_URL, KEY_CREDENTIALS_SIGN_IN_ERROR } from '.';
import { useSearchParams } from 'next/navigation';
export default function SignInForm() {
const params = useSearchParams();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [response, action] = useFormState(signInAction, undefined);
@ -27,7 +30,7 @@ export default function SignInForm() {
<InfoBlock>
<form action={action}>
<div className="space-y-8">
{response === CREDENTIALS_SIGN_IN_ERROR &&
{response === KEY_CREDENTIALS_SIGN_IN_ERROR &&
<ErrorNote>
Invalid email/password
</ErrorNote>}
@ -47,6 +50,11 @@ export default function SignInForm() {
value={password}
onChange={setPassword}
/>
<input
type="hidden"
name={KEY_CALLBACK_URL}
value={params.get(KEY_CALLBACK_URL) ?? ''}
/>
</div>
<SubmitButtonWithStatus disabled={!isFormValid}>
Sign in

View File

@ -1,6 +1,13 @@
'use server';
import { CREDENTIALS_SIGN_IN_ERROR, signIn, signOut } from '@/auth';
import {
KEY_CALLBACK_URL,
KEY_CREDENTIALS_SIGN_IN_ERROR,
signIn,
signOut,
} from '@/auth';
import { PATH_ADMIN_PHOTOS } from '@/site/paths';
import { redirect } from 'next/navigation';
export const signInAction = async (
_prevState: string | undefined,
@ -9,13 +16,15 @@ export const signInAction = async (
try {
await signIn('credentials', Object.fromEntries(formData));
} catch (error) {
if ((`${error}`).includes(CREDENTIALS_SIGN_IN_ERROR)) {
return CREDENTIALS_SIGN_IN_ERROR;
} else {
console.log('Next Auth Error', error);
if (`${error}`.includes(KEY_CREDENTIALS_SIGN_IN_ERROR)) {
// Rethrow credentials error to display on the sign in page.
return KEY_CREDENTIALS_SIGN_IN_ERROR;
} else if (!`${error}`.includes('NEXT_REDIRECT')) {
// Rethrow non-redirect errors
throw error;
}
throw error;
}
redirect(formData.get(KEY_CALLBACK_URL) as string || PATH_ADMIN_PHOTOS);
};
export const signOutAction = async () => {

View File

@ -2,7 +2,8 @@ import { isPathProtected } from '@/site/paths';
import NextAuth, { User } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
export const CREDENTIALS_SIGN_IN_ERROR = 'CredentialsSignin';
export const KEY_CREDENTIALS_SIGN_IN_ERROR = 'CredentialsSignin';
export const KEY_CALLBACK_URL = 'callbackUrl';
export const {
handlers: { GET, POST },