– create an Express app, then add body-parser and cors middlewares using app.use() method. Notice that we set origin: http://localhost:8081.
– define a GET route which is simple for test.
– listen on port 8080 for incoming requests.
Now let’s run the app with command: node server.js.
Open your browser with url http://localhost:8080/, you will see:
In the app folder, create config folder for configuration.
Then create a new db.config.js file that contains parameters for setting up MongoDB later:
Define the Mongoose Model
In models folder, create User and Role data model as following code:
models/role.model.js
models/user.model.js
These Mongoose Models represents users & roles collections in MongoDB database.
User object will have a roles array that contains ids in roles collection as reference.
find User by username: User.findOne({ username: … })
find all Roles which name in given roles array: Role.find({ name: { $in: roles } })
These functions will be used in our Controllers and Middlewares.
Initialize Mongoose
Now create app/models/index.js with content like this:
Open server.js and add following code to open Mongoose connection to MongoDB database:
initial() function helps us to create 3 important rows in roles collection.
Configure Auth Key
jsonwebtoken functions such as verify() or sign() use algorithm that needs a secret key (as String) to encode and decode token.
In the app/config folder, create auth.config.js file with following code:
You can create your own secret String.
Create Middleware functions
To verify a Signup action, we need 2 functions:
– check duplications for username and email
– check if roles in the request is legal or not
middlewares/verifySignUp.js
To process Authentication & Authorization, we create following functions:
- check if token is provided, legal or not. We get token from x-access-token of HTTP headers, then use jsonwebtoken's verify() function
- check if roles of the user contains required role or not
middlewares/authJwt.js
middlewares/index.js
Create Controllers
Controller for Authentication
There are 2 main functions for Authentication:
- signup: create new User in database (role is user if not specifying role)
- signin:
find username of the request in database, if it exists
compare password with password in database using bcrypt, if it is correct
generate a token using jsonwebtoken
return user information & access Token
controllers/auth.controller.js
Controller for testing Authorization
There are 4 functions:
– /api/test/all for public access
– /api/test/user for loggedin users (any role)
– /api/test/mod for moderator users
– /api/test/admin for admin users
controllers/user.controller.js
Let's combine middlewares with controller functions in the next section.
Define Routes
When a client sends request for an endpoint using HTTP request (GET, POST, PUT, DELETE), we need to determine how the server will response by setting up the routes.
We can separate our routes into 2 part: for Authentication and for Authorization (accessing protected resources).
Authentication:
POST /api/auth/signup
POST /api/auth/signin
routes/auth.routes.js
Authorization:
GET /api/test/all
GET /api/test/user for loggedin users (user/moderator/admin)
GET /api/test/mod for moderator
GET /api/test/admin for admin
routes/user.routes.js
Don't forget to add these routes in server.js:
Run & Test with Results
Run Node.js application with command: node server.js.
...
// routes
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
// set port, listen for requests
...
Server is running on port 8080.
Successfully connect to MongoDB.
added 'user' to roles collection
added 'admin' to roles collection
added 'moderator' to roles collection