Express + MongoDB注冊登錄token驗(yàn)證

一、連接數(shù)據(jù)庫創(chuàng)建集合規(guī)則

首先安裝依賴 npm install express mongoose

1、連接數(shù)據(jù)庫
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/demo', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true
}).then(() => {
  console.log("數(shù)據(jù)庫連接成功");
})
2、創(chuàng)建集合規(guī)則
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true    // 表示唯一鍵
  },
  password: {
    type: String
  }
})
const User = mongoose.model('User', UserSchema)

二、注冊

1、安裝加密模塊npm install bcrypt,并修改集合規(guī)則
// 集合規(guī)則password添加set方法
password: {
    type: String,
    set(val) {
      // 返回同步hash加密10次后的值
      return bcrypt.hashSync(val, 10)
    }
  }
2、將json處理中間件放在接口最上方
// 使用express中間件處理json數(shù)據(jù)
app.use(express.json())
3、接口
// 注冊
app.post('/api/register', async (req, res) => {
  const user = await User.create({
    username: req.body.username,
    password: req.body.password,
  })
  res.send(user)
})
4、注冊成功存入已加密的密碼
{
  "_id": "606ac9909467de1ed008468c",
  "username": "ceshiuser",
  "password": "$2b$10$Py0lNdlY2JZOWBfC3wkk4OLIIzsdWoDRsID1z9jqPa9qO3ewVvD8a",
  "__v": 0
}

三、登錄

1、安裝token模塊npm install jsonwebtoken
const jwt = require('jsonwebtoken')
const SECRET = ‘jasdkljaskldjASKDJASKLJDKL’
2、密碼驗(yàn)證生成token
// 登錄
app.post('/api/login', async (req, res) => {
  const user = await User.findOne({
    username: req.body.username
  })
  if (!user) {
    return res.status(422).send({
      msg: '用戶不存在'
    })
  }
  // 比較傳過來的密碼和數(shù)據(jù)庫的密碼是否一樣,返回值為布爾值
  const isPasswordValid = bcrypt.compareSync(req.body.password, user.password);
  if (!isPasswordValid) {
    return res.status(423).send({
      msg: '密碼錯誤'
    })
  }
  // 生成token
  const token = jwt.sign({
    id: String(user._id)
  }, SECRET)
  
  res.send({
    user,
    token
  })
})

四、通過請求頭token獲取用戶信息

app.get('/api/profile', async (req, res) => {
  if (!String(req.headers.authorization)) {
    return res.status(425).send({
      msg: 'token不存在'
    })
  }
  // 獲取請求頭的token值
  const getToken = String(req.headers.authorization).split(' ').pop();
  // 解析出token
  const { id } = jwt.verify(getToken, SECRET)
  // 查詢用戶
  const user = await User.findById(id)
  res.send(user)
})

封裝中間件復(fù)用

const auth = async (req, res, next) => {
  if (!String(req.headers.authorization)) {
    return res.status(425).send({
      msg: 'token不存在'
    })
  }
  // 獲取請求頭的token值
  const getToken = String(req.headers.authorization).split(' ').pop();
  // 解析出token,解構(gòu)用戶id
  const { id } = jwt.verify(getToken, SECRET)
  // 查詢用戶信息
  req.user = await User.findById(id)
  next()
}

調(diào)用

app.get('/api/profile', auth, async (req, res) => {
  res.send(req.user)
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容