NodeJs-#2-Auth JWT

Persiapan

  1. Install NodeJs
  2. Install MongoDB Community
  3. Buat Database MongoDB bernama mongoose_basics
Buat Project
mkdir -p jwt-node-auth/{controllers/users.js,models/users.js,routes/index.js,routes/users.js}
cd jwt-node-auth
touch utils.js && touch config.js && touch index.js
Struktur direktori:
root
├── .env
├── config.js
├── controllers
│   └── users.js
├── index.js
├── models
│   └── users.js
├── routes
│   ├── index.js
│   └── users.js
├── utils.js
Installasi Dependensi
npm init --yes
npm install express body-parser bcrypt dotenv jsonwebtoken mongoose  --save
npm install morgan nodemon cross-env  --save-dev
Fungsi Dependensi
  1. body-parser: This will add all the information we pass to the API to the request.body object.
  2. bcrypt: We’ll use this to hash our passwords before we save them our database.
  3. dotenv: We’ll use this to load all the environment variables we keep secret in our .env file.
  4. jsonwebtoken: This will be used to sign and verify JSON web tokens.
  5. mongoose: We’ll use this to interface with our mongo database.
Development Dependensi
  1. morgan: This will log all the requests we make to the console whilst in our development environment.
  2. nodemon: We’ll use this to restart our server automatically whenever we make changes to our files.
  3. cross-env: This will make all our bash commands compatible with machines running windows.
Membuat Enviroment Variabel(.env)

.env

JWT_SECRET=addjsonwebtokensecretherelikeQuiscustodietipsoscustodes
MONGO_LOCAL_CONN_URL=mongodb://127.0.0.1:27017/node-jwt
MONGO_DB_NAME=auth-with-jwts

config.js

module.exports = {
  development: {
    port: process.env.PORT || 3000
  }
}

index.js

require('dotenv').config(); // Sets up dotenv as soon as our application starts

const express = require('express'); 
const logger = require('morgan');
const bodyParser = require('body-parser');

const app = express();
const router = express.Router();

const environment = process.env.NODE_ENV; // development
const stage = require('./config')[environment];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

if (environment !== 'production') {
  app.use(logger('dev'));
}

app.use('/api/v1', (req, res, next) => {
  res.send('Hello');
  next();
});

app.listen(`${stage.port}`, () => {
  console.log(`Server now listening at localhost:${stage.port}`);
});

module.exports = app;

Referensi:

  1. https://scotch.io/tutorials/authenticate-a-node-es6-api-with-json-web-tokens
  2. https://grokonez.com/node-js/jwt/nodejs-jwt-authentication-nodejs-express-restapis-json-web-token-bcryptjs-sequelize-mysql

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>