管理使用者角色 (User Roles) + Permission
Authorization 是什麼?
還記得我們在 AuthController 中建立的 protect function 嗎?
protect function 可以看這邊:
https://ithelp.ithome.com.tw/articles/10336709
之前,我們在 Good practice 中,實作了在需要被保護的 route 中,會在最後要執行動作前,先經過 AuthController 裡 protect function 的控管,像是這樣:
router
  .route('/')
  .get(authController.protect, testController.getAllTests)
在實現另外一個控管權限的 middleware 以前,我們需要在 userModel 更新 userSchema:
userSchema:
const userSchema = new mongoose.Schema({
    // 略
    role: {
        type: String,
        enum: ['user', 'admin']
    }
    // 有關 enum 的介紹請看下面的說明
});
說明:
enum:
上面程式碼中的 enum 為一個陣列,它將檢查給定的值是否是數組中的一個。
如果該值不在陣列中,當嘗試 save() 時,Mongoose 將拋出 ValidationError 。
接著,假設我們有一個 route 是 /:id,我們可以透過這個 route 操作 delete,而只有 user role 為 admin 才可以 delete。
那麼,我們就可以在要操作的 function 前,再加上一個 Middleware - authController.restrictTo('admin') 來保護 :
router
    .route('/:id')
    .delete(authController.protect, authController.restrictTo('admin'), testController.deleteTest)
在 authController 中的 restrictTo function:
restrictTo function:
exports.restrictTo = (...roles) => {
    return (res, req, next) => {
       
        // 若 user 並不再指定的角色之中,回傳錯誤
        if(!roleTypes.include(req.user.role)){
            return next(new AppError("You don't have the permission to execute this action.", 403));
        }
        
        // 若有,則繼續
        next();
    }
}
最後,就可以嘗試看看該 route 的 delete 操作是否會受到 admin 的權限限制啦 ~
意外地到最後才感覺有開始串起前面的文章內容,不過我好像現在才掌握到寫文章的訣竅 XD 好像有點太晚...
這次的鐵人賽讓我收穫不少 ~
Udemy Node.js, Express, MongoDB & More: The Complete Bootcamp 2023:
https://www.udemy.com/course/nodejs-express-mongodb-bootcamp
Hacksplaining:
https://www.hacksplaining.com/