import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
const JWT_SECRET = process.env.JWT_SECRET;
const JWT_EXPIRES_IN = '7d';
interface User {
id: string;
email: string;
password: string;
}
async function verifyToken(token: string): Promise<any> {
try {
return jwt.verify(token, JWT_SECRET);
} catch (error) {
throw new Error('Invalid token');
}
}
async function authenticateUser(email: string, password: string): Promise<string> {
const user = await getUserByEmail(email);
if (!user) {
throw new Error('User not found');
}
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
throw new Error('Invalid credentials');
}
const token = jwt.sign(
{ id: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
return token;
}
// Usage in API route
export async function POST(request: Request) {
const { email, password } = await request.json();
const token = await authenticateUser(email, password);
return Response.json({
success: true,
token,
user: { id, email }
});
}