반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 러닝
- nodejs
- 박스점프
- 드림코딩
- 활동 킬로칼로리
- Til
- github
- 홈트
- 독서 리뷰
- 월별 운동일지
- dql
- express
- 달리기
- 크로스핏
- 메디패치
- 위코드
- node.js
- 운동일지
- Udemy
- dml
- node
- SQL
- MySQL
- wecode
- 습윤밴드
- code kata
- axios
- 걷기
- git
- JavaScript
Archives
- Today
- Total
RISK IT
[TIL22_23.1.30.] [Node] "westagram" 인증 & 인가 (bcrypt, jwt 모듈) 본문
IT/TIL
[TIL22_23.1.30.] [Node] "westagram" 인증 & 인가 (bcrypt, jwt 모듈)
nomoremystery 2023. 1. 31. 00:28반응형
추가된 부분
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
bcrypt, jsonwebtoken 모듈 추가
app.post('/users/signup', async (req, res) => {
const { name, email, password, profileImage } = req.body;
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);
await mysqlDataSource.query(
`INSERT INTO users (
name,
email,
password,
profile_image
)
VALUES (
?,
?,
?,
?
);
`,
[name, email, hashedPassword, profileImage]
);
return res.status(201).json({ message: 'userCreated' });
});
유저 회원가입하는 코드의 비밀번호를 암호화된 비밀번호로 설정
app.get('/users/signup', async (req, res) => {
const { email, password } = req.body;
const [userData] = await mysqlDataSource.query(
`
SELECT *
FROM users
WHERE email=?
`,
[email]
);
const payLoad = { email: userData.email };
const secretKey = 'mySecretKey';
const jwtToken = jwt.sign(payLoad, secretKey);
const checkHash = await bcrypt.compare(password, userData.password);
if (!checkHash) {
return res.status(400).json({ message: 'Invalid User' });
}
return res.status(200).json({ accessToken: jwtToken });
});
jwt을 이용하여 토큰 생성하는 코드 작성
전체 소스코드
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { DataSource } = require('typeorm');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const mysqlDataSource = new DataSource({
type: process.env.TYPEORM_CONNECTION,
host: process.env.TYPEORM_HOST,
port: process.env.TYPEORM_PORT,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
});
mysqlDataSource
.initialize()
.then(() => {
console.log('Data Source has been initialized!');
})
.catch((err) => {
console.error('Error during Data Source initialization', err);
mysqlDataSource.destroy();
});
const app = express();
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// health check
app.get('/ping', (req, res) => {
res.status(200).json({ message: 'pong' });
});
app.post('/users/signup', async (req, res) => {
const { name, email, password, profileImage } = req.body;
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);
await mysqlDataSource.query(
`INSERT INTO users (
name,
email,
password,
profile_image
)
VALUES (
?,
?,
?,
?
);
`,
[name, email, hashedPassword, profileImage]
);
return res.status(201).json({ message: 'userCreated' });
});
app.post('/posts', async (req, res) => {
const { title, content, postImgUrl, userId } = req.body;
await mysqlDataSource.query(
`INSERT INTO posts (
title,
content,
post_image_url,
user_id
)
VALUES (
?,
?,
?,
?
);
`,
[title, content, postImgUrl, userId]
);
return res.status(201).json({ message: 'postCreated' });
});
app.get('/posts', async (req, res) => {
const posts = await mysqlDataSource.query(
`SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
p.id AS postingId,
p.post_image_url AS postingImageUrl,
p.content AS postingContent
FROM posts p
INNER JOIN users u ON u.id = p.user_id;
`
);
return res.status(200).json({ posts });
});
app.get('/posts/:userId', async (req, res) => {
const { userId } = req.params;
const [result] = await mysqlDataSource.query(
`
SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
pi.post_informations AS postings
FROM users u
INNER JOIN (
SELECT
user_id,
JSON_ARRAYAGG(
JSON_OBJECT (
"postingId", id,
"postingImageUrl", post_image_url,
"postingContent", content
)
) AS post_informations
FROM posts
GROUP BY user_id
) pi
ON pi.user_id = u.id
WHERE u.id = ?;
`,
[userId]
);
return res.status(200).json({ data: result });
});
app.patch('/posts/:postId/:userId', async (req, res) => {
const { userId, postId } = req.params;
const { content } = req.body;
await mysqlDataSource.query(
`UPDATE posts
SET
content = ?
WHERE
user_id = ? AND id = ?
`,
[content, userId, postId]
);
const [result] = await mysqlDataSource.query(
`
SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
p.id AS postingId,
p.post_image_url AS postingImageUrl,
p.content AS postingContent
FROM posts p
INNER JOIN users u ON u.id = p.user_id
WHERE u.id = ? AND p.id = ?
`,
[userId, postId]
);
return res.status(201).json({ data: result });
});
app.delete('/posts/:postId', async (req, res) => {
const { postId } = req.params;
await mysqlDataSource.query(
`DELETE
FROM posts
WHERE posts.id = ?
`,
[postId]
);
return res.status(200).json({ message: 'postingDeleted' });
});
app.post('/likes/:userId/:postId', async (req, res) => {
const { userId, postId } = req.params;
await mysqlDataSource.query(
`INSERT INTO likes (
user_id,
post_id
)
VALUES (
?,
?
);
`,
[userId, postId]
);
return res.status(201).json({ message: 'likeCreated' });
});
app.get('/users/signup', async (req, res) => {
const { email, password } = req.body;
const [userData] = await mysqlDataSource.query(
`
SELECT *
FROM users
WHERE email=?
`,
[email]
);
const payLoad = { email: userData.email };
const secretKey = 'mySecretKey';
const jwtToken = jwt.sign(payLoad, secretKey);
const checkHash = await bcrypt.compare(password, userData.password);
if (!checkHash) {
return res.status(400).json({ message: 'Invalid User' });
}
return res.status(200).json({ accessToken: jwtToken });
});
const PORT = process.env.PORT;
const start = async () => {
try {
app.listen(PORT, () => console.log(`Server is listening on ${PORT}!!`));
} catch (err) {
console.error(err);
}
};
start();
반응형
'IT > TIL' 카테고리의 다른 글
[TIL24_23.2.1.] [Javascript] 문법 정리 - const{}와 const 및 try {} catch (err) {} (0) | 2023.02.01 |
---|---|
[TIL23_23.1.31.] [Node] Layered Pattern 개념 정리 (0) | 2023.01.31 |
[TIL21_23.1.29.] [NodeJS] Node 라이프사이클, 요청 및 응답 (0) | 2023.01.29 |
[TIL20_23.1.28.] [NodeJS] Node 서버 생성 (0) | 2023.01.28 |
[TIL19_23.1.27.] [Node] Express - 'westagram' feature/CRUD 코드 수정 (0) | 2023.01.27 |