Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions frontend/app/api/auth/password-reset/confirm/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,52 @@ import { z } from 'zod';
import { db } from '@/db';
import { passwordResetTokens } from '@/db/schema/passwordResetTokens';
import { users } from '@/db/schema/users';
import {
PASSWORD_MAX_BYTES,
PASSWORD_MIN_LEN,
PASSWORD_POLICY_REGEX,
} from '@/lib/auth/signup-constraints';

const schema = z.object({
token: z.string().uuid(),
password: z.string().min(8),
password: z
.string()
.min(
PASSWORD_MIN_LEN,
`Password must be at least ${PASSWORD_MIN_LEN} characters`
)
.regex(/[A-Z]/, 'Password must contain at least one capital letter')
.regex(
/[^A-Za-z0-9]/,
'Password must contain at least one special character'
)
.regex(PASSWORD_POLICY_REGEX, 'Password does not meet the required policy')
.refine(
val => Buffer.byteLength(val, 'utf8') <= PASSWORD_MAX_BYTES,
`Password must be at most ${PASSWORD_MAX_BYTES} bytes`
),
});

function firstFieldErrorMessage(
fieldErrors: Record<string, string[] | undefined>
): string | null {
for (const key of Object.keys(fieldErrors)) {
const msgs = fieldErrors[key];
if (Array.isArray(msgs) && msgs.length > 0 && msgs[0]) {
return msgs[0];
}
}
return null;
}

export async function POST(req: Request) {
const body = await req.json().catch(() => null);
const parsed = schema.safeParse(body);

if (!parsed.success) {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
const flattened = parsed.error.flatten().fieldErrors;
const firstMsg = firstFieldErrorMessage(flattened) ?? 'Invalid request';
return NextResponse.json({ error: firstMsg }, { status: 400 });
}

const { token, password } = parsed.data;
Expand Down Expand Up @@ -60,4 +94,4 @@ export async function POST(req: Request) {
await db.update(users).set({ passwordHash }).where(eq(users.id, userId));

return NextResponse.json({ success: true });
}
}
61 changes: 51 additions & 10 deletions frontend/app/api/auth/signup/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,60 @@ import { z } from 'zod';
import { db } from '@/db';
import { users } from '@/db/schema/users';
import { createEmailVerificationToken } from '@/lib/auth/email-verification';
import {
EMAIL_MAX_LEN,
EMAIL_MIN_LEN,
NAME_MAX_LEN,
NAME_MIN_LEN,
PASSWORD_MAX_BYTES,
PASSWORD_MIN_LEN,
PASSWORD_POLICY_REGEX,
} from '@/lib/auth/signup-constraints';
import { sendVerificationEmail } from '@/lib/email/sendVerificationEmail';
import { resolveBaseUrl } from '@/lib/http/getBaseUrl';

export const runtime = 'nodejs';

const signupSchema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});
const passwordSchema = z
.string()
.min(
PASSWORD_MIN_LEN,
`Password must be at least ${PASSWORD_MIN_LEN} characters`
)
.regex(/[A-Z]/, 'Password must contain at least one capital letter')
.regex(/[^A-Za-z0-9]/, 'Password must contain at least one special character')
.regex(PASSWORD_POLICY_REGEX, 'Password does not meet the required policy')
.refine(
val => Buffer.byteLength(val, 'utf8') <= PASSWORD_MAX_BYTES,
`Password must be at most ${PASSWORD_MAX_BYTES} bytes`
);

const signupSchema = z
.object({
name: z
.string()
.trim()
.min(NAME_MIN_LEN, `Name must be at least ${NAME_MIN_LEN} characters`)
.max(NAME_MAX_LEN, `Name must be at most ${NAME_MAX_LEN} characters`),
email: z
.string()
.trim()
.min(EMAIL_MIN_LEN, `Email must be at least ${EMAIL_MIN_LEN} characters`)
.max(EMAIL_MAX_LEN, `Email must be at most ${EMAIL_MAX_LEN} characters`)
.email('Invalid email'),
password: passwordSchema,

confirmPassword: z.string(),
})
.superRefine((val, ctx) => {
if (val.password !== val.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['confirmPassword'],
message: 'Passwords do not match',
});
}
});

export async function POST(req: Request) {
try {
Expand Down Expand Up @@ -74,10 +118,7 @@ export async function POST(req: Request) {
});

return NextResponse.json(
{
success: true,
verificationRequired: true,
},
{ success: true, verificationRequired: true },
{ status: 201 }
);
} catch (error) {
Expand All @@ -88,4 +129,4 @@ export async function POST(req: Request) {
{ status: 500 }
);
}
}
}
85 changes: 77 additions & 8 deletions frontend/components/auth/ResetPasswordForm.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,66 @@
'use client';

import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { useMemo, useState } from 'react';

import { AuthErrorBanner } from '@/components/auth/AuthErrorBanner';
import { AuthShell } from '@/components/auth/AuthShell';
import { AuthSuccessBanner } from '@/components/auth/AuthSuccessBanner';
import { PasswordField } from '@/components/auth/fields/PasswordField';
import { Button } from '@/components/ui/button';
import {
PASSWORD_MAX_BYTES,
PASSWORD_MIN_LEN,
PASSWORD_POLICY_REGEX,
} from '@/lib/auth/signup-constraints';

type ResetPasswordFormProps = {
token: string;
};

function utf8ByteLength(value: string): number {
return new TextEncoder().encode(value).length;
}

export function ResetPasswordForm({ token }: ResetPasswordFormProps) {
const t = useTranslations('auth.resetPassword');
const tf = useTranslations('auth.fields');

const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);

const [passwordValue, setPasswordValue] = useState('');
const [passwordTouched, setPasswordTouched] = useState(false);

const passwordPolicyOk = useMemo(() => {
if (!passwordValue) return false;
if (passwordValue.length < PASSWORD_MIN_LEN) return false;
if (!PASSWORD_POLICY_REGEX.test(passwordValue)) return false;
if (utf8ByteLength(passwordValue) > PASSWORD_MAX_BYTES) return false;
return true;
}, [passwordValue]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const passwordRequirementsText = tf('validation.passwordRequirements', {
PASSWORD_MIN_LEN,
PASSWORD_MAX_BYTES,
});

const passwordErrorText =
passwordTouched && !passwordPolicyOk
? tf('validation.invalidPassword', { passwordRequirementsText })
: null;

const passwordBytesTooLong =
passwordTouched &&
utf8ByteLength(passwordValue) > PASSWORD_MAX_BYTES;
Comment thread
kryvosheyin marked this conversation as resolved.

const submitDisabled = loading || !passwordPolicyOk;

async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
if (submitDisabled) return;

setLoading(true);
setError(null);

Expand All @@ -29,17 +69,21 @@ export function ResetPasswordForm({ token }: ResetPasswordFormProps) {
try {
const res = await fetch('/api/auth/password-reset/confirm', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token,
password: formData.get('password'),
}),
});

const data = await res.json().catch(() => null);

if (!res.ok) {
setError(t('errors.resetFailed'));
const msg =
typeof data?.error === 'string'
? data.error
: t('errors.resetFailed');
setError(msg);
return;
}

Expand All @@ -57,15 +101,40 @@ export function ResetPasswordForm({ token }: ResetPasswordFormProps) {
<AuthSuccessBanner message={t('success')} />
) : (
<form onSubmit={onSubmit} className="space-y-4">
<PasswordField minLength={8} />
<div className="space-y-1">
<PasswordField
id="password"
name="password"
placeholder={tf('setNewPassword')}
autoComplete="new-password"
minLength={PASSWORD_MIN_LEN}
pattern={PASSWORD_POLICY_REGEX.source}
onChange={setPasswordValue}
onBlur={() => setPasswordTouched(true)}
/>

{passwordErrorText && (
<p className="text-sm text-red-600">
{passwordErrorText}
</p>
)}

{passwordBytesTooLong && (
<p className="text-sm text-red-600">
{tf('validation.passwordTooLongBytes', {
PASSWORD_MAX_BYTES,
})}
</p>
)}
</div>

{error && <AuthErrorBanner message={error} />}

<Button type="submit" disabled={loading} className="w-full">
<Button type="submit" disabled={submitDisabled} className="w-full">
{loading ? t('submitting') : t('submit')}
</Button>
</form>
)}
</AuthShell>
);
}
}
Loading