💡

JWT Authentication【2Hash Password】

2022/10/04に公開約1,500字

JWT Authentication【2Hash Password】

YouTube: https://youtu.be/lbZg8fA5exs

bcrypt: https://www.npmjs.com/package/bcrypt

npm i bcrypt
npm i --save-dev @types/bcrypt

{
    "name": "John",
    "email": "john@mail.com",
    "password": "john",
    "confirm_password": "john"
}

npx prisma studio
package.json
  "dependencies": {
    "@prisma/client": "^4.3.1",
    "bcrypt": "^5.0.1",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "helmet": "^6.0.0",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cors": "^2.8.12",
    "@types/express": "^4.17.14",
    "@types/morgan": "^1.9.3",
    "@types/node": "^18.7.18",
    "prisma": "^4.3.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.8.3"
  }
authControllers.ts
import {Request, Response} from 'express'
import { prisma } from '../utils/prismaClient'
import bcrypt from 'bcrypt'

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})
  }
}

Discussion

ログインするとコメントできます