Let's build an API that will:
GET
, POST
, PUT
, DELETE
)Connecting mongolab
mongodb://<dbuser>:<dbpassword>@ds037607.mongolab.com:37607/meanmachine
dbuser
refers to the admin user created inside databse.
User Model
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// user schema
var UserSchema = new mongoose.Schema({
name: String,
username: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true,
select: false // when we query the list of users , there will be no need to provide the password
}
});
// Hash the password befoer the user is saved
UserSchema.pre('save', function(next){
var user = this;
// Hash the passworld only if the password has been changed or user is new
if(!user.isModified('password')) return next();
// generate the hash
bcrypt.hash(user.password, null, null, function(err, hash) {
if(err) return next(err);
// change the password to the hash version
user.password = hash;
next();
});
});
// Method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
var user = this;
return bcrypt.compareSync(password, user.password);
}
// return the model
module.exports = mongoose.model('User', UserSchema);
apiRouter.get('/', function(req, res){
res.json( { message: "this is a json message"});
});
Middleware Uses Using middleware like this can be very powerful. We can do validations to make sure that everything coming from a request is safe and sound. We can throw errors here in case something in the request is wrong. We can do some extra logging for analytics or any statistics we’d like to keep. And the big usage is to authenticate the API calls by checking if a user has the correct token.
The main things we want to do here are:
For handling authentication in Node, you won’t find a better package than PassportJS
. This allows us to integrate authentication on our server with session based security, social based authentication, and what we’ve done in this chapter, JWT security.
There is even a package to handle checking the JWT and protecting routes called express-jwt
. This package creates a middleware for us so that we don’t have to. It will allow us to set protected and unprotected routes.