{"size": 909, "ext": "js", "max_stars_repo_path": "server/controllers/login.js", "max_stars_repo_name": "VincentLeV/verifyhut-mern-fullstack", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/controllers/login.js", "max_issues_repo_name": "VincentLeV/verifyhut-mern-fullstack", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/controllers/login.js", "max_forks_repo_name": "VincentLeV/verifyhut-mern-fullstack", "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": 34.9615384615, "max_line_length": 90, "alphanum_fraction": 0.6578657866}
const jwt = require( "jsonwebtoken" )
const bcrypt = require( "bcrypt" )
const loginRouter = require( "express" ).Router()
const User = require( "../models/user" )
const { successHandler } = require("../middleware")
const { SECRET } = require("../utils/config")

loginRouter.post("/", async (req, res, next) => {
    const user = await User.findOne({ username: req.body.username })
    const isCorrectPassword = await bcrypt.compare( req.body.password, user.passwordHash )

    if (user === null || !isCorrectPassword) {
        return next(new Error("unauthorized"))
    } 

    const userForToken = {
        username: user.username,
        id: user._id
    }

    const token = jwt.sign( userForToken, SECRET, { expiresIn: "1h" } )
    // const token = jwt.sign(userForToken, SECRET)
    return successHandler(res, { token, username: user.username, name: user.name }, 200)
})

module.exports = loginRouter