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.
104 lines
2.4 KiB
104 lines
2.4 KiB
import express from 'express';
|
|
import bcrypt from 'bcryptjs';
|
|
import User from '../models/User.js';
|
|
|
|
const router = express.Router();
|
|
|
|
// Register route
|
|
router.post('/register', async (req, res) => {
|
|
try {
|
|
const { email, password, name } = req.body;
|
|
|
|
// Check if user exists
|
|
const existingUser = await User.findOne({ email });
|
|
if (existingUser) {
|
|
return res.status(400).json({ message: 'User already exists' });
|
|
}
|
|
|
|
// Create new user
|
|
const user = new User({
|
|
email,
|
|
password,
|
|
name
|
|
});
|
|
|
|
await user.save();
|
|
|
|
res.status(201).json({ message: 'Registration successful' });
|
|
} catch (error) {
|
|
console.error('Registration error:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Login route
|
|
router.post('/login', async (req, res) => {
|
|
try {
|
|
const { email, password } = req.body;
|
|
|
|
// Find user
|
|
const user = await User.findOne({ email });
|
|
if (!user) {
|
|
return res.status(401).json({ message: 'Invalid email or password' });
|
|
}
|
|
|
|
// Check password
|
|
const isMatch = await bcrypt.compare(password, user.password);
|
|
if (!isMatch) {
|
|
return res.status(401).json({ message: 'Invalid email or password' });
|
|
}
|
|
|
|
// Create session
|
|
req.session.userId = user._id;
|
|
|
|
res.json({
|
|
message: 'Login successful',
|
|
user: {
|
|
id: user._id,
|
|
name: user.name,
|
|
email: user.email,
|
|
role: user.role
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('Login error:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Get current user
|
|
router.get('/current_user', async (req, res) => {
|
|
try {
|
|
if (!req.session.userId) {
|
|
return res.status(401).json({ message: 'Not authenticated' });
|
|
}
|
|
|
|
const user = await User.findById(req.session.userId);
|
|
if (!user) {
|
|
return res.status(401).json({ message: 'User not found' });
|
|
}
|
|
|
|
res.json({
|
|
id: user._id,
|
|
name: user.name,
|
|
email: user.email,
|
|
role: user.role
|
|
});
|
|
} catch (error) {
|
|
console.error('Error getting current user:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Logout route
|
|
router.post('/logout', (req, res) => {
|
|
req.session.destroy((err) => {
|
|
if (err) {
|
|
console.error('Logout error:', err);
|
|
return res.status(500).json({ message: 'Error logging out' });
|
|
}
|
|
res.json({ message: 'Logged out successfully' });
|
|
});
|
|
});
|
|
|
|
export default router; |