🐡

JWT Authentication【4JWT Token】

2022/10/06に公開

JWT Authentication【4JWT Token】

YouTube: https://youtu.be/8CngqMaQeAw

JWT : https://jwt.io/
jsonwebtoken: https://www.npmjs.com/package/jsonwebtoken

{
    "email": "john@mail.com",
    "password": "john"
}
npm i jsonwebtoken
npm i --save-dev @types/jsonwebtoken
  "dependencies": {
    "@prisma/client": "^4.3.1",
    "bcrypt": "^5.0.1",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "helmet": "^6.0.0",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cors": "^2.8.12",
    "@types/express": "^4.17.14",
    "@types/jsonwebtoken": "^8.5.9",
    "@types/morgan": "^1.9.3",
    "@types/node": "^18.7.18",
    "prisma": "^4.3.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.8.3"
  }
.env
DATABASE_URL="file:./dev.db"
JWT_SECRET=sadflakjdfio234234fsf
authControllers.ts
import {Request, Response} from 'express'
import { prisma } from '../utils/prismaClient'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { jwtSecretKey } from '../utils/jwtSecretKey'

export const register = async (req: Request, res: Response) => {
  const { email, name, password, confirm_password } = req.body

  if (password !== confirm_password ) {
    res.status(400).json({
      'message': "Password do not match confirm password."
    })
    return
  }

  const hashedPassword = await bcrypt.hash(password, 10)

  try {
    const user = await prisma.user.create({
      data: {
        email: email,
        name: name,
        password: hashedPassword
      },
      select: {
        id: true,
        email: true,
        name: true,
      }
    })
    res.status(200).json(user)
  } catch (error) {
    res.status(500).json({"error": error})
  }
}

export const login = async (req: Request, res: Response) => {
  const { email, password } = req.body

  try {
    const user = await prisma.user.findUnique({
      where: {
        email: email
      },
      select: {
        id: true,
        name: true,
        email: true,
        password: true
      }
    })

    if (user === null) {
      return res.status(404).json({error: "user do not exist"})
    }

    const compared = await bcrypt.compare(password, user.password)

    if (!compared) {
      return res.status(400).json({error: "password wrong"})
    }

    const token = jwt.sign({userId: user.id}, jwtSecretKey, {algorithm: 'HS256'})

    const resUser = {
      id: user.id,
      name: user.name,
      email: user.email
    }

    res.status(200).json({user: resUser, token: token})

  } catch (error: any) {
    res.status(500).json({error: error})
  }
}
jwtSecretKey.ts
import jwt from 'jsonwebtoken'

export const jwtSecretKey = process.env.JWT_SECRET as jwt.Secret

Discussion