diff --git a/src/controllers/auth.controller.ts b/src/controllers/auth.controller.ts index b1b2ea5c0cd6c488f1d39ee488055673256052e2..f9805833d292f72bed7191932891d4c5cb31cc0e 100644 --- a/src/controllers/auth.controller.ts +++ b/src/controllers/auth.controller.ts @@ -25,15 +25,17 @@ export const login = asyncWrap(async (req, res) => { return res.status(401).send("잘못된 비밀번호를 입력하셨습니다"); } // 3) 비밀번호가 맞으면 토큰 생성 - const token = jwt.sign({ userId: user.id }, jwtCofig.secret, { //userId를 토큰에다 넣는 중. + const token = jwt.sign({ userId: user.id }, jwtCofig.secret, { + //userId를 토큰에다 넣는 중. expiresIn: jwtCofig.expires, }); // 4) 토큰을 쿠키에 저장 - res.cookie(cookieConfig.name, token, {//token은 쿠키에 무엇을 실렸는가 이다. 항상 갖고 있다가 홈페이지 들어가면 서버로 접속 - maxAge: cookieConfig.maxAge,// 이 기간 한에서만 유효 - path: "/",//어떠한 경로에 관해서만 쓴다. 지금은 전부에 쓴다. - httpOnly: envConfig.mode === "production", //false 면 브라우저에서 쿠키를 조작, true면 조작할 수 있다. - secure: envConfig.mode === "production", //true 면 https 를 통해서만 쿠키 전달, false면 + res.cookie(cookieConfig.name, token, { + //token은 쿠키에 무엇을 실렸는가 이다. 항상 갖고 있다가 홈페이지 들어가면 서버로 접속 + maxAge: cookieConfig.maxAge, // 이 기간 내에서만 유효 + path: "/", //어떠한 경로에 관해서만 쓴다. 지금은 전부에 쓴다. + httpOnly: envConfig.mode === "production", //false면 브라우저에서 쿠키를 조작, true면 조작할 수 없다. + secure: envConfig.mode === "production", //true 면 https를 통해서만 쿠키 전달, false면 }); // 5) 사용자 반환 res.json({ @@ -59,7 +61,7 @@ export const requireLogin = asyncWrap(async (reqExp, res, next) => { const decodedUser = jwt.verify(token, jwtCofig.secret); // 아까보낸 토근을 디코딩중. // 3) 요청 객체에 토큰 사용자 객체 추가 req.auth = decodedUser; - next();// 에러가 안나오면 next 사용, 나오면 catch쪽으로. + next(); // 에러가 안나오면 next 사용, 나오면 catch쪽으로. } catch (error) { res.clearCookie(cookieConfig.name); console.log("error in requreLogin===\n", error); @@ -84,13 +86,12 @@ export const signup = asyncWrap(async (req, res) => { if (userExist) { return res.status(422).send(`${email} 사용자가 이미 존재합니다`); } - // 3) 비밀번호 암호화 - const hash = await bcrypt.hash(password, 10); + // 3) 비밀번호 암호화는 useDb.createUser에서 처리 // 4) 새로운 사용자 만들기 const newUser = await userDb.createUser({ email, - password: hash, + password, }); - // 5) 사용자 반환 + // 5) 사용자 반환(내부적으로 몽구스가 toJSON() 호출) res.json(newUser); }); diff --git a/src/db/user.db.ts b/src/db/user.db.ts index a7c794ca22f8d6bad9225d444faf55715c9573cf..e32309a18d57d7b39522d9a4bc4b43a0289f6e49 100644 --- a/src/db/user.db.ts +++ b/src/db/user.db.ts @@ -1,7 +1,10 @@ +import bcrypt from "bcryptjs"; import { IUser, User } from "../models"; export const createUser = async (user: IUser) => { - const newUser = await User.create(user); + // 비밀번호 암호화 + const hash = await bcrypt.hash(user.password, 10); + const newUser = await User.create({ email: user.email, password: hash }); return newUser; };