Skip to content

Commit

Permalink
registering and logging in modification
Browse files Browse the repository at this point in the history
  • Loading branch information
Ndi-Shema committed Jul 30, 2024
1 parent 3b78016 commit 6a1a6ed
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,48 @@ const User = require('../models/user');
exports.register = async (req, res) => {
try {
const { username, email, password } = req.body;

// Validate input
if (!username || !email || !password) {
return res.status(400).json({ message: 'All fields are required' });
}

// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: 'Email already registered' });
}

// Create and save new user
const newUser = new User({ username, email, password });
await newUser.save();

res.status(201).json({ message: 'User registered successfully', user: newUser });
} catch (error) {
res.status(400).json({ message: 'Error registering user', error });
console.error(error); // Log the error for debugging
res.status(500).json({ message: 'Error registering user', error });
}
};

exports.login = async (req, res) => {
try {
const { email, password } = req.body;

// Validate input
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}

// Find the user
const user = await User.findOne({ email });
if (!user || !(await user.comparePassword(password))) {
return res.status(401).json({ message: 'Invalid email or password' });
}

res.status(200).json({ message: 'Login successful', user });
} catch (error) {
res.status(400).json({ message: 'Error logging in', error });
console.error(error); // Log the error for debugging
res.status(500).json({ message: 'Error logging in', error });
}
};

0 comments on commit 6a1a6ed

Please sign in to comment.