Skip to content

Commit

Permalink
[BE][Feat] : #42 : 로그인 api 구현
Browse files Browse the repository at this point in the history
- 로그인을 위한 패키지 (bcrypt, express-validator, jsonwebtoken) 설치
- 로그인을 위한 router, controller, service, repository, middleware 구현
- index.js router 호출 및 사용
- 로그인 api 구현 테스트
  • Loading branch information
happyhyep committed Nov 11, 2024
1 parent eb33e2d commit 9be7e01
Show file tree
Hide file tree
Showing 10 changed files with 420 additions and 7 deletions.
5 changes: 4 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"express-validator": "^7.2.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.13.1",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"ws": "^8.18.0"
"ws": "^8.11.0"
}
}
File renamed without changes.
16 changes: 16 additions & 0 deletions backend/src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { loginUser } from '../services/authService.js';

export const login = async (req, res) => {
const { id, password } = req.body;

try {
const token = await loginUser(id, password);
if (!token) {
return res.status(401).json({ message: 'Invalid ID or password' });
}
return res.status(200).json({ token });
} catch (error) {
console.error('Login error:', error);
return res.status(500).json({ message: 'Server error occurred' });
}
};
File renamed without changes.
2 changes: 1 addition & 1 deletion backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { specs } from '../swaggerConfig.js';
import { pool } from './db/db.js';
import { PORT } from './constants/constants.js';
import { initializeWebSocketServer } from './websocketServer.js';
import authRouter from './routes/authRouter.js';
import { authRouter } from './routes/authRouter.js';

const app = express();
app.use(express.json());
Expand Down
9 changes: 9 additions & 0 deletions backend/src/middleware/validationMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { validationResult } from 'express-validator';

export const validationMiddleware = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
6 changes: 6 additions & 0 deletions backend/src/repositories/userRepository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { pool } from '../db/db.js';

export const findUserById = async id => {
const result = await pool.query('SELECT * FROM "main"."user" WHERE id = $1', [id]);
return result.rows[0];
};
6 changes: 3 additions & 3 deletions backend/src/routes/authRouter.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import express from 'express';
import { body } from 'express-validator';
import { login } from '../controllers/authController.js';
import validationMiddleware from '../middleware/validationMiddleware.js';
import { validationMiddleware } from '../middleware/validationMiddleware.js';

export const router = express.Router();
export const authRouter = express.Router();

router.post(
authRouter.post(
'/login',
[
body('id').notEmpty().withMessage('ID is required'),
Expand Down
19 changes: 19 additions & 0 deletions backend/src/services/authService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { findUserById } from '../repositories/userRepository.js';

export const loginUser = async (id, password) => {
const user = await findUserById(id);
if (!user) {
throw new Error('User not found');
}

const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
throw new Error('Invalid password');
}

// JWT 생성
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
return { token, userId: user.id };
};
Loading

0 comments on commit 9be7e01

Please sign in to comment.