簡體   English   中英

添加基本身份驗證以表達 rest api

[英]add basic auth to express rest api

so I have rest api where i store user data in mongoDB, I want to add basic auth to my api but I'm stuck, I want to check if user is authorised on some paths, for example on /update, if user is auth執行請求,如果不發送該用戶未授權

我存儲用戶的代碼是 db

  const addUser = async (req, res) => {
  const checknick = await User.find({ nickname: req.body.nickname }) //checks if user exists with nickname
  if (checknick.length !== 0) {
    return res.send({
      message: 'user already exists, please use another nickname',
    })
  }

  const secretInfo = await hash(req.body.password).catch((err) =>
    res.send('password is required!')
  )
  const user = new User({
    name: req.body.name,
    surname: req.body.surname,
    nickname: req.body.nickname,
    password: secretInfo.password,
    salt: secretInfo.salt,
  })
  user.save((err, result) => {
    if (err) {
      return res.send(err)
    }
    res.send('user added sucesessfully')
  })
}

我在哪里驗證用戶

const verify = async (req, res) => {
  const user = await User.findOne({ nickname: req.body.nickname })
  if (!user) {
    return
  }

  const { password } = await hash(req.body.password, user.salt).catch((err) =>
    res.send('password is required')
  )

  const verifiedUser = await User.findOne({
    nickname: req.body.nickname,
    password: password,
  })

  if (!verifiedUser) {
    return false
  }
  return true
}

最后是登錄邏輯

const login = async (req, res) => {
  const access = await verify(req, res)

  // console.log(req.headers)
  if (access) {
    res.send('logged in')
    console.log(req.headers)
    return
  }
  return res.status(401).send('failed to login')
}

一切正常,但我想使用授權 header 發送用戶和密碼信息

this is how to restrict a route add this middleware function before tho 
route you want to restrict like this : app.post("/update", 
restrictTo("admin"));

// every user must have a role to authorize . here I am handling error with a global error handler but you can handle error another way

exports.restrictTo = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role))
      return next(
        new AppError('You dont have permission to do this action', 403)
      );
    next();
  };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM