text-dataset-tiny-code-script-py-format
/
ysnrfd_messenger
/BACKUP2
/backend
/src
/controllers
/authController.js
| 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' }); | |
| } | |
| }; |