You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.0 KiB
85 lines
2.0 KiB
|
7 months ago
|
import { NextRequest, NextResponse } from "next/server";
|
||
|
|
import { getPool } from "@/lib/database";
|
||
|
|
import bcrypt from "bcryptjs";
|
||
|
|
import jwt from "jsonwebtoken";
|
||
|
|
|
||
|
|
export async function POST(request: NextRequest) {
|
||
|
|
try {
|
||
|
|
const { email, password } = await request.json();
|
||
|
|
|
||
|
|
// Validate input
|
||
|
|
if (!email || !password) {
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: "Email and password are required" },
|
||
|
|
{ status: 400 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
const pool = getPool();
|
||
|
|
const client = await pool.connect();
|
||
|
|
|
||
|
|
try {
|
||
|
|
// Find user by email
|
||
|
|
const result = await client.query(
|
||
|
|
`SELECT id, email, password_hash, first_name, last_name, role, subscription_tier, created_at
|
||
|
|
FROM users WHERE email = $1`,
|
||
|
|
[email]
|
||
|
|
);
|
||
|
|
|
||
|
|
if (result.rows.length === 0) {
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: "Invalid email or password" },
|
||
|
|
{ status: 401 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
const user = result.rows[0];
|
||
|
|
|
||
|
|
// Verify password
|
||
|
|
const isValidPassword = await bcrypt.compare(
|
||
|
|
password,
|
||
|
|
user.password_hash
|
||
|
|
);
|
||
|
|
if (!isValidPassword) {
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: "Invalid email or password" },
|
||
|
|
{ status: 401 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Create JWT token
|
||
|
|
const token = jwt.sign(
|
||
|
|
{
|
||
|
|
userId: user.id,
|
||
|
|
email: user.email,
|
||
|
|
role: user.role,
|
||
|
|
},
|
||
|
|
process.env.JWT_SECRET || "your-secret-key",
|
||
|
|
{ expiresIn: "7d" }
|
||
|
|
);
|
||
|
|
|
||
|
|
return NextResponse.json({
|
||
|
|
success: true,
|
||
|
|
token,
|
||
|
|
user: {
|
||
|
|
id: user.id,
|
||
|
|
email: user.email,
|
||
|
|
FirstName: user.first_name,
|
||
|
|
LastName: user.last_name,
|
||
|
|
role: user.role,
|
||
|
|
subscriptionTier: user.subscription_tier,
|
||
|
|
createdAt: user.created_at,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
} finally {
|
||
|
|
client.release();
|
||
|
|
}
|
||
|
|
} catch (error) {
|
||
|
|
console.error("Login error:", error);
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: "Internal server error" },
|
||
|
|
{ status: 500 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|