Untitled

 avatar
unknown
plain_text
25 days ago
2.5 kB
2
Indexable
const express = require('express');
const router = express.Router();
const Users = require('../models/Users');
const bcrypt = require('bcrypt'); // Import bcrypt for password comparison
const jwt = require('jsonwebtoken'); // Import jwt for token generation
require('dotenv').config(); // Load environment variables

// Signup route
router.post('/signup', async(req, res) => {
    const { user_name, user_password } = req.body;

    if (!user_name || !user_password) {
        return res.status(400).json({ message: 'Username and password are required.' });
    }

    try {
        // Check if the user already exists
        const existingUser = await Users.findOne({ where: { user_name } });
        if (existingUser) {
            return res.status(400).json({ message: 'Username already exists.' });
        }

        // Create the user (password is hashed automatically by the model hook)
        const user = await Users.create({ user_name, user_password });
        res.status(201).json({ message: 'User created successfully!', user });
    } catch (error) {
        console.error('Error creating user:', error);
        res.status(500).json({ message: 'An error occurred while creating the user.' });
    }
});

// Login route
router.post('/login', async(req, res) => {
    const { user_name, user_password } = req.body;

    if (!user_name || !user_password) {
        return res.status(400).json({ message: 'Username and password are required.' });
    }

    try {
        // Find the user by username
        const user = await Users.findOne({ where: { user_name } });
        if (!user) {
            return res.status(401).json({ message: 'Invalid username or password.' });
        }

        // Compare the provided password with the hashed password in the database
        const isPasswordValid = await user.comparePassword(user_password);
        if (!isPasswordValid) {
            return res.status(401).json({ message: 'Invalid username or password.' });
        }

        // Generate a JWT
        const token = jwt.sign({ user_name: user.user_name }, process.env.JWT_SECRET, { expiresIn: '1h' });

        // Send the token to the client
        res.status(200).json({ message: 'Login successful!', token });
    } catch (error) {
        console.error('Error during login:', error);
        res.status(500).json({ message: 'An error occurred during login.' });
    }
});

module.exports = router;
Leave a Comment