Skip to content

[JITERA] Implement User Authentication Backend

Created by: chi-jitera

Overview

This pull request introduces a backend implementation for user authentication, including user registration and login functionality. It consists of a user model, service, controller, and routes, integrated into the existing Express server.

Changes Made

  1. User Model:

    • Created a user schema with fields for username and password.
    • File: /models/User.js
    const mongoose = require('../config/db');
    const userSchema = new mongoose.Schema({
        username: { type: String, required: true, unique: true },
        password: { type: String, required: true }
    });
    module.exports = mongoose.model('User', userSchema);
  2. User Service:

    • Implemented functions for user authentication and registration, including password hashing.
    • File: /services/userService.js
    const User = require('../models/User');
    const bcrypt = require('bcrypt');
    
    exports.authenticateUser = async (username, password) => {
        const user = await User.findOne({ username });
        if (!user) throw new Error('User not found');
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) throw new Error('Invalid password');
        return user;
    };
    
    exports.createUser = async (userData) => {
        const hashedPassword = await bcrypt.hash(userData.password, 10);
        const user = new User({ ...userData, password: hashedPassword });
        return await user.save();
    };
  3. User Controller:

    • Handled login and registration requests, returning appropriate responses.
    • File: /controllers/userController.js
    const userService = require('../services/userService');
    
    exports.login = async (req, res) => {
        try {
            const { username, password } = req.body;
            const user = await userService.authenticateUser(username, password);
            res.status(200).json({ message: 'Login successful', user });
        } catch (error) {
            res.status(401).json({ error: error.message });
        }
    };
    
    exports.register = async (req, res) => {
        try {
            const user = await userService.createUser(req.body);
            res.status(201).json({ message: 'User registered successfully', user });
        } catch (error) {
            res.status(400).json({ error: error.message });
        }
    };
  4. User Routes:

    • Defined routes for login and registration.
    • File: /routes/userRoutes.js
    const express = require('express');
    const userController = require('../controllers/userController');
    const router = express.Router();
    
    router.post('/login', userController.login);
    router.post('/register', userController.register);
    
    module.exports = router;
  5. Update Express Server:

    • Integrated user routes into the main Express server.
    • File: /index.ts
    import express from 'express';
    import path from 'path';
    import userRoutes from './routes/userRoutes';
    
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.use(express.json());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/api', userRoutes);
    
    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname, 'public', 'loginForm.html'));
    });
    
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

Additional Notes

  • Ensure to install the necessary packages like bcrypt for password hashing by running npm install bcrypt.

Merge request reports