text: const express = require("express");
  const router = express.Router();
  const gravatar = require("gravatar");
  const bcrypt = require("bcryptjs");
  const jwt = require("jsonwebtoken");
  const keys = require("../../config/keys");
  const passport = require("passport");
  
  // Load Input Validation
  const validateRegisterInput = require("../../validation/register");
  const validateLoginInput = require("../../validation/login");
  
  // Load User model
  const User = require("../../models/User");
  
  // @route   GET api/users/test
  // @desc    Tests users route
  // @access  Public
  router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
  
  // @route   POST api/users/register
  // @desc    Register user
  // @access  Public
  router.post("/register", (req, res) => {
    // Check input to see if valid
    const { errors, isValid } = validateRegisterInput(req.body);
  
    // If invalid return errors to the frontend to be diplayed
    if (!isValid) {
      return res.status(400).json(errors);
    }
  
    // Try find a user with the provided email
    User.findOne({ email: req.body.email }).then(user => {
      // If user with email exists display error to user
      if (user) {
        errors.email = "Email already exists";
        return res.status(400).json(errors);
      } else {
        // Get the avatar using the email through gravatar
        const avatar = gravatar.url(req.body.email, {
          s: "200", // Size
          r: "pg", // Rating
          d: "mm" // Default
        });
  
        // Create new user using provided details
        const newUser = new User({
          name: req.body.name,
          email: req.body.email,
          avatar,
          password: req.body.password
        });
  
        // Hash the users password
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
          });
        });
      }
    });
  });
  
  // @route   POST api/users/login
  // @desc    Login User / Returning JWT Token
  // @access  Public
  router.post("/login", (req, res) => {
    // Check input to see if valid
    const { errors, isValid } = validateLoginInput(req.body);
  
    // If invalid return the errors
    if (!isValid) {
      return res.status(400).json(errors);
    }
  
    const email = req.body.email;
    const password = req.body.password;
  
    // Find user by email
    User.findOne({ email }).then(user => {
      // Check for user
      if (!user) {
        errors.email = "No user found for Username/Password combination";
        return res.status(404).json(errors);
      }
  
      // Check Password
      bcrypt.compare(password, user.password).then(isMatch => {
        // User Matched
        if (isMatch) {
          const payload = { id: user.id, name: user.name, avatar: user.avatar }; // Create JWT Payload
  
          // Sign Token
          jwt.sign(
            payload,
            keys.secretOrKey,
            { expiresIn: 3600 },
            (err, token) => {
              res.json({
                success: true,
                token: "Bearer " + token
              });
            }
          );
        } else {
          errors.password = "No user found for Username/Password combination";
          return res.status(400).json(errors);
        }
      });
    });
  });
  
  // @route   GET api/users/current
  // @desc    Return current user
  // @access  Private
  router.get(
    "/current",
    passport.authenticate("jwt", { session: false }),
    (req, res) => {
      res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email
      });
    }
  );
  
  module.exports = router;
  