DEV Community

Cover image for Express js jwt
Andi Ismail
Andi Ismail

Posted on

Express js jwt

mkdir express_jwt
npm init -y //akan menghasilkan package.json
npm install express dotenv prisma jsonwebtoken


npm install -D @babel/core @babel/node @babel/preset-env //akan menghasilkan node modules

npx prisma init
Enter fullscreen mode Exit fullscreen mode

Image vs code

buat file .babelrc

//.babelrc

{
    "presets": ["@babel/preset-env"]
}

Enter fullscreen mode Exit fullscreen mode

tambahkan dev

//package.json

{
  "name": "express_jwt",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"nodemon --exec babel-node ./src/index.js" //tambahkan ini 
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "jsonwebtoken": "^9.0.0",
    "prisma": "^4.8.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/node": "^7.20.7",
    "@babel/preset-env": "^7.20.2"
  }
}

Enter fullscreen mode Exit fullscreen mode

selanjutnya buat folder sr, kemudian file index.js

// src/index.js

import express from "express"
import env from "dotenv"
env.config()

const app = express()

app.listen(8000, ()=>{
    console.info("server berjalan di port 8000")
})
Enter fullscreen mode Exit fullscreen mode

coba jalankan server

npm run dev
Enter fullscreen mode Exit fullscreen mode

Image npm run dev

selanjutnya kita ke env, kita akan ganti postgre

//env

DATABASE_URL="file:./db.sqlite"
PORT=8000

Enter fullscreen mode Exit fullscreen mode

sekarang ke schema prisma

// schem.prisma

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model Users {
  id        Int     @id @default(autoincrement())
  email     String  @unique
  password  String  
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

model Notes {
  id          Int @id   @default(autoincrement())
  title       String
  content     String
  author      String
  createdAt   DateTime   @default(now())
  updatedAt   DateTime  @updatedAt
}
Enter fullscreen mode Exit fullscreen mode

port 8000 kita nonaktifkan dulu,

npx prisma db push //database is now sync with prisma

Enter fullscreen mode Exit fullscreen mode

buat file baru di prisma

//connetions.js

import {PrismaClient} from "@prisma/client"
const db = new PrismaClient()
export default db

Enter fullscreen mode Exit fullscreen mode

selanjutnya kita buat folder controllers didalam folder src

//user_controller.js

import { request, response } from "express";
import db from "../../prisma/connection";

//create user

export const user_register = async(req =request, res= response)=>{
    try{

        //membaca request body
        const data = await req.body

        //tulis data dari body ke database
        const result = await db.users.create({
            data : data
        })

        //kembalikan rsponse json 
        res.status(201).json({
            success: true,
            message : "user berhasil di tambahkan ke database "
        })

    } catch(error){
        res.status(500).json({
            success : false,
            error : error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

selanjutnya kita buat routenya

//routes/user_routes.js

import express from "express"
import { user_register } from "../controllers/user_controllers"
const user_routes = express.Router()

//userRegister
user_routes.post("/user/register", user_register)

export default user_routes

Enter fullscreen mode Exit fullscreen mode

selanjutnya kita kembali lagi ke index.js untuk menambahkan middleware dan routes

//index.js

import express from "express"
import env from "dotenv"
import user_routes from "./routes/user_routes"
env.config()

const app = express()

//middleware
app.use(express.urlencoded({extended: false}))
app.use(express.json())


//routes
app.use(user_routes)


app.listen(8000, ()=>{
    console.info("server berjalan di port 8000")
})
Enter fullscreen mode Exit fullscreen mode

coba hentikan server port 8000 kemudian hidupkan kembali seharusnya tidak ada error.

Image berjalan 8000

kita akan coba test model yang sudah kita buat dengan post man :

  • new connection
  • buat 2 folder users dan notes
  • add request ganti namanya dengan user register
  • masukkan link http://localhost:8000/user/register
  • lanjut ke body : ganti jadi raw, json
  • kemudian send request, rresponse nya berada disamping kanan, bernilai true

Image postman hit

Image login flow

konsep jwt

Image pengertian jwt

package library yang kita gunakan

Image json webtoken

kita import json webtoken di user controller
kita generate dulu secret password di sha256

Image sha256

copy password kita ke env

// .env

DATABASE_URL="file:./db.sqlite"
PORT=8000
SECRET_KEY = "822311a345980e7a0a2cdb7fd8c51d4c0fe302f671e619386f740b19d9ffa243" //paste disini 
Enter fullscreen mode Exit fullscreen mode

lanjut ke user_controller import env, generated token dan kembalikan respon token

//user_controllers.js
import { request, response } from "express";
import db from "../../prisma/connection";
import jwt from 'jsonwebtoken'
import env from 'dotenv'
env.config()

//create user
export const user_register = async(req =request, res= response)=>{
    try{

        //membaca request body
        const data = await req.body

        //tulis data dari body ke database
        const result = await db.users.create({
            data : data
        })


        //generated token 
        const token = jwt.sign({
            id : result.id,
            email : result.email
        }, process.env.SECRET_KEY)

        //kembalikan response json 
        res.status(201).json({
            success: true,
            message : "user berhasil di tambahkan ke database ",
            token : token
        })
    } catch(error){
        res.status(500).json({
            success : false,
            error : error.message
        })
    }
}

Enter fullscreen mode Exit fullscreen mode

selanjutnya kita ke postman lagi unutk coba hit , jangan lupa untuk mengganti emailnya karena unique jadi gak boleh sma adengan email sebelumnya.

Image hit kedua dengan jwt

berhasil menambahkan email dan password baru.

Image jwt io

kalau kita copy token kita yang ada di post man , kemudian kita pastekan ke jwt.io ternyata id email kita masih terbaca, makanya kita tidak bisa menyimpan password disini, kita simpannya di env, dengan nama secret_key

lanjut ke nottes

// src/controllers/notes_controllers.js

import {request, response} from "express"
import db from "../../prisma/connection"

//read notes
export const notes_read = async (req=request, res = response)=>{
    try{
        const result = await db.notes.findMany()
        res.status(200).json({
            success : true,
            notes : result
        })

    }catch(error){
        res.status(500).json({
            success : false,
            error : error.message
        })
    }
}

//create note
export  const notes_create = async (req=request, res = response)=>{
    try {
        const data = await req.body
        const createNote = await db.notes.create({
            data: data
        })
        res.status(201).json({
            success : true,
            message : "berhasil menambahkan note ke database",
            note : createNote
        })
    }catch(error){
        res.status(500).json({
            success : false,
            error : error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

selesai membuat controller selanjutnya kita akan buat routesnya

//notes_routes.js

import express from 'express'
import { notes_create, notes_read } from '../controllers/notes_controllers'

const notes_routes = express.Router()

//create
notes_routes.post("/notes/create", notes_create)

//read
notes_routes.get("/notes/read", notes_read)

export default notes_routes
Enter fullscreen mode Exit fullscreen mode

kemudian kita panggil di index js

//index.js

import express from "express"
import env from "dotenv"
import user_routes from "./routes/user_routes"
import notes_routes from "./routes/notes_routes"
env.config()

const app = express()

//middleware
app.use(express.urlencoded({extended: false}))
app.use(express.json())

//routes
app.use(user_routes)
app.use(notes_routes) //tambahkan ini 

app.listen(8000, ()=>{
    console.info("server berjalan di port 8000")
})
Enter fullscreen mode Exit fullscreen mode

coba kita hit di postman
sebelumnya aku ada error di model notes, tertulis athoe, harusnya author dan ketika dirubah dia harus di db push ulang jangan lupa control save.

sekarang kita ke post man, sama seperti user register, kemudian kita hit dan berhasil

Image berhasil create notes

untuk raednya

Image read notes

selanjutnya kita butuh middleware untuk membatasi siapa saja yang bisa membuat dan read artikel. kita buat folder middleware.

// middleware/user_mdw.js

import {request, response} from 'express'
import jwt from 'jsonwebtoken'
import env from 'dotenv'
env.config()

const user_mdw = async (req=request, res= response, next)=>{

    //coba cek apaakah ada authorization
    const authorization = await req.headers.authorization

    if (!authorization){
        return res.status(401).json({
            success : false,
            message : "authorization tidak di temukan "
        })
    }
    const token = await authorization.split(" ")[1] //hati hati diantara spasi tanda petik  ada spasi

    //validation token 
    const verify = await jwt.verify(token, process.env.SECRET_KEY)

    if(!verify){
        return res.status(401).json({
            success : false,
            message : "Token tidak terverifikasi "
        })
    }

    next()
}

export default user_mdw

Enter fullscreen mode Exit fullscreen mode

lanjut ke notes_routes.js, untuk menambahkan middlewarenya

//notes_routes.js

import express from 'express'
import { notes_create, notes_read } from '../controllers/notes_controllers'
import user_mdw from '../middleware/user_mdw'


const notes_routes = express.Router()

//create
notes_routes.post("/notes/create", user_mdw, notes_create) //tambahkan disini 

//read
notes_routes.get("/notes/read", notes_read)

export default notes_routes
Enter fullscreen mode Exit fullscreen mode

Image false

authorization tidak ditemukan karena belum login.
kita pinjma token yang sudah kita buat sebelumnya.

Image auth

Image authorization

berhasil ya, berarti sekarang kita sudah berhasil melakukan validasi user, mereka harus memiliki token dulu baru bisa akses create data.

di user_mdw.js kita tambahkan try and catch , sehingga kita ada error tidak error server,

//user_mdw.js

import { request, response } from "express";
import jwt from "jsonwebtoken";
import env from "dotenv";
env.config();

const user_mdw = async (req = request, res = response, next) => {
    try {
          //coba cek apaakah ada authorization
  const authorization = await req.headers.authorization;

  if (!authorization) {
    return res.status(401).json({
      success: false,
      message: "authorization tidak di temukan ",
    });
  }
  const token = await authorization.split(" ")[1];

  //validation token
  const verify = await jwt.verify(token, process.env.SECRET_KEY);

  if (!verify) {
    return res.status(401).json({
      success: false,
      message: "Token tidak terverifikasi ",
    });
  }

  next();
    } catch (error) {
        res.status(401).json({
            success : false,
            error : error.message
        })
    }
};

export default user_mdw;

Enter fullscreen mode Exit fullscreen mode

repo github

Top comments (0)