83 lines
1.8 KiB
JavaScript
83 lines
1.8 KiB
JavaScript
const jwt = require('jsonwebtoken');
|
|
const User = require('../models/User');
|
|
const { validationResult } = require('express-validator');
|
|
|
|
// Helper function to generate JWT
|
|
const generateToken = (id) => {
|
|
return jwt.sign({ id }, process.env.JWT_SECRET, {
|
|
expiresIn: process.env.JWT_EXPIRATION || '24h'
|
|
});
|
|
};
|
|
|
|
// @desc Login user
|
|
// @route POST /api/auth/login
|
|
// @access Public
|
|
exports.login = async (req, res, next) => {
|
|
try {
|
|
const errors = validationResult(req);
|
|
if (!errors.isEmpty()) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
errors: errors.array()
|
|
});
|
|
}
|
|
|
|
const { email, password } = req.body;
|
|
|
|
// Check if user exists
|
|
const user = await User.findOne({ email }).select('+password');
|
|
|
|
if (!user) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
message: 'Invalid credentials'
|
|
});
|
|
}
|
|
|
|
// Check if password matches
|
|
const isMatch = await user.comparePassword(password);
|
|
|
|
if (!isMatch) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
message: 'Invalid credentials'
|
|
});
|
|
}
|
|
|
|
// Generate token
|
|
const token = generateToken(user._id);
|
|
|
|
// Remove password from response
|
|
const userResponse = {
|
|
_id: user._id,
|
|
email: user.email,
|
|
role: user.role,
|
|
companyId: user.companyId
|
|
};
|
|
|
|
res.status(200).json({
|
|
success: true,
|
|
token,
|
|
user: userResponse
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
// @desc Get current logged in user
|
|
// @route GET /api/auth/me
|
|
// @access Private
|
|
exports.getMe = async (req, res, next) => {
|
|
try {
|
|
const user = await User.findById(req.user.id).select('-password');
|
|
|
|
res.status(200).json({
|
|
success: true,
|
|
data: user
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|