在 update user data 的時候,我們需要注意 "不要沒有過濾掉 role"。
上述的話是什麼意思呢?
讓我們來看看 Bad Practice 吧 ~
export.updateSelfUserData = catchAsync(async (req, res, next) => {
   // 仔細看這邊 update 了整個 req.body
   const updatedUser = await User.findByIdAndUpdate(req.user.id, req.body, { new: true, runValidators: true });
    
    req.status(200).json({
       status: 'success' 
    });
});
說明:
這樣會出現一個漏洞,假設今天有人在 request 這個 api 時,帶上 role: 'admin',這樣就會把他的 role 給設成 admin,進而上升使用者的角色到 admin 級別,那麼就有更多不一樣的權限可以操作系統,這樣十分危險!
接著,我們來看看 Good practice ~
export.updateSelfUserData = catchAsync(async (req, res, next) => {
    
   // 允許 update 的 field 可以更換成其他的 field (看你如何定義 user)
   const filteredData = filterObject(req.body, 'username', 'email');
   
   // 我們在這把 req.body 換成了 filteredData
   const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredData, { new: true, runValidators: true });
    
    req.status(200).json({
       status: 'success',
       data: {
           user: updatedUser
       }
    });
});
filterObject function:
const filterObject = (object, ...allowedField) => {
	
    const newObject = {}; 
    
	// 透過重新組裝一個新的允許 return 的 data
	Object.keys(obj).foreach((element) => {
	    if(allowedField.includes(element)) {
	    	newObject[element] = object[element];
	    }
	});
	
	return newObject;
}
說明:
透過加入一個過濾器 - filterObject function,我們將 req.body 中的資料給過濾掉,只剩下我們需要 update 的 field,這樣我們就可以避免掉使用者無意間 update 了 role 的窘況,也提升了安全性。
今天在打文章的時候,意外發現有十分多都還沒講完 QQ
每天趕稿+學習真的很拚 XD
雖然說鐵人賽只有 30 天,但感覺如果要寫道很完整還是有一定的難度...
再加加油吧 TAT 之後的日子再多學習
Udemy Node.js, Express, MongoDB & More: The Complete Bootcamp 2023
https://www.udemy.com/course/nodejs-express-mongodb-bootcamp
Hacksplaining
https://www.hacksplaining.com/