{"size": 2122, "ext": "js", "max_stars_repo_path": "routes/users.js", "max_stars_repo_name": "Nicocappabianca/marketlist-backend", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "routes/users.js", "max_issues_repo_name": "Nicocappabianca/marketlist-backend", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "routes/users.js", "max_forks_repo_name": "Nicocappabianca/marketlist-backend", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.3368421053, "max_line_length": 74, "alphanum_fraction": 0.5424128181}
import express from 'express';
import * as uuid from 'uuid';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import Users from '../models/users.js';

const router = express.Router();

router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    const user = await Users.findOne({ email: email });

    if (!user) {
      res.status(200).json({
        Response: false,
        Message: `User not found`
      });
    } else {
      const validPassword = await bcrypt.compare(password, user.password);

      if (!validPassword) {
        res.status(200).json({
          Response: false,
          Message: `Wrong password or user`
        });
      } else {
        const sessionToken = jwt.sign(
          {
            id: user.id
          },
          process.env.SECRET_TOKEN || '12345'
        );

        res.status(200).json({
          Response: true,
          id: user.id,
          sessionToken
        });
      }
    }
  } catch (err) {
    res.status(200).json({
      Response: false,
      Message: `${err}`
    });
  }
});

router.post('/register', async (req, res) => {
  try {
    const { email, password } = req.body;

    console.log(`email: ${email} \n password: ${password}`);

    /* Check if email already exists */
    const emailExists = await Users.findOne({ email: email });

    if (emailExists) {
      res.status(200).json({
        Response: false,
        Message: `Your email is already registered`
      });
    } else {
      /* Generate Unique Token */
      const userId = uuid.v4();

      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      const newUser = new Users({
        id: userId,
        email: email,
        password: hashedPassword
      });

      const savedUser = await newUser.save();

      /* New User Created */
      res.status(200).json({
        Response: true,
        Message: `User created`
      });
    }
  } catch (error) {
    res.status(200).json({
      Response: false,
      Message: `${error}`
    });
  }
});

export default router;
