magda
magda copied to clipboard
Tidy up `req.user`'s Structure & Life Cycle
Is your feature request related to a problem? Please describe.
We might want to tidy up code around req.user among all modules for some inconsistencies.
Mainly because req.user at this moment can:
- have a different value
- different structure)
- and sometimes not exist / not available at all
And the actual status of req.user at this moment depends on many things, they are:
- request processing life cycle
- request routes
- middleware / lib get involved (particularly this one)
e.g. req.user's value might be set under 3 scenarios:
- recover a session from cookie
- In this case,
req.user's value is{ id: "xxxx" }. Internally, we call itUserTokentype
- In this case,
- authenticate through API Key
- Same as above
- micro-services that receives request with JWT
- the micro-service didn't use
mustBeAdminmiddleware (e.g. only usedmustBeLoggedInmiddleware)-
req.userwill be undefined
-
- the micro-service used
mustBeAdminmiddleware and the user is an admin- In this case,
req.user's value would be an object that contains all user properties (e.g. displayName, isAdmin etc.)
- In this case,
- the micro-service didn't use
Those inconsistencies cause confusion and might lead to errors.
Describe the solution you'd like
To reduce inconsistencies, I think we can make sure:
- if
req.userexists, it must include all properties ofuser(i.e. all columns of user table), rather than justidfield instead.- This requires all oAuth plugin should call passport
callbackwith complete user object (instead ofidonly) - JWT token should carry the user object with all properties of
user (so that when we need to recoverreq.user` from JWT, we don't have to fetch it from the database again)
- This requires all oAuth plugin should call passport
- Stop decoding JWT in middleware
mustBeAdminormustBeLoggedInand move JWT decoding (plusreq.userrecovery function ) to a common middlewareuseJwtToken.-
mustBeAdminormustBeLoggedInshould complete their logic purely based onreq.user's data
-