Express Auth(權限管理)的設置 (二)

1.

使用 jwt 保存 token

const jwt = require("jsonwebtoken");

2. 

在 userSchema 中創建methods, 不同於 statics 的是 methods 是用於 instance 的, statics 是用於 whole model 的。

使用普通函數不用箭頭函數是因爲要用 this。

jwt.sign() 接受 2 個參數, 第一個參數可以選一個 unique 的屬性, 第二個參數類似密鑰。

將 token 保存到 User model 中,再 save。

userSchema.methods.generateAuthToken = async function() {
  const user = this;
  const token = jwt.sign({ _id: user._id.toString() }, "thisismynewmall");
  user.tokens = user.tokens.concat({ token });
  await user.save();

  return token;
};

3. 相應的 userSchema 增加 tokens 子集

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true,
  },
  password: {
    type: String,
    required: true,
  },
  tokens: [
    {
      token: {
        type: String,
        required: true,
      },
    },
  ],
});

4. 

userRouter 中生成 token, 並且 res.send 回 user 和 token

router.post("/api/users", async (req, res) => {
  const user = new User(req.body);

  try {
    await user.save();
    const token = await user.generateAuthToken();
    res.status(201).send({ user, token });
  } catch (error) {
    res.status(400).send(error);
  }
});

router.post("/api/users/login", async (req, res) => {
  try {
    const user = await User.findByCredentials(
      req.body.email,
      req.body.password
    );
    const token = await user.generateAuthToken();
    res.send({ user, token });
  } catch (error) {
    res.status(400).send();
  }
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章