Skip to content
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 client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"socket.io-client": "^4.8.1"
"socket.io-client": "^4.8.1",
"zod": "^4.3.5"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
Expand Down
23 changes: 7 additions & 16 deletions client/src/components/auth/AuthForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { User, Lock, UserPlus, LogIn, Mail, Shield } from "lucide-react";
import { login, signup, sendOTP } from "../../utils/api";

import PasswordInput from "../ui/PasswordInput";
interface AuthFormProps {
onAuthChange: () => void;
}
Expand Down Expand Up @@ -210,22 +210,13 @@ const AuthForm: React.FC<AuthFormProps> = ({ onAuthChange }) => {
<label className="block text-sm font-medium text-gray-300 mb-2">
Password
</label>
<div className="relative">
<Lock
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={20}
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="alien-input w-full pl-10"
placeholder="Enter your password"
required
/>
</div>
<PasswordInput
value={password}
onChange={(e) => setPassword(e.target.value)}
className="alien-input" // This keeps your project's green/black theme
placeholder="Enter your password"
/>
</div>

{error && (
<div className="bg-red-900/50 border border-red-500 text-red-200 px-4 py-3 rounded-lg">
{error}
Expand Down
164 changes: 164 additions & 0 deletions client/src/components/ui/PasswordInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import React, { useState, useEffect } from 'react';
import { Eye, EyeOff, KeyRound } from 'lucide-react';

import { passwordSchema } from '../../schemas/auth.schema';

interface PasswordInputProps {
value: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
placeholder?: string;
name?: string;
id?: string;
className?: string;
}


const PasswordInput: React.FC<PasswordInputProps> = ({
value,
onChange,
placeholder = "Enter password",
name,
id,
className = ""
}) => {
const [showPassword, setShowPassword] = useState(false);
const [strength, setStrength] = useState(0);
const [errors, setErrors] = useState<string[]>([]); // New state for Zod errors


const calculateVisualStrength = (password: string) => {
let score = 0;
if (!password) return 0;
if (password.length > 8) score++;
if (/[A-Z]/.test(password)) score++;
if (/[0-9]/.test(password)) score++;
if (/[^A-Za-z0-9]/.test(password)) score++;
return score;
};


useEffect(() => {
// Run the text against the shared schema
const result = passwordSchema.safeParse(value);

if (!result.success) {
// If invalid, extract the specific error messages
const errorMessages = result.error.issues.map((issue) => issue.message);
setErrors(errorMessages);
} else {
// If valid, clear errors
setErrors([]);
}

// Update the visual strength meter
setStrength(calculateVisualStrength(value));
}, [value]);

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e);
// Validation is handled by the useEffect above
};

const generatePassword = () => {
// 1. Define sets
const lower = "abcdefghijklmnopqrstuvwxyz";
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const nums = "0123456789";
const special = "!@#$%^&*";
const allChars = lower + upper + nums + special;

let generated = "";

// 2. GUARANTEE one of each required type
generated += lower[Math.floor(Math.random() * lower.length)];
generated += upper[Math.floor(Math.random() * upper.length)];
generated += nums[Math.floor(Math.random() * nums.length)];
generated += special[Math.floor(Math.random() * special.length)];

// 3. Fill the rest (aiming for length 12-14)
for (let i = generated.length; i < 14; i++) {
generated += allChars[Math.floor(Math.random() * allChars.length)];
}

// 4. Shuffle the result so the pattern isn't predictable
generated = generated.split('').sort(() => 0.5 - Math.random()).join('');

const event = {
target: { name, value: generated }
} as React.ChangeEvent<HTMLInputElement>;

handleInputChange(event);
};

const getStrengthColor = (score: number) => {
if (score < 2) return 'bg-red-500';
if (score < 3) return 'bg-yellow-500';
return 'bg-green-500';
};

const getStrengthLabel = (score: number) => {
const labels = ['Weak', 'Fair', 'Good', 'Strong', 'Excellent'];
return labels[score] || 'Weak';
};

return (
<div className="w-full">
<div className="relative">
<input
type={showPassword ? "text" : "password"}
name={name}
id={id}
value={value}
onChange={handleInputChange}
placeholder={placeholder}
// Add red border if there are validation errors
className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
errors.length > 0 && value.length > 0 ? 'border-red-500 focus:ring-red-500' : 'border-gray-300'
} ${className}`}
/>

<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 focus:outline-none"
>
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
</button>
</div>

<div className="flex justify-between items-start mt-2 min-h-[1.5rem]">
{value ? (
<div className="flex flex-col gap-1">
{/* Visual Bar */}
<div className="flex items-center gap-2">
<div className={`h-1.5 w-16 rounded-full transition-colors duration-300 ${getStrengthColor(strength)}`} />
<span className={`text-xs font-medium transition-colors duration-300 ${strength < 2 ? 'text-red-500' : strength < 3 ? 'text-yellow-500' : 'text-green-500'}`}>
{getStrengthLabel(strength)}
</span>
</div>

{/* Zod Error Messages Displayed Here */}
{errors.length > 0 && (
<ul className="text-red-500 text-[10px] list-disc pl-3 leading-tight">
{errors.slice(0, 3).map((err, idx) => ( // Limit to showing first 3 errors to save space
<li key={idx}>{err}</li>
))}
</ul>
)}
</div>
) : <div />}

<button
type="button"
onClick={generatePassword}
className="flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 font-medium ml-auto whitespace-nowrap"
>
<KeyRound size={14} />
Suggest Strong Password
</button>
</div>
</div>
);
};

export default PasswordInput;
61 changes: 61 additions & 0 deletions client/src/schemas/auth.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// src/schemas/auth.schema.ts
import { z } from 'zod';


export const passwordSchema = z
.string()
.min(8, 'Password must be at least 8 characters long')
.regex(/[a-z]/, 'Password must include at least one lowercase letter')
.regex(/[A-Z]/, 'Password must include at least one uppercase letter')
.regex(/[0-9]/, 'Password must include at least one number')
.regex(
/[^A-Za-z0-9]/,
'Password must include at least one special character (! @#$%^&*... )'
)
.refine(
(password: string) => {
// Block common passwords
const commonPasswords = [
'password', 'password123', '123456', '123456789', '12345678',
'qwerty', 'abc123', 'monkey', '1234567', 'letmein',
'trustno1', 'dragon', 'baseball', 'iloveyou', 'master',
'sunshine', 'ashley', 'bailey', 'shadow', 'superman',
'qazwsx', 'welcome', 'admin', 'login', 'passw0rd'
];
return !commonPasswords.includes(password.toLowerCase());
},
{ message: 'This password is too common. Please choose a more secure password' }
)
.refine(
(password: string) => {
// Block sequential characters (abc, 123)
const sequential = /(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i;
return !sequential.test(password);
},
{ message: 'Password should not contain sequential characters (e.g., "abc", "123")' }
)
.refine(
(password: string) => {
// Block repeated characters (aaa, 111)
return !/(.)\1{2,}/.test(password);
},
{ message: 'Password should not contain repeated characters (e.g., "aaa", "111")' }
);

export type PasswordType = z.infer<typeof passwordSchema>;

// Signup Schema (Optional, if you need the full object validation)
export const signupSchema = z.object({
username: z
.string()
.min(3, 'Username must be at least 3 characters')
.max(30, 'Username must not exceed 30 characters')
.regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'),
email: z
.string()
.email('Please enter a valid email address'),
password: passwordSchema,
otp: z.string().optional()
});

export type SignupType = z.infer<typeof signupSchema>;