1714825713

Practical project to develop a login and registration system in Node.js


Basic example of a Node.js application implementing a login and registration system using Express.js and bcrypt for password hashing. This example will not include database integration, but you can easily extend it to work with a database like MongoDB or MySQL. Let's set up the project structure: ```bash project/ │ ├── app.js ├── controllers/ │ ├── authController.js ├── models/ │ └── User.js ├── routes/ │ └── authRoutes.js └── views/ ├── login.html └── register.html ``` Now, let's start with the code: 1. **app.js**: This file sets up the Express server and defines middleware. ```js const express = require('express'); const bodyParser = require('body-parser'); const authRoutes = require('./routes/authRoutes'); const app = express(); const PORT = process.env.PORT || 3000; // Middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Routes app.use('/auth', authRoutes); // Start server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); ``` 2. **controllers/authController.js**: This file contains controller functions for handling user registration and login. ```js const bcrypt = require('bcryptjs'); const User = require('../models/User'); // Register a new user exports.register = async (req, res) => { try { const { username, email, password } = req.body; // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Create a new user const user = new User({ username, email, password: hashedPassword }); await user.save(); res.status(201).json({ message: 'User registered successfully' }); } catch (err) { console.error(err); res.status(500).json({ error: 'Server error' }); } }; // Login user exports.login = async (req, res) => { try { const { email, password } = req.body; // Find user by email const user = await User.findOne({ email }); if (!user) { return res.status(404).json({ error: 'User not found' }); } // Compare passwords const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return res.status(401).json({ error: 'Invalid credentials' }); } res.status(200).json({ message: 'Login successful' }); } catch (err) { console.error(err); res.status(500).json({ error: 'Server error' }); } }; ``` 3. **models/User.js**: This file defines the User model. ```js const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } }); const User = mongoose.model('User', userSchema); module.exports = User; ``` 4. **routes/authRoutes.js**: This file defines the authentication routes. ```js const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); // Register a new user router.post('/register', authController.register); // Login user router.post('/login', authController.login); module.exports = router; ``` 5. **views/login.html and views/register.html**: These files contain HTML forms for user registration and login. Now, you need to set up your database and connect it to the application. You can use MongoDB with Mongoose or any other database of your choice. This is a basic setup. You can extend it by adding features like session management, token-based authentication (JWT), error handling, validation, and frontend integration.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]