Skip to content

Commit

Permalink
로그인, 재로그인, 회원가입 시 osType을 db에 저장하도록 코드 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
hyejungg committed Jan 3, 2025
1 parent 290272b commit 90f74ce
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 9 deletions.
2 changes: 2 additions & 0 deletions src/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ module.exports = {
throw new BadRequest(ErrorMessage.BadRequestMeg);
}

console.log(req.osType);

const isExist = await User.validateEmail(req);
if (!isExist) {
await User.signUp(req).then(async (userId) => {
Expand Down
20 changes: 18 additions & 2 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const jwt = require('jsonwebtoken');
const { ErrorMessage } = require('../utils/response');
const { Unauthorized } = require('../utils/errors');
const { Unauthorized, BadRequest } = require('../utils/errors');
const { OsType } = require('../utils/strings');
require('dotenv').config({ path: '../.env' });

const jwtSecret = process.env.JWT_SECRET_KEY;
Expand All @@ -20,4 +21,19 @@ const verifyToken = (req, res, next) => {
}
};

module.exports = { verifyToken };
const getOsType = (req, res, next) => {
const userAgent = req.headers['user-agent'];
if (!userAgent) {
throw new BadRequest(ErrorMessage.userAgentNotFound);
}
const osType = userAgent.split('/')[0].split('-')[1];
const osTypeToUpperCase = String(osType).toUpperCase();

if (!Object.keys(OsType).includes(osTypeToUpperCase)) {
throw new BadRequest(ErrorMessage.userAgentInOsInfoNotFound);
}
req.osType = String(osType).toUpperCase();
return next();
};

module.exports = { verifyToken, getOsType };
32 changes: 29 additions & 3 deletions src/models/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const bcrypt = require('bcryptjs');
const { NotFound, Conflict } = require('../utils/errors');
const { NotFound, Conflict, BadRequest } = require('../utils/errors');
const { ErrorMessage } = require('../utils/response');
const db = require('../config/db');
const { trimToString } = require('../utils/util');
Expand All @@ -10,6 +10,7 @@ module.exports = {
const email = req.body.email;
const password = req.body.password;
const fcmToken = req.body.fcmToken;
const osType = req.osType;

const hashPassword = bcrypt.hashSync(password, 10);

Expand All @@ -29,8 +30,8 @@ module.exports = {
}

const sqlInsert =
'INSERT IGNORE INTO users (email, password, fcm_token) VALUES (?, ?, ?)';
const params = [email, hashPassword, fcmToken];
'INSERT IGNORE INTO users (email, password, fcm_token, os_type) VALUES (?, ?, ?, ?)';
const params = [email, hashPassword, fcmToken, osType];

const [rows] = await db.queryWithTransaction(sqlInsert, params);

Expand All @@ -43,6 +44,7 @@ module.exports = {
const email = req.body.email;
const password = req.body.password;
const fcmToken = req.body.fcmToken;
const osType = req.osType;

const sqlSelect =
'SELECT user_id, email, nickname, fcm_token, password, is_active FROM users WHERE email = ?';
Expand All @@ -53,6 +55,9 @@ module.exports = {
}

const checkPassword = bcrypt.compareSync(password, selectRows[0].password);
if (!checkPassword) {
throw new BadRequest(ErrorMessage.signInPasswordNotCorrect);
}

// fcm 토큰이 다른 유저에 존재한다면, 다른 유저를 null 처리
const sqlSelectByFcmToken =
Expand Down Expand Up @@ -85,6 +90,16 @@ module.exports = {
}
}

// osType 저장
const sqlUpdate = 'UPDATE users SET os_type = ? WHERE user_id = ?';
const params = [osType, selectRows[0].user_id];

const [updateRows] = await db.queryWithTransaction(sqlUpdate, params);

if (updateRows.affectedRows < 1) {
throw new NotFound(ErrorMessage.failedUpdateFcmToken);
}

return {
result: checkPassword,
userId: selectRows[0].user_id,
Expand All @@ -94,6 +109,7 @@ module.exports = {
restartSignIn: async function (req) {
const email = req.body.email;
const fcmToken = req.body.fcmToken;
const osType = req.osType;

const sqlSelect =
'SELECT user_id, email, nickname FROM users WHERE email = ? AND is_active = true';
Expand All @@ -115,6 +131,16 @@ module.exports = {
}
}

// osType 저장
const sqlUpdate = 'UPDATE users SET os_type = ? WHERE user_id = ?';
const params = [osType, rows[0].user_id];

const [updateRows] = await db.queryWithTransaction(sqlUpdate, params);

if (updateRows.affectedRows < 1) {
throw new NotFound(ErrorMessage.failedUpdateFcmToken);
}

return Object.setPrototypeOf(rows, []);
},
selectUser: async function (userId) {
Expand Down
8 changes: 4 additions & 4 deletions src/routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const authController = require('../controllers/authController');
const { verifyToken } = require('../middleware/auth');
const { verifyToken, getOsType } = require('../middleware/auth');
const express = require('express');
const router = new express.Router();

router.post('/signin', authController.signIn);
router.post('/signup', authController.signUp);
router.post('/signin', getOsType, authController.signIn);
router.post('/signup', getOsType, authController.signUp);
router.post('/logout', verifyToken, authController.logout);
router.post('/check-email', authController.checkEmail);
router.post('/password-mail', authController.sendMail);
router.post('/re-signin', authController.restartSignIn);
router.post('/re-signin', getOsType, authController.restartSignIn);
router.post('/refresh', authController.refreshToken);

module.exports = router;
4 changes: 4 additions & 0 deletions src/utils/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ const ErrorMessage = {
unActvieUserDelete: '매주 월요일 자정, 탈퇴 유저 삭제 실패',

unActiveUser: '탈퇴 처리된 유저',
signInPasswordNotCorrect: '입력하신 비밀번호가 올바르지 않음',
signUpFailed: 'wishboard 앱 회원가입 실패',
existsUserFcmToken: '이미 존재하는 사용자의 fcmToken',
validateEmail: '이미 존재하는 이메일 주소',
Expand All @@ -134,6 +135,9 @@ const ErrorMessage = {
failedCreateToken: 'token 생성 실패',
userIdNotFound: '토큰을 생성하기 위한 userId data 없음',

userAgentNotFound: 'User-Agent가 없음',
userAgentInOsInfoNotFound: 'User-Agent에 OS정보가 없음',

/* 버전 */
versionInfoNotFound: '버전 정보 없음',
versionUpdatedFailed: '버전 정보 수정 실패',
Expand Down
7 changes: 7 additions & 0 deletions src/utils/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ const ItemAddType = {
MANUAL: 'MANUAL',
};

const OsType = {
IOS: 'IOS',
AOS: 'AOS',
SERVER: 'SERVER',
};

module.exports = {
Strings,
ItemAddType,
OsType,
};

0 comments on commit 90f74ce

Please sign in to comment.