Untitled

 avatar
unknown
plain_text
24 days ago
2.7 kB
3
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.' });
    }

    // Hash the password before saving it
    const saltRounds = 10; // Number of salt rounds for bcrypt
    const hashedPassword = await bcrypt.hash(user_password, saltRounds);

    // Create the user with the hashed password
    const user = await Users.create({ user_name, user_password: hashedPassword });
    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.' });
    }

    // Log the user and password for debugging
    console.log('User found:', user);
    console.log('Provided password:', user_password);
    console.log('Stored hashed password:', user.user_password);

    // Compare the provided password with the hashed password in the database
    const isPasswordValid = await bcrypt.compare(user_password, user.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