Skip to content

fix: password length validation and error handling #1773

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,15 @@
"typescript": "^5.4.5",
"vitest": "^1.6.0",
"vitest-mock-extended": "^1.3.1"
}
},
"pnpm": {
"onlyBuiltDependencies": [
"@prisma/client",
"@prisma/engines",
"bcrypt",
"esbuild",
"prisma"
]
},
"packageManager": "[email protected]+sha512.da9dc28cd3ff40d0592188235ab25d3202add8a207afbedc682220e4a0029ffbff4562102b9e6e46b4e3f9e8bd53e6d05de48544b0c57d4b0179e22c76d1199b"
}
8 changes: 2 additions & 6 deletions src/app/api/admin/services/externalLogin/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { z } from 'zod';
import db from '@/db';
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcrypt';

const loginSchema = z.object({
email: z.string(),
password: z.string(),
});
import { loginSchema } from '@/lib/validations/auth';

export async function POST(req: NextRequest) {
const authKey = req.headers.get('Auth-Key');
Expand Down Expand Up @@ -77,6 +72,7 @@ export async function POST(req: NextRequest) {
{ status: 401 },
);
} catch (error) {
console.log(error);
return NextResponse.json(
{ message: 'Error fetching user' },
{ status: 500 },
Expand Down
9 changes: 2 additions & 7 deletions src/app/api/mobile/signin/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import db from '@/db';
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcrypt';
import { z } from 'zod';
import { importJWK, JWTPayload, SignJWT } from 'jose';

const requestBodySchema = z.object({
email: z.string().email(),
password: z.string(),
});
import { loginSchema } from '@/lib/validations/auth';

const generateJWT = async (payload: JWTPayload) => {
const secret = process.env.JWT_SECRET || '';
Expand All @@ -31,7 +26,7 @@ export async function POST(req: NextRequest) {

try {
const body = await req.json();
const parseResult = requestBodySchema.safeParse(body);
const parseResult = loginSchema.safeParse(body);

if (!parseResult.success) {
return NextResponse.json(
Expand Down
37 changes: 28 additions & 9 deletions src/components/Signin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useRouter } from 'next/navigation';
import React, { useRef, useState, useEffect } from 'react';
import { toast } from 'sonner';
import { motion } from 'framer-motion';
import { loginSchema } from '@/lib/validations/auth';

const emailDomains = [
'gmail.com',
Expand All @@ -24,6 +25,7 @@ const Signin = () => {
const [requiredError, setRequiredError] = useState({
emailReq: false,
passReq: false,
passLength: false,
});
const [suggestedDomains, setSuggestedDomains] =
useState<string[]>(emailDomains);
Expand Down Expand Up @@ -109,20 +111,29 @@ const Signin = () => {
};

const handleSubmit = async (e?: React.FormEvent<HTMLButtonElement>) => {
const loadId = toast.loading('Signing in...');
if (e) {
e.preventDefault();
}

if (!email.current || !password.current) {
// Validate credentials using Zod schema
const validationResult = loginSchema.safeParse({
email: email.current,
password: password.current,
});

if (!validationResult.success) {
const errors = validationResult.error.errors;
setRequiredError({
emailReq: email.current ? false : true,
passReq: password.current ? false : true,
emailReq: errors.some((err) => err.path[0] === 'email'),
passReq: errors.some((err) => err.path[0] === 'password'),
passLength: errors.some((err) => err.path[0] === 'password' && err.message.includes('6 characters')),
});
toast.dismiss(loadId);
return;
}

const loadId = toast.loading('Signing in...');
setCheckingPassword(true);

const res = await signIn('credentials', {
username: email.current,
password: password.current,
Expand Down Expand Up @@ -239,7 +250,7 @@ const Signin = () => {
</div>
<div className="relative flex flex-col gap-2">
<Label>Password</Label>
<div className="flex">
<div className="relative flex">
<Input
className="focus:ring-none border-none bg-primary/5 focus:outline-none"
name="password"
Expand All @@ -251,6 +262,7 @@ const Signin = () => {
setRequiredError((prevState) => ({
...prevState,
passReq: false,
passLength: false,
}));
password.current = e.target.value;
}}
Expand All @@ -262,7 +274,8 @@ const Signin = () => {
}}
/>
<button
className="absolute bottom-0 right-0 flex h-10 items-center px-4 text-neutral-500"
type="button"
className="absolute right-0 flex h-full items-center px-3 text-neutral-500"
onClick={togglePasswordVisibility}
>
{isPasswordVisible ? (
Expand Down Expand Up @@ -303,8 +316,14 @@ const Signin = () => {
)}
</button>
</div>
{requiredError.passReq && (
<span className="text-red-500">Password is required</span>
{password.current ? (
requiredError.passLength && (
<span className="text-red-500">Password must be at least 6 characters</span>
)
) : (
requiredError.passReq && (
<span className="text-red-500">Password is required</span>
)
)}
</div>
</div>
Expand Down
10 changes: 10 additions & 0 deletions src/lib/validations/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from 'zod';

export const passwordSchema = z.string().min(6, {
message: 'Password must be at least 6 characters long',
});

export const loginSchema = z.object({
email: z.string().email({ message: 'Please enter a valid email address' }),
password: passwordSchema,
});