git clone https://github.com/andiks2018/JvalleyExpress-jwtPostman.git express_jwt_2
buat file .env
DATABASE_URL="file:./db.sqlite"
PORT=8000
SECRET_KEY="masukanSecretKeyKamuTerserahApaAja"
npx prisma db push
selanjutnya kita akan buat relasi di scheme prisma, serta mengganti author dengan user_id
//schema.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
//relation
notes Notes[]
}
model Notes {
id Int @id @default(autoincrement())
title String
content String
user_id Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//relation
user Users @relation(fields: [user_id], references: [id])
}
setelah merubah data di model schema prisma selanjutnya kita db push ulang
npx prisma db push
selanjutnya kita akan jalankan server dengan perintah
npm run dev
selanjutnya kita buat file test.rest sebelumnya kita sudah menginstal extension REST Client for Visual Studio Code.
//test.rest
###
POST http://localhost:8000/user/register
Content-Type: application/json
{
"email":"andi@andi.com",
"password": "cobapassword"
}
sebelumnya kita sudah membuat register user selanjutnya kita akan membuat login user di user_controller.js
//user_controller.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
})
const { SECRET_KEY } = process.env
// generated token
const token = jwt.sign({
id: result.id,
email: result.email
}, 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
})
}
}
//login user
export const user_login = async (req = request, res = response) => {
try {
//kita ambil body
const data = await req.body
//check email
const checkEmail = await db.users.findUnique({
where: {
email: data.email
}
})
//jika email tidak ditemukan di database
if (!checkEmail) {
return res.status(404).json({
success: false,
message: "email tidak ditemukan"
})
}
//jika password tidak sama
if (data.password !== checkEmail.password) {
return res.status(401).json({
success: false,
message: "password kurang tepat"
})
}
//generate token
const token = jwt.sign({
id: checkEmail.id,
email: checkEmail.email
}, process.env.SECRET_KEY)
//kembalikan reseponse json
res.status(500).json({
success: true,
message: "user berhasil di tambahkan ke database",
token: token
})
} catch (error) {
res.status(500).json({
success: false,
error: error.message
})
}
}
tambahkan user login
//user_routes.js
import express from "express"
import { user_login, user_register } from "../controllers/user_controllers"
const user_routes = express.Router()
// user register
user_routes.post("/user/register", user_register)
user_routes.post("/user/login", user_login)
export default user_routes
selanjutnya kita ke test.rest untuk menambahkan user login
//test.rest
### USER REGISTER
POST http://localhost:8000/user/register
Content-Type: application/json
{
"email":"andi@andi.com",
"password": "cobapassword"
}
### USER LOGIN
POST http://localhost:8000/user/login
Content-Type: application/json
{
"email":"andi@andi.com",
"password": "cobapassword"
}
kita tidak bisa register dengan email yang sama,
kalau kita cek password generate muncul user dan id
kita butuh generate req bdy
//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 check apakah ada authorization
const authorization = await req.headers.authorization
if (!authorization) {
return res.status(401).json({
success: false,
message: "authorization tidak ditemukan !"
})
}
const token = await authorization.split(" ")[1]
// validasi token
const verify = await jwt.verify(token, process.env.SECRET_KEY)
if (!verify) {
return res.status(401).json({
success: false,
message: "Token tidak terverifikasi!"
})
}
/**
* {
* "id" : 1,
* "email" : 'andi@andi.com'
* }
*
* lanjut boss..
*/
//generate req body
req.body.user_id = verify.id
req.body.email = verify.email
next()
} catch (error) {
res.status(401).json({
success: false,
error: error.message
})
}
}
export default user_mdw
lanjut ke test rest, tapi sebelumnya kita harus rubah data menjadi objek dengan inputan nilai title content dan user_id
//note_controller.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: {
title : data.title,
content : data.content,
uer_id : data.user_id
}
})
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
})
}
}
tadi ada beberapa error http yang salagh tulis, kemudian ketika send request create note katanya jwt must provider. solusinya tadi kita hapus file db.sqlite kemudian kita
npx prisma db push
ulang
maka kemudian send request ulang , register, login, dan create note.
sampai disini selesai create note
selanjutnya kita akan baca datanya dimana note user itu hanya bisa membaca note yang dia buat. read note sebelumnya in bisa membaca semua note yang ada,
//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 data = await req.body
const result = await db.notes.findMany({
where: {
user_id : data.user_id
}
})
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
console.info(data)
const createNote = await db.notes.create({
data: {
title : data.title,
content : data.content,
user_id : data.user_id
}
})
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
})
}
}
//test.rest
### USER REGISTER
POST http://localhost:8000/user/register
Content-Type: application/json
{
"email":"andi3@andi.com",
"password": "cobapassword"
}
### USER LOGIN
POST http://localhost:8000/user/login
Content-Type: application/json
{
"email":"andi3@andi.com",
"password": "cobapassword"
}
### NOTE CREATE
POST http://localhost:8000/notes/create
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwiZW1haWwiOiJhbmRpM0BhbmRpLmNvbSIsImlhdCI6MTY3Mjk3OTU1M30.EE_pXrJpClcwz7fzO0jL37orfXsHXalyCP3BGtlIvok
{
"title":"ini judul saya",
"content": "ini content saya "
}
### NOTE READ
GET http://localhost:8000/notes/read
Content-Type: application/json
kalau seperti ini maka akan bisa membaca semua note yang sudah dibuat oleh semua user,
register
login
Create note user 6
Read note
cuman yang kita baca disini adalah semua note, sekarang kita pisahkan dengan middleware, kita notes_routes.js
//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)
// read
notes_routes.get("/notes/read", user_mdw, notes_read)
export default notes_routes
lanjut kita ke test.rest lagi untuk membaca note, harusnya sekarang sudah tidak bisa lagi di akses, kecuali memasukkan token user loginnya.
error tidak bisa membaca note
sekarang kita sudah bisa akses note yang kita buat tadi. kita baru membuat satu note.
Top comments (0)