HrMateRepository/src/app/login/page.js
2025-04-07 14:21:07 +05:30

69 lines
2.2 KiB
JavaScript

'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { account, ID } from "../lib/appwrite";
export default function AuthPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [err, setErr] = useState('');
const [isLogin, setIsLogin] = useState(true);
const handleAuth = async (e) => {
e.preventDefault();
try {
if (isLogin) {
await account.createEmailPasswordSession(email, password);
router.push('/pages/dashboard');
} else {
await account.create(ID.unique(), email, password);
// Automatically log in after sign up
await account.createEmailPasswordSession(email, password);
router.push('/pages/dashboard');
}
} catch (error) {
console.error('Auth error:', error);
setErr(error.message || 'Something went wrong');
}
};
return (
<div className="flex items-center justify-center min-h-screen">
<form onSubmit={handleAuth} className="bg-white p-6 rounded shadow-md w-full max-w-sm">
<h2 className="text-xl font-semibold mb-4">{isLogin ? 'Login' : 'Sign Up'}</h2>
{err && <p className="text-red-500 mb-4">{err}</p>}
<input
type="email"
placeholder="Email"
className="w-full mb-2 p-2 border rounded"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
className="w-full mb-4 p-2 border rounded"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength="8"
/>
<button type="submit" className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded w-full mb-4">
{isLogin ? 'Login' : 'Sign Up'}
</button>
<button
type="button"
onClick={() => {
setIsLogin(!isLogin);
setErr('');
}}
className="text-blue-500 hover:text-blue-700 text-sm"
>
{isLogin ? 'Need an account? Sign Up' : 'Already have an account? Login'}
</button>
</form>
</div>
);
}