I am developing a service using the MVC pattern with the support of NodeJS, jsonwebtoken, and MongoDB (mongoose). In my application, I have modeled two main actors: normal users (that can sign-up via Facebook, Amazon or local signup), drivers (sign-up only through the website). I have also to model the transactions between user & drivers that can be obviously be modified by a CRUD paradigm only by users and drivers.
Here I post the models of users and drivers:
var userSchema = mongoose.Schema({
name: String,
surname: String,
email: String,
password: {
type: String,
required: true
}
});
var driverSchema = mongoose.Schema({
name: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
email: {
type:String,
required: true,
unique:true
},
password: {
type: String,
required: true,
minlength: minimum
} });
My issue is in the authentication and data access to the endpoints. How can i create a distinction on the token between users and drivers? Should I add this information to the payload of the token?
Well, there are several approaches to solving this issue. One of the approaches would be to sign the user's token with their role. Since you already have separate authentication logic for the different types, you can easily sign the token with a specific userType.
For the driver, the code would be something like this:
var driverToken = jwt.sign({email:'[email protected]', userType: 'driver'}, 'YOUR_SECRET');
For the normal user, the code would be something like this:
var normalToken = jwt.sign({email:'[email protected]', userType: 'normal'}, 'YOUR_SECRET');
Now when verifying the token, you can do this:
var user = jwt.verify(TOKEN, 'YOUR_SECRET');
if(user.userType === 'driver') {
//Hey, you are a driver!
}
else if(user.userType === 'normal') {
//Hey, you are normal...
}
Also, I noticed that the driver and user schema are almost the same. I suggest that you take a look at mongoose's discriminators
. Basically, discriminators
are a schema inheritance mechanism for mongoose.