Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3655

Passport.js Error Handling Instead of throwing the error into stdout

$
0
0

So I Have The Current Code For Authorization (and im probably going to merge login with signup):

Strategy:

const passport = require("passport")const { Strategy } = require("passport-local")const { getUserByUsername, getUserById } = require("./database/interactors/user")const { comparePasswords } = require("./utils/hashing")passport.serializeUser(( user, done ) => {  done(null, user.dbid.toString())})passport.deserializeUser(async ( id, done ) => {  try {    const user = await getUserById(id)    if(!user){      throw new Error("ERR_USER_NOTFOUND_AUTHED")    }    done(null, user)  } catch (err) {    done(err, null)  }})module.exports = passport.use(  new Strategy({}, async ( username, password, done ) => {    try {      const user = await getUserByUsername(username, true)      if(!comparePasswords(password, user.password)) throw new Error("ERR_PASSWORD_WRONG")      done(null, user)    } catch (err) {      done(err, null)    }  }))

Route:

const LOGGER_NAME = "Auth Router"// A LOT of imports were hereconst router = Router()log(LOGGER_NAME, "🌐 Router Is Up")router.post("/",  checkSchema(auth_base, ["body"]),  inputValidator,  passport.authenticate("local"),  ( req, res ) => {    res.sendStatus(200)})router.post("/signup",  checkSchema(auth_base, ["body"]),  inputValidator,  /**   *    * @param {import("express").Request} req    * @param {import("express").Response} res    * @returns    */  async ( req, res ) => {    const { body } = req    if(req.user) return res.status(400).send(generateJSONError({ msg: "ERR_AUTHORIZED", path: ""}))    if(await getUserByUsername(body["username"], false, false)) return res.status(400).send(generateJSONError({ msg: "ERR_USERNAME_EXISTS", path: "username"}))    try {      const user = await createUser(body["username"], hashPassword(body["password"]))      res.status(201).send(user)    }catch(err){      res.status(400).send(generateJSONError({ msg: "ERR_UNEXPECTED", path: ""}))      throw err    }})router.get("/status", ( req, res ) => {  if(req.user) return res.status(200).send(req.user)  res.sendStatus(401)})router.post("/logout",  requiresAuth,  ( req, res ) => {    req.logOut({}, err => {      if(err) return res.sendStatus(500)      return res.sendStatus(200)    })})module.exports = router

The Problem Is That This Code Throws The Error Directly And Does Not Let Me Handle It (i want to convert it to json and send it to the user)

btw if the response has a status code of 400 or 500, will AXIOS return it in the .then or .catch ?


Viewing all articles
Browse latest Browse all 3655

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>