[Express] 인증, 파일업로드를 구현해보자

적자생존·2023년 1월 25일
0

Node

목록 보기
17/17

1. jwt 설치

우선 터미널을 열고 npm install jsonwebtoken을 설치해준다.

2. 회원가입, 로그인 부분 jwt적용

우선 회원가입부터 보면

가장 최상단에 jwt를 불러온다.

const jwt = require("jsonwebtoken")

비밀번호는 평문으로 저장해두는 순간 바로 털리기 때문에 hash를 해준다.

hash란 암호를 만들어서 저장하는 것으로 npm install bcryptjs를 이용해서 설치해준다.

const jwt = require("jsonwebtoken")

const signup = async(req, res, next) => {
	생략
    const {email, password} = req.body
    let hashedPassword
    try{
    	hashedPassword = await bcrypt.hash(password, 12)
    } catch(error){에러}
  
  
}

bcrypt.hash(비밀번호, 숫자) 형식으로 쓰는데 숫자는 몇번 암호화 할 것인지 알려주는 것으로 보통 12로 두면 된다.

이후 jwt를 발행해준다.

const jwt = require("jsonwebtoken")

const signup = async(req, res, next) => {
	생략
    const {email, password} = req.body
    let hashedPassword
    try{
    	hashedPassword = await bcrypt.hash(password, 12)
    } catch(error){에러}
  
  	생략
    let token
    try{
    token = jwt.sign({userId: 스키마.id, email:스키마.email}, "토큰이름", {expiresIn: "1h"})
    }catch(error){에러}
  
  res.status(201).json({userId: 스키마.id, email:스키마.email, token:token})
}

위의 코드처럼 토큰을 발급할 수 있다.

jwt.sign({스키마}, "토큰이름", {만료시간})으로 작성하면 된다.

이제 로그인 부분을 보면

const login = async(req, res, next) => {
	const {email, password} = req.body
    생략
    // 비밀번호 암호 해제
    let existingUser;
  try {
    existingUser = await User.findOne({ email: email });
  } catch (err) {
    애러
  }

  if (!existingUser) {
    에러
  }

  let isValidPassword = false;
  try {
    isValidPassword = await bcrypt.compare(password, existingUser.password);
  } catch (err) {
    에러
  }
}

우선 유저가 존재하는지 찾아주고(findOne이용)
bcyrpt.compare(비밀번호, 존재하는유저.비밀번호)를 이용해 암호를 해제하고 비밀번호와 위에서 찾은 유저의 비밀번호를 비교한다.

생략

let token
try{
	token = jwt.sign({userId:existingUser.id, email:existingUser.email}, "회원가입시 발급한 토큰 이름", {expiresIn: "1h"})
}

회원가입시 발급한 토큰이름으로 로그인 시 토큰을 발급해준다.

3. 파일업로드 구현

터미널을 열고 npm install multer를 설치해준다.

4. 미들웨어 작성

미들웨어 폴더에 file-upload.js를 만들어준다.

const multer = require("multer");
const { v4: uuidv4 } = require("uuid");
const MIME_TYPE_MAP = {
  "image/png": "png",
  "image/jpeg": "jpeg",
  "image/jpg": "jpg",
};

const fileUpload = multer({
  limits: 500000,
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, "uploads/images");
    },
    filename: (req, file, cb) => {
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, uuidv4() + "." + ext);
    },
  }),
  fileFilter: (req, file, cb) => {
    const isValid = !!MIME_TYPE_MAP[file.mimetype];
    let error = isValid ? null : new Error("Invalid mime type");
    cb(error, isValid);
  },
});

module.exports = fileUpload;

위와 같이 작성하고 root경로에 uploads/images폴더를 생성해준다.

업로드된 이미지는 위의 경로에 저장되게 된다.

이제 routes파일에 가서 이미지 업로드를 구현한다.

//users-routes.js

const fileUpload = require("미들웨어경로")

생략
router.post("/signup", fileUpload.single("image"), 생략)

이렇게 되면 req.file.path에 이미지가 들어오게 된다.

// users-controller.js

// 회원가입시 프로필 사진

const signup = async(req, res, next) => {
	const createdUser = new User({
    	email,
      	password: "해쉬된 비밀번호",
      	image: req.file.path
    })
}

위와 같이 구현할 수 있다.

이미지 삭제를 하려면??

const fs = require("fs")
const delete = () => {
  const imagePath = 데이터.image
	fs.unlink(imagePath, (err) => {
    	console.log(err)
    })
}

로 처리해주면 db에서 데이터를 삭제 시 이미지가 삭제된다.

profile
적는 자만이 생존한다.

0개의 댓글