{"size": 1489, "ext": "js", "max_stars_repo_path": "coding-garden/auth/server/auth/auth.controller.js", "max_stars_repo_name": "mohammedelzanaty/myRoad2BeFullStack", "max_stars_repo_stars_event_min_datetime": "2021-04-21T12:05:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T09:58:38.000Z", "max_issues_repo_path": "coding-garden/auth/server/auth/auth.controller.js", "max_issues_repo_name": "mohammedelzanaty/myRoad2BeFullStack", "max_issues_repo_issues_event_min_datetime": "2019-12-26T11:21:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T19:55:10.000Z", "max_forks_repo_path": "coding-garden/auth/server/auth/auth.controller.js", "max_forks_repo_name": "mohammedelzanaty/myRoad2BeFullStack", "max_forks_repo_forks_event_min_datetime": "2021-08-15T07:59:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T06:17:32.000Z"}
{"max_stars_count": 2, "max_issues_count": 34, "max_forks_count": 2, "avg_line_length": 19.5921052632, "max_line_length": 61, "alphanum_fraction": 0.5809267965}
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

const users = require('./auth.model')

const salt = bcrypt.genSaltSync(12)

const createTokenSendResponse = (user, res, next) => {
  const payload = {
    _id: user._id,
    email: user.email,
  }
  jwt.sign(
    payload,
    process.env.TOKEN_SECRET,
    {
      expiresIn: '1h',
    },
    (err, token) => {
      if (err) {
        res.status(422)
        const error = Error('Unable to login')
        next(error)
      } else {
        // login all good
        res.json({ token })
      }
    }
  )
}

const get = (req, res) => {
  res.json({
    message: 'Hello Auth! 🔐',
  })
}

const signup = async (req, res, next) => {
  try {
    const hashed = await bcrypt.hash(req.body.password, salt)
    const newUser = {
      email: req.body.email,
      password: hashed,
    }
    const insertedUser = await users.insert(newUser)
    createTokenSendResponse(insertedUser, res, next)
  } catch (error) {
    res.status(500)
    next(error)
  }
}

const login = async (req, res, next) => {
  try {
    const result = await bcrypt.compare(
      req.body.password,
      req.loggingInUser.password
    )
    if (result) {
      createTokenSendResponse(req.loggingInUser, res, next)
    } else {
      res.status(422)
      throw new Error('Unable to login')
    }
  } catch (error) {
    res.status(res.statusCode === 200 ? 500 : res.statusCode)
    next(error)
  }
}

module.exports = {
  get,
  login,
  signup,
}
