text: const express = require("express");
  const router = express.Router();
  const bcrypt = require("bcryptjs");
  const jwt = require("jsonwebtoken");
  const config = require("config");
  const { check, validationResult } = require("express-validator/check");
  
  const auth = require("../../middleware/auth");
  const User = require("../../models/Users");
  
  // @route    GET api/auth
  // @desc     Test route
  // @access   Public
  router.get("/", auth, async (req, res) => {
    try {
      const user = await User.findById(req.user.id).select("-password");
      res.json(user);
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server Error");
    }
  });
  
  // @route    POST api/auth
  // @desc     Authentication user & get token
  // @access   Public
  router.post(
    "/",
    [
      check("email", "請輸入合法的電子郵件信箱").isEmail(),
      check("password", "尚未填寫密碼").exists()
    ],
    async (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
  
      const { email, password } = req.body;
  
      try {
        let user = await User.findOne({ email });
  
        if (!user) {
          return res
            .status(400)
            .json({ errors: [{ msg: "不合法的帳號或密碼" }] });
        }
  
        const isMatch = await bcrypt.compare(password, user.password);
  
        if (!isMatch) {
          return res
            .status(400)
            .json({ errors: [{ msg: "不合法的帳號或密碼" }] });
        }
  
        // Return jsonwebtoken
        const payload = {
          user: {
            id: user.id
          }
        };
  
        jwt.sign(
          payload,
          config.get("jwtSecret"),
          { expiresIn: 360000 },
          (err, token) => {
            if (err) throw err;
            res.json({ token });
          }
        );
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
    }
  );
  
  module.exports = router;
  