File size: 6,889 Bytes
057576a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const generateToken = (userId) => {
return jwt.sign({ userId }, process.env.JWT_SECRET || 'fallback-secret', {
expiresIn: process.env.JWT_EXPIRES_IN || '30d'
});
};
exports.register = async (req, res) => {
try {
const { username, email, password, displayName } = req.body;
console.log('π Registration attempt:', { username, email, displayName });
// Validation
if (!username || !email || !password || !displayName) {
return res.status(400).json({ error: 'All fields are required' });
}
if (!validator.isEmail(email)) {
return res.status(400).json({ error: 'Invalid email format' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters' });
}
if (username.length < 3 || username.length > 30) {
return res.status(400).json({ error: 'Username must be between 3 and 30 characters' });
}
if (displayName.length < 2 || displayName.length > 50) {
return res.status(400).json({ error: 'Display name must be between 2 and 50 characters' });
}
// Check if user exists
const existingUser = await User.findOne({
$or: [{ email }, { username }]
});
if (existingUser) {
const field = existingUser.email === email ? 'email' : 'username';
return res.status(400).json({ error: `User already exists with this ${field}` });
}
// Create user
const user = await User.create({
username,
email,
password,
displayName,
status: 'online'
});
// Generate token
const token = generateToken(user._id);
res.status(201).json({
message: 'User registered successfully',
user: {
id: user._id,
username: user.username,
email: user.email,
displayName: user.displayName,
avatar: user.avatar,
status: user.status,
bio: user.bio,
lastSeen: user.lastSeen
},
token
});
} catch (error) {
console.error('β Registration error:', error);
if (error.name === 'ValidationError') {
const errors = Object.values(error.errors).map(err => err.message);
return res.status(400).json({ error: errors.join(', ') });
}
if (error.code === 11000) {
return res.status(400).json({ error: 'Username or email already exists' });
}
res.status(500).json({ error: 'Server error during registration' });
}
};
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
console.log('π Login attempt:', { email });
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
// Find user and include password for comparison
const user = await User.findOne({ email }).select('+password');
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Check password
const isPasswordValid = await user.comparePassword(password);
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Update status to online
user.status = 'online';
user.lastSeen = new Date();
await user.save();
const token = generateToken(user._id);
res.json({
message: 'Login successful',
user: {
id: user._id,
username: user.username,
email: user.email,
displayName: user.displayName,
avatar: user.avatar,
status: user.status,
bio: user.bio,
lastSeen: user.lastSeen,
settings: user.settings
},
token
});
} catch (error) {
console.error('β Login error:', error);
res.status(500).json({ error: 'Server error during login' });
}
};
exports.logout = async (req, res) => {
try {
// Update user status to offline
if (req.user && req.user.userId) {
await User.findByIdAndUpdate(req.user.userId, {
status: 'offline',
lastSeen: new Date()
});
}
res.json({ message: 'Logged out successfully' });
} catch (error) {
console.error('β Logout error:', error);
res.status(500).json({ error: 'Server error during logout' });
}
};
exports.getMe = async (req, res) => {
try {
const user = await User.findById(req.user.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
user: {
id: user._id,
username: user.username,
email: user.email,
displayName: user.displayName,
avatar: user.avatar,
status: user.status,
bio: user.bio,
lastSeen: user.lastSeen,
settings: user.settings,
createdAt: user.createdAt
}
});
} catch (error) {
console.error('β Get me error:', error);
res.status(500).json({ error: 'Server error' });
}
};
exports.updateProfile = async (req, res) => {
try {
const { displayName, bio, status } = req.body;
const updateData = {};
if (displayName) {
if (displayName.length < 2 || displayName.length > 50) {
return res.status(400).json({ error: 'Display name must be between 2 and 50 characters' });
}
updateData.displayName = displayName;
}
if (bio !== undefined) {
if (bio.length > 500) {
return res.status(400).json({ error: 'Bio must be less than 500 characters' });
}
updateData.bio = bio;
}
if (status && ['online', 'offline', 'away', 'busy'].includes(status)) {
updateData.status = status;
}
const user = await User.findByIdAndUpdate(
req.user.userId,
updateData,
{ new: true, runValidators: true }
);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
message: 'Profile updated successfully',
user: {
id: user._id,
username: user.username,
email: user.email,
displayName: user.displayName,
avatar: user.avatar,
status: user.status,
bio: user.bio,
lastSeen: user.lastSeen
}
});
} catch (error) {
console.error('β Update profile error:', error);
if (error.name === 'ValidationError') {
const errors = Object.values(error.errors).map(err => err.message);
return res.status(400).json({ error: errors.join(', ') });
}
res.status(500).json({ error: 'Server error during profile update' });
}
}; |