estatesfunding/ef-api/controllers/admin.js

33 lines
832 B
JavaScript

import dotenv from "dotenv";
import mongoose from 'mongoose';
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import adminModal from "../models/admin.js"
dotenv.config();
const secret = process.env.SECRET_KEY;
export const login = async (req, res) => {
const { username, password } = req.body;
try {
const user = await adminModal.findOne({ username });
if (!user) return res.status(400).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid password" });
const token = jwt.sign({ userId: user._id }, secret, { expiresIn: "1h" });
res.json({ token });
} catch (error) {
res.status(500).json({ message: "Server error" });
}
};