💥we need to add new dependencies
👸 bcrypt is a package with the bcrypt algorithm implementation for hashing passwords
👸 jsonwebtoken is an implementation of JSON Web Token standard
👸 mongoose is a MongoDB ORM library
👸 passport is a flexible authentication library
👸 passport-local is a Passport strategy for authenticating with an email and a password
💥We can install these packages by typing:
npm install --save bcrypt jsonwebtoken mongoose passport-local
💥The application will have the next directory structure
💥 Index.js file
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const config = require('./config');
// connect to the database and load models
require('./server/models').connect(config.dbUri);
const app = express();
// tell the app to look for static files in these directories
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
// tell the app to parse HTTP body messages
app.use(bodyParser.urlencoded({ extended: false }));
// pass the passport middleware
app.use(passport.initialize());
// load passport strategies
const localSignupStrategy = require('./server/passport/local-signup');
const localLoginStrategy = require('./server/passport/local-login');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);
// pass the authenticaion checker middleware
const authCheckMiddleware = require('./server/middleware/auth-check');
app.use('/api', authCheckMiddleware);
// routes
const authRoutes = require('./server/routes/auth');
const apiRoutes = require('./server/routes/api');
app.use('/auth', authRoutes);
app.use('/api', apiRoutes);
// start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000 or http://127.0.0.1:3000');
});
The property
jwtSecret
of the config object contains a secret phrase our application will use to sign tokens.
config/index.json
{
"dbUrl": "mongodb://localhost/react_app",
"jwtSecret": "a secret phrase! !"
}
💥The bcrypt module will generate a hash from a generated earlier salt string and a user’s password. This hash instead of a user’s password will be saved in the collection.
user.password = hash;
💥The basic logic here is to check if a user with a given email exists.
If so, we will compare the given password’s hash value with a value
saved in the database. If the user exists and the password is correct,
we will create a JSON Web Token (JWT).The token looks similar to this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
No comments:
Post a Comment