code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—ฌ๊ธฐ๋„ ์œ„์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ์— ์ ์ ˆํ•œ ํ‚ค์›Œ๋“œ๊ฐ€ ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๋ฐ˜๋ณต๋ฌธ ์•ˆ์˜ `validType` ์€ ์žฌํ• ๋‹นํ•  ํ•„์š”๋Š” ์—†์–ด ๋ณด์ž…๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด `const` ๊ฐ€ ๋” ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ „์ฒด์ ์œผ๋กœ String.prototype.match ๋ฅผ ๋งŽ์ด ์‚ฌ์šฉํ•˜์…จ๋Š”๋ฐ, Regex ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•ด ๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–ฏ๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
`req.body` ์— ๋‹ค์Œ ํ‚ค๊ฐ’๋“ค ์ค‘ ํ•˜๋‚˜๊ฐ€ ์•„์˜ˆ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ, ๋Ÿฐํƒ€์ž„์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ตฌ์กฐํ™” ํ• ๋‹น ์‹œ์— ์ „์ฒด์ ์œผ๋กœ ์ฃผ์˜ํ•˜๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—ฌ๊ธฐ ๋ฐ˜๋ณต๋ฌธ ๋‚ด์˜ `info` ๋„ ์žฌํ• ๋‹นํ•  ์ผ์€ ์—†์–ด๋ณด์ด๋‹ˆ `const` ๊ฐ€ ๋” ์ ์ ˆํ•ด ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—๋Ÿฌ๋ฅผ ๋˜์ง€๋Š” ๋ถ€๋ถ„์„ ๋ชจ๋“ˆํ™”ํ•˜๊ฒŒ ๋˜๋ฉด ๋” ๋†’์€ ์‚ฌ์šฉ์„ฑ์„ ๊ฐ–๊ฒŒ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ทธ๋ฆฌ๊ณ  ์ง์ ‘ ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์—๋Ÿฌ๋ฅผ `throw` ํ•˜๊ณ , `catch` ๊ตฌ๋ฌธ์—์„œ ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด๋กœ ๊ฑด๋‚ด๋ฉด์„œ ์ตœ์ข…์ ์œผ๋กœ ์—๋Ÿฌ๋ฅผ ํ—จ๋“ค๋งํ•˜๋Š” ํ•จ์ˆ˜์—์„œ ํ•œ๋ฒˆ์— ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ „์ฒด์ ์œผ๋กœ ํ•˜๋‚˜์˜ ์ปจํŠธ๋กค๋Ÿฌ ์•ˆ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ ˆ์ฐจ๋“ค์ด ๋‚˜์—ด๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•จ์ˆ˜ ๋‹จ์œ„๋กœ ๋” ์ชผ๊ฒŒ๊ฒŒ๋˜๋ฉด, ๋‚˜์ค‘์— unit test ์‹œ์—๋„ ๋” ํŽธ๋ฆฌํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฒ€์ฆํ•˜๊ณ  ์žˆ๋Š” ์—ฌ๋Ÿฌ ๋กœ์ง๋“ค๋„, ์ ์ ˆํžˆ Service ์•ˆ์— ๋„ฃ์–ด๋‘˜ ํ•„์š”๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ hash ํ•˜๋Š” ๋ถ€๋ถ„๋„ req, res ๋งŒ ๋‹ค๋ฃจ๊ฒŒ ๋˜๋Š” ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ๋‹ค๋ฃจ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ์–ด์ƒ‰ํ•ด ๋ณด์ด๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค. ์ „๋ฐ˜์ ์œผ๋กœ ์ด ๊ฐ ํ•จ์ˆ˜๊ฐ€ ํ•˜๋‚˜์˜ ๋ช…ํ™•ํ•œ ์ผ๋งŒ ํ•˜๋„๋ก ๊ตฌ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์‘๋‹ต ๊ฐ’๋„ ํด๋ผ์ด์–ธํŠธ์™€์˜ ํ˜‘์•ฝ์— ๋”ฐ๋ผ ์ •ํ•ด์ง„ ํผ์„ ํ•ญ์ƒ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋ชจ๋“ˆํ™”ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์œ ์ง€/๋ณด์ˆ˜์— ๋” ์šฉ์ดํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const middleware = require('../middlewares'); +const { userController } = require('../controllers'); +// Route ๋Š” ์˜ค์ง Controller ์—๋งŒ ์˜์กด ํ•ฉ๋‹ˆ๋‹ค. + +router.post( + '/signup', + [middleware.validateSignUpUserData, middleware.hashPassword], + userController.signUp, +); + +module.exports = router;
JavaScript
์ด ๋ถ€๋ถ„ ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ํ•˜๋‚˜์š”? ํ‚ค๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +const bcrypt = require('bcrypt'); +const { userDao } = require('../dao'); + +const validateEmail = (email) => { + const validEmailRegExp = /\w@\w+\.\w/i; + return validEmailRegExp.test(email); +}; + +const validatePw = (pw) => { + const pwValidation = { + regexUppercase: /[A-Z]/g, + regexLowercase: /[a-z]/g, + regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g, + regexDigit: /[0-9]/g, + }; + const MIN_PW_LENGTH = 8; + const pwLength = pw.length; + + if (pwLength < MIN_PW_LENGTH) return false; + + for (const validType in pwValidation) { + if (!pwValidation[validType].test(pw)) { + return false; + } + } + + return true; +}; + +const hashPassword = async (password) => { + return await bcrypt.hash(password, 10); +}; + +const findUser = async (fields) => { + return await userDao.findUser(fields); +}; + +const createUser = async (userData) => { + return await userDao.createUser(userData); +}; + +module.exports = { + validateEmail, + validatePw, + hashPassword, + findUser, + createUser, +};
JavaScript
์ด๋Ÿฐ ํ•จ์ˆ˜๋Š” ์•„์˜ˆ ๋ชจ๋“ˆํ™”ํ•ด์„œ ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ด ๋ถ€๋ถ„ ์ž‘๋™ ์ž˜ ํ•˜๋‚˜์š”? ํ‚ค ๊ฐ’์ด ์•ˆ ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค! validation ๋กœ์ง์€ ์˜ˆ์ „ ์ œ ์ฝ”๋“œ ๊ธ์–ด์˜ค๋‹ค๊ฐ€ ๋†“์นœ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
ํ”„๋ก ํŠธ๋‹จ์—์„œ ๋ฐ›์€ `req.body`์— ์œ„ ํ‚ค๊ฐ’๋“ค์ด ๋ˆ„๋ฝ๋  ๊ฒฝ์šฐ ๊ทธ ๊ฐ’์ด undefined๋กœ ๋˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ œ๊ฐ€ ๋†“์น˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์ด ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
`RegExp.prototype.test()`๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์›”์š”์ผ์— ๋ง์”€ํ•ด์ฃผ์‹ ๋Œ€๋กœ `return res` ํ˜•ํƒœ๊ฐ€ ์•„๋‹ˆ๋ผ ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ๋ชจ๋“ˆํ™” ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!!!!!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์—๋Ÿฌ ํ•ธ๋“ค๋ง๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์‘๋‹ต๋„ ๋ชจ๋“ˆํ™” ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const middleware = require('../middlewares'); +const { userController } = require('../controllers'); +// Route ๋Š” ์˜ค์ง Controller ์—๋งŒ ์˜์กด ํ•ฉ๋‹ˆ๋‹ค. + +router.post( + '/signup', + [middleware.validateSignUpUserData, middleware.hashPassword], + userController.signUp, +); + +module.exports = router;
JavaScript
convention ์ˆ˜์ •ํ•˜๋ ค๋‹ค๊ฐ€ ๋†“์นœ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค... ๊ด€๋ จ๋œ ๋ถ€๋ถ„ ๋ชจ๋‘ ์ˆ˜์ •ํ•˜๊ณ  ํšŒ์›๊ฐ€์ž…๋„ ํ™•์ธํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
dao์™€ services๋กœ ๋ถ„๋ฆฌํ•˜๊ธฐ๋กœ ๊ฒฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ œ๊ฐ€ ์ฐฉ๊ฐํ–ˆ๋„ค์š”! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๋ฏธ๋“ค์›จ์–ด์—์„œ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ•˜๋Š” ๊ฑด๊ฐ€์š”? ์ด ๋ฐฉ๋ฒ•๋„ ๊ต‰์žฅํžˆ ์ฐธ์‹ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์„œ๋น„์Šค๊ฐ€ ์ปค์ง€๊ฒŒ ๋˜๊ฑฐ๋‚˜, ๋ชจ๋…ธ๋ฆฌํฌ๋ฅผ ์ ์šฉํ•œ๋‹ค๊ฑฐ๋‚˜, ๊ธฐํƒ€ ๋‹ค์–‘ํ•œ ๋ฐฉ์‹์œผ๋กœ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ™œ์šฉํ•˜๊ฒŒ ๋  ๊ฒฝ์šฐ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ณดํ†ต util ํ•จ์ˆ˜๋กœ ๋นผ๋‚ด์–ด ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ณตํ†ต ํ•จ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ๋” ๋ณดํŽธ์ ์ด๊ธฐ๋Š” ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
๋‹ค๋ฅธ POST ์—์„œ๋„ ํ•„์ˆ˜์ ์ธ ํ‚ค๊ฐ’๋“ค์„ ํ™•์ธํ•  ์ผ์ด ๋งŽ์ง€ ์•Š์„๊นŒ์š”? ๋ฒ”์šฉ์ ์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” + ํ•„์ˆ˜ body ํ‚ค ๊ฐ’์„ ํ™•์ธํ•˜๋Š” ๊ณตํ†ต ํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +const bcrypt = require('bcrypt'); +const { userDao } = require('../dao'); + +const validateEmail = (email) => { + const validEmailRegExp = /\w@\w+\.\w/i; + return validEmailRegExp.test(email); +}; + +const validatePw = (pw) => { + const pwValidation = { + regexUppercase: /[A-Z]/g, + regexLowercase: /[a-z]/g, + regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g, + regexDigit: /[0-9]/g, + }; + const MIN_PW_LENGTH = 8; + const pwLength = pw.length; + + if (pwLength < MIN_PW_LENGTH) return false; + + for (const validType in pwValidation) { + if (!pwValidation[validType].test(pw)) { + return false; + } + } + + return true; +}; + +const hashPassword = async (password) => { + return await bcrypt.hash(password, 10); +}; + +const findUser = async (fields) => { + return await userDao.findUser(fields); +}; + +const createUser = async (userData) => { + return await userDao.createUser(userData); +}; + +module.exports = { + validateEmail, + validatePw, + hashPassword, + findUser, + createUser, +};
JavaScript
Regex ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•ด์„œ ์กฐ๊ธˆ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? Regex.prototype.test ์ž์ฒด๊ฐ€ boolean ์„ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋˜๋‹ˆ๊นŒ์š”! +test ๋ฉ”์„œ๋“œ๊ฐ€ match ๋ณด๋‹ค ์„ฑ๋Šฅ์ƒ ์šฐ์œ„์— ์žˆ๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜ค...! ๋งค์šฐ ์œ ์šฉํ•œ ํ•จ์ˆ˜๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,93 @@ +const context = describe; + +describe('์˜ํ™”๋ชฉ๋ก API ํ…Œ์ŠคํŠธ', () => { + context('์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.', () => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.request('GET', `${baseUrl}?${param}`).as('popularMovies'); + + cy.get('@popularMovies').its('status').should('eq', 200); + cy.get('@popularMovies').its('body.results').should('have.length', 20); + }); + }); +}); + +describe('์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('์˜ํ™” ๋ชฉ๋ก ์กฐํšŒ ์‹œ', () => { + it('800ms ๋™์•ˆ Skeleton UI๊ฐ€ ๋…ธ์ถœ๋˜์—ˆ๋‹ค๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค.', () => { + cy.wait('@popularMovies'); + cy.get('.skeleton').should('have.length', 60); + cy.wait(800); + cy.get('.skeleton').should('have.length', 0); + }); + }); + + context('ํŽ˜์ด์ง€ ์ง„์ž… ์‹œ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 20); + }); + }); + + context('๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด', () => { + it('40๊ฐœ์˜ item-card ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.btn').click(); + cy.get('.item-card').should('have.length', 40); + }); + }); +}); + +describe('์งง์€ ์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular-short.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('total_pages ๊ฐ€ 1์ธ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('18๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 18); + }); + + it('๋” ๋ณด๊ธฐ ๋ฒ„ํŠผ์ด ๋…ธ์ถœ๋˜์ง€ ์•Š๋Š”๋‹ค.', () => { + cy.contains('๋”๋ณด๊ธฐ').should('not.exist'); + }); + }); +});
JavaScript
ํ˜น์‹œ 18๊ฐœ์ธ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,10 @@ +์˜ํ™” ๋ชฉ๋ก API +- ์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. + +ํŽ˜์ด์ง€ +- ํŽ˜์ด์ง€๋ฅผ ์ฆ๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค. + +UI +- ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ๋‹ค์Œ ์˜ํ™” ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. +- ์˜ํ™” ๋ชฉ๋ก์˜ ํŽ˜์ด์ง€ ๋์— ๋„๋‹ฌํ•œ ๊ฒฝ์šฐ์—๋Š” ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํ™”๋ฉด์— ์ถœ๋ ฅํ•˜์ง€ ์•Š๋Š”๋‹ค. +- ์˜ํ™” ๋ชฉ๋ก ์•„์ดํ…œ์€ Skeleton UI๋ฅผ ๊ฐ€์ง„๋‹ค.
Unknown
ํŽ˜์ด์ง€๋ฅผ ์ดˆ๊ธฐํ™”ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์ด ์žˆ์„๊นŒ์š”? โ†’ ์•„๋ž˜์˜ ์ฝ”๋ฉ˜ํŠธ๋“ค๊ณผ ๋ชฉ์ ์€ ์ด์–ด์ง‘๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์กฐ๊ธˆ ํŠน์ดํ•œ ๋ฐฉ์‹์ธ ๊ฒƒ ๊ฐ™๊ธดํ•œ๋ฐ์š”! ์ด๋ ‡๊ฒŒ ๊ฐ์ฒด๋กœ ๋ฌถ์–ด์„œ export ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ๊ฐ€์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์•„์ง ๊ตฌํ˜„๋˜์ง€ ์•Š์€ ๊ธฐ๋Šฅ์— ๋Œ€ํ•œ ํ•จ์ˆ˜๋ฅผ ๋จผ์ € ์ƒ์„ฑํ•ด๋‘์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?!
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜์—์„œ UI๋ฅผ ์กฐ์ž‘ํ•ด์ฃผ๊ณ  ์žˆ๋„ค์š”! ์ฒ˜์Œ์—” `if (PageHandler.getCurrentPage() !== total_pages)` ์กฐ๊ฑด์ด UI ์™€ ๊ด€๋ จ์ด ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ฐ๊ฐ ๋ชฉ์ ์ด ๋‹ค๋ฅด๋„ค์š”. ์—ฌ๊ธฐ์„œ ์ด ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ ๋‘ ๊ฐ€์ง€๋ฅผ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! 1. `onClickMoreButton` ๋ผ๋Š” ์ด๋ฆ„์ด ํ•ด๋‹น ํ•จ์ˆ˜๊ฐ€ ๋ฌด์—‡์„ ํ•˜๋Š”์ง€ ๋“œ๋Ÿฌ๋‚ผ ์ˆ˜ ์žˆ๋Š”๊ฐ€? 2. UI ์กฐ์ž‘๊ณผ ๋„๋ฉ”์ธ ๋กœ์ง์„ ํ•จ๊ป˜ ๋‘๋Š” ๊ฒŒ ๋งž์„๊นŒ?
@@ -0,0 +1,42 @@ +const MOVIE_TOTAL_PAGE_LIMIT = 500; + +const INITIAL_VALUE = { + page: 1, + totalPages: MOVIE_TOTAL_PAGE_LIMIT, +}; + +function PageEventHandler() { + let attr = { ...INITIAL_VALUE }; + + return { + next() { + if (!this.hasNextPage()) { + return { + page: attr.page, + done: true, + }; + } + attr.page = attr.page + 1; + + return { + page: attr.page, + done: !this.hasNextPage(), + }; + }, + getCurrentPage() { + return attr.page; + }, + setTotalPages(totalPages) { + if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) { + return; + } + attr.totalPages = totalPages; + }, + hasNextPage() { + return attr.page < attr.totalPages; + }, + }; +} + +const PageHandler = PageEventHandler(); +export default PageHandler;
JavaScript
๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ธฐ๋Šฅ๋“ค์— ๋Œ€ํ•œ ๊ตฌํ˜„๋“ค์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”! ์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ  ๋‚จ๊ฒจ ๋†“์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์กฐ๊ธˆ ๋” ์˜๋„๋ฅผ ์ „๋‹ฌ๋“œ๋ฆฌ์ž๋ฉด! `onClickMoreButton`์€ ํด๋ฆญ + ํŠน์ •๋ฒ„ํŠผ + ํ•ธ๋“ค๋Ÿฌ๋ผ๋Š” ๊ฒƒ๋งŒ ๋“œ๋Ÿฌ๋‚˜์ง€, ์ด ํ•จ์ˆ˜๊ฐ€ ์‹ค์ œ๋กœ ์–ด๋–ค ํ–‰๋™์„ ํ•˜๋Š” ์ง€๋Š” ์ „ํ˜€ ์•Œ๋ ค ์ฃผ์ง€ ๋ชปํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,93 @@ +const context = describe; + +describe('์˜ํ™”๋ชฉ๋ก API ํ…Œ์ŠคํŠธ', () => { + context('์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.', () => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.request('GET', `${baseUrl}?${param}`).as('popularMovies'); + + cy.get('@popularMovies').its('status').should('eq', 200); + cy.get('@popularMovies').its('body.results').should('have.length', 20); + }); + }); +}); + +describe('์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('์˜ํ™” ๋ชฉ๋ก ์กฐํšŒ ์‹œ', () => { + it('800ms ๋™์•ˆ Skeleton UI๊ฐ€ ๋…ธ์ถœ๋˜์—ˆ๋‹ค๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค.', () => { + cy.wait('@popularMovies'); + cy.get('.skeleton').should('have.length', 60); + cy.wait(800); + cy.get('.skeleton').should('have.length', 0); + }); + }); + + context('ํŽ˜์ด์ง€ ์ง„์ž… ์‹œ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 20); + }); + }); + + context('๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด', () => { + it('40๊ฐœ์˜ item-card ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.btn').click(); + cy.get('.item-card').should('have.length', 40); + }); + }); +}); + +describe('์งง์€ ์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular-short.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('total_pages ๊ฐ€ 1์ธ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('18๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 18); + }); + + it('๋” ๋ณด๊ธฐ ๋ฒ„ํŠผ์ด ๋…ธ์ถœ๋˜์ง€ ์•Š๋Š”๋‹ค.', () => { + cy.contains('๋”๋ณด๊ธฐ').should('not.exist'); + }); + }); +});
JavaScript
์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก ๋ฐ์ดํ„ฐ๊ฐ€ 18๊ฐœ๋ฐ–์— ์—†์„ ๋•Œ 20๊ฐœ๋ฅผ ๊ทธ๋ฆฌ์ง€ ์•Š๊ณ  ๊ฐœ์ˆ˜๋ฅผ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ํ‘œ์‹œํ•˜๋Š”์ง€ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด ์ถ”๊ฐ€ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ ๋ฌถ์–ด์„œ ๋‚ด๋ณด๋‚ด๊ธฐ ์œ„ํ•ด์„œ ์œ„์™€๊ฐ™์€ ์ข…์ข… ์‚ฌ์šฉํ•ด์™”์—ˆ๋Š”๋ฐ์š”! ์—ฌ๊ธฐ์„œ๋Š” ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋งŒ ๋‚ด๋ณด๋‚ด๊ธฐ์— ์ œ๊ฑฐํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค..! ํ˜น์‹œ ์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ export ํ•ด์•ผํ•  ๋•Œ ์–ด๋–ค ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜์‹œ๊ณ  ์„ ํ˜ธํ•˜์‹œ๋Š”์ง€ ์—ฌ์ญˆ์–ด๋ด๋„ ๋ ๊นŒ์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
figma๋ฅผ ๋ณด๊ณ  modal ์‚ฌ์šฉ๋ถ€๋ถ„์ด ์žˆ์–ด ๋ฏธ๋ฆฌ ์ž‘์„ฑํ•ด๋‘” ๊ฒƒ์ธ๋ฐ ๋ง์”€ํ•ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ์œ ์ง€๋ณด์ˆ˜์— ์–ด๋ ค์›€์„ ์ค„ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”..! ๋ช…์‹ฌํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค! ํ•ด๋‹น ๋ถ€๋ถ„์€ ์ œ๊ฑฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ™‡
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
`onClickMoreButton`์„ `getNextPopularMovieList`๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด์„œ ์—ญํ• ์„ ๋ถ„๋ฆฌํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,42 @@ +const MOVIE_TOTAL_PAGE_LIMIT = 500; + +const INITIAL_VALUE = { + page: 1, + totalPages: MOVIE_TOTAL_PAGE_LIMIT, +}; + +function PageEventHandler() { + let attr = { ...INITIAL_VALUE }; + + return { + next() { + if (!this.hasNextPage()) { + return { + page: attr.page, + done: true, + }; + } + attr.page = attr.page + 1; + + return { + page: attr.page, + done: !this.hasNextPage(), + }; + }, + getCurrentPage() { + return attr.page; + }, + setTotalPages(totalPages) { + if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) { + return; + } + attr.totalPages = totalPages; + }, + hasNextPage() { + return attr.page < attr.totalPages; + }, + }; +} + +const PageHandler = PageEventHandler(); +export default PageHandler;
JavaScript
์ œ๊ฑฐํ•˜์˜€์Šต๋‹ˆ๋‹ค! ์ด์œ ๋Š” ์•ž์„œ ๋ง์”€๋“œ๋ฆฐ ์ด์œ ์™€ ๋™์ผํ•ฉ๋‹ˆ๋‹ค! ๊ผผ๊ผผํžˆ ๋ฆฌ๋ทฐํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค ๐Ÿ™‡
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์Œ... ์ด ๋ถ€๋ถ„์€ ์ œ๊ฐ€ ์˜๋„ํ•œ ๋ฐ”์™€๋Š” ์กฐ๊ธˆ ๋‹ค๋ฅด๊ฒŒ ๋ณ€๊ฒฝ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ œ๊ฐ€ ์˜์‚ฌ ์ฝ”๋“œ๋ฅผ ์„ž์–ด๊ฐ€๋ฉฐ ์–ด๋А ์ •๋„ ๋ณ€๊ฒฝํ•ด๋ณผ๊ฒŒ์š”!
@@ -0,0 +1,18 @@ +export class LoadingHandler { + #loading; + constructor(initialValue) { + this.#loading = initialValue; + } + + start() { + this.#loading = true; + } + + end() { + this.#loading = false; + } + + isLoading() { + return this.#loading; + } +}
JavaScript
์‚ฌ์šฉ์ฒ˜๋ฅผ ๋ณด๋ฉด, ๋กœ๋”ฉ ์ƒํƒœ ์ž์ฒด๋ฅผ ํ™œ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ํ•œ ๋ฒˆ ๋ฐ–์— ์—†๊ณ , start(), end() ์‹คํ–‰๊ณผ ํ•จ๊ป˜ DOM ์กฐ์ž‘ ๋กœ์ง์ด ํ•จ๊ป˜ ์˜ค๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ์—ฌ๊ธฐ์„œ DOM ์กฐ์ž‘๋„ ๊ฐ™์ด ํ•ด์ฃผ๊ณ , ์ž…๋ ฅ์œผ๋กœ ์กฐ์ž‘ํ•  ์š”์†Œ๋ฅผ ๊ฐ™์ด ๋ฐ›์œผ๋ฉด ๋” ์‘์ง‘์„ฑ์ด ๋†’์€ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ ๋ฌถ์–ด์„œ ๋‚ด๋ณด๋‚ด๊ธฐ ์œ„ํ•จ์ด๋‹ค -> ์ปจ๋ฒค์…˜๋งŒ ๋งž๋‹ค๋ฉด ์–ด๋–ค ๋ฐฉํ–ฅ์ด๋˜ ์ƒ๊ด€ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ๋‹ค๋งŒ, ์ €๋Š” ํ•˜๋‚˜์˜ ํ•จ์ˆ˜์ธ ์ƒํ™ฉ์—์„œ ํ•จ์ˆ˜๊ฐ€ ๋” ์ถ”๊ฐ€๋˜์ง€ ์•Š์•˜๋Š”๋ฐ, ๋” ์ถ”๊ฐ€๋  ์˜ˆ์ •์ธ๋ฐ ์ด๋ ‡๊ฒŒ ํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์„œ ๋‚จ๊ธด ์ฝ”๋ฉ˜ํŠธ์ด๊ธดํ•ฉ๋‹ˆ๋‹ค! (๋ณธ๋ฌธ์˜ ์ฝ”๋ฉ˜ํŠธ์™€ ๋™์ผํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค ใ…Žใ…Ž)
@@ -0,0 +1,58 @@ +package nextstep.app.config; + +import nextstep.security.authentication.*; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextRepository; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.filter.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import java.util.List; + +@Configuration +public class SecurityConfig { + + private final MemberDetailService memberDetailService; + + public SecurityConfig(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of(new ExceptionHandlerFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new BasicAuthenticationFilter(authenticationManager()), + new LoginAuthenticationFilter(authenticationManager()))); + + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + return new DaoAuthenticationProvider(memberDetailService, new BasicPasswordMatcher()); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } +}
Java
ํ•„ํ„ฐ์˜ ์ˆœ์„œ๋Š” ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค! SecurityContextHolderFilter๋Š” BasicAuthenticationFilter, LoginAuthenticationFilter๋ณด๋‹ค ๋จผ์ € ์„ค์ •๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,77 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class BasicAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication resultAuthentication = authenticationManager.authenticate(getAuthenticationFrom(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(resultAuthentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/members"); + } + + private static Authentication getAuthenticationFrom(HttpServletRequest httpRequest) { + SecurityContext context = SecurityContextHolder.getContext(); + Authentication authentication = context.getAuthentication(); + if (authentication != null) { + return authentication; + } + + String basicToken = extractToken(httpRequest); + String[] usernameAndPassword = splitToken(basicToken); + + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static String extractToken(HttpServletRequest httpRequest) { + String authorization = httpRequest.getHeader("Authorization"); + return authorization.split(" ")[1]; + } + + private static String[] splitToken(String basicToken) { + String decodedString = Base64Convertor.decode(basicToken); + String[] usernameAndPassword = decodedString.split(":"); + validateToken(usernameAndPassword); + return usernameAndPassword; + } + + private static void validateToken(String[] usernameAndPassword) { + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + } +}
Java
๊ฐ ํ•„ํ„ฐ์—์„œ SecurityContext๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๋Š” SecurityContextHolder๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.exception.FilterChainNotFoundException; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.List; + +public class FilterChainProxy extends GenericFilterBean { + + private final List<SecurityFilterChain> filterChains; + + public FilterChainProxy(List<SecurityFilterChain> filterChains) { + this.filterChains = filterChains; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + List<Filter> filters = getFilters(httpRequest); + VirtualFilterChain virtualFilterChain = new VirtualFilterChain(filters, chain); + virtualFilterChain.doFilter(servletRequest, servletResponse); + } + + private List<Filter> getFilters(HttpServletRequest httpRequest) { + return filterChains.stream() + .filter(filterChain -> filterChain.matches(httpRequest)) + .findFirst() + .map(SecurityFilterChain::filters) + .orElseThrow(FilterChainNotFoundException::new); + } + + public static class VirtualFilterChain implements FilterChain { + + private final List<Filter> filters; + private final FilterChain originalChain; + private int currentPosition = 0; + + public VirtualFilterChain(List<Filter> filters, FilterChain originalChain) { + this.filters = filters; + this.originalChain = originalChain; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + if (currentPosition >= filters.size()) { + originalChain.doFilter(request, response); + } else { + Filter filter = filters.get(currentPosition++); + filter.doFilter(request, response, this); + } + } + } +}
Java
์ง€๊ธˆ์€ ๋ชจ๋“  ์ฒด์ธ์˜ ํ•„ํ„ฐ๋ฅผ ์‹คํ–‰ํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”. ์ง€๊ธˆ ํ”„๋กœ์ ํŠธ์—์„  ํ•˜๋‚˜์˜ ํ•„ํ„ฐ ์ฒด์ธ๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์ง€๋งŒ, ์—ฌ๋Ÿฌ ํ•„ํ„ฐ ์ฒด์ธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ๊ฒฝ์šฐ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,67 @@ +package nextstep.security.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { + try { + chain.doFilter(request, response); + } catch (Exception e) { + createErrorResponse(e, response); + } + } + + private void createErrorResponse(Throwable e, HttpServletResponse response) throws IOException { + if (e instanceof Exception) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + if (e instanceof AuthenticationException) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + + if (e instanceof IllegalArgumentException) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + } + + ErrorResponse errorResponse = new ErrorResponse(response.getStatus(), e.getMessage()); + String errorResponseJson = errorResponse.toJson(); + response.getWriter().write(errorResponseJson); + } + + public static class ErrorResponse { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private final Integer code; + private final String message; + + public ErrorResponse(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String toJson() throws JsonProcessingException { + return objectMapper.writeValueAsString(this); + } + } +}
Java
> ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ clearContext๋Š” ExceptionHandlerFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ๊ณ , ์š”์ฒญ ์™„๋ฃŒ ํ›„ clearContext๋Š” SecurityContextHolderFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒŒ ๋งž๋Š” ๋ฐฉ์‹์ธ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. Filter์˜ ์—ญํ• ์„ ์ž˜ ๋‚˜๋ˆ ์ฃผ์…จ์–ด์š” ๐Ÿ‘ ์กฐ๊ธˆ ๋” ์ฝ”๋“œ๋ฅผ ๋ฐœ์ „์‹œ์ผœ ๋ณธ๋‹ค๋ฉด ์˜ˆ์™ธ ์ƒํ™ฉ์— ๋”ฐ๋ฅธ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๊ฐ€ ์ถ”๊ฐ€๋˜๊ณ , SecurityContextHolder์™€ ๊ด€๋ จ๋œ ๋ชจ๋“  ์—ญํ• ์€ SecurityContextHolderFilter์—์„œ ๋‹ด๋‹นํ•˜๋„๋ก ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Map; + +public class LoginAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public LoginAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication authentication = authenticationManager.authenticate(getAuthentication(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(authentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/login"); + } + + private static UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + validateParameter(parameterMap); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static void validateParameter(Map<String, String[]> parameterMap) { + if (parameterMap.get("username") == null || parameterMap.get("password") == null) { + throw new IllegalArgumentException("Missing required parameter"); + } + } +}
Java
SPRING_SECURITY_CONTEXT_KEY๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ์—ญํ• ์€ SecurityContextRepository์—๊ฒŒ ๋„˜๊ฒจ์ฃผ๋ฉด ์ข‹๊ฒ ๋„ค์š”!
@@ -0,0 +1,39 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.context.SecurityContextRepository; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + SecurityContext securityContext = securityContextRepository.loadContext(httpRequest); + SecurityContextHolder.setContext(securityContext); + + try { + chain.doFilter(httpRequest, response); + } finally { + securityContextRepository.saveContext(securityContext, httpRequest, httpResponse); + SecurityContextHolder.clearContext(); + } + } +}
Java
> 4๋‹จ๊ณ„ SecurityContextHolderFilter ๊ตฌํ˜„ ์ค‘ clearContext๋ฅผ SecurityContextHolderFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒŒ ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, clearContext๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ํ…Œ์ŠคํŠธ๊ฐ€ ์‹คํŒจํ•ฉ๋‹ˆ๋‹ค. ์ผ๋‹จ ์ œ์ถœ์„ ์œ„ํ•ด ์ฃผ์„์ฒ˜๋ฆฌํ–ˆ๋Š”๋ฐ, ํ…Œ์ŠคํŠธ๊ฐ€ ์‹คํŒจํ•˜๋Š” ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ```suggestion securityContextRepository.saveContext(securityContext, httpRequest, httpResponse); SecurityContextHolder.clearContext(); ``` ์œ„์™€ ๊ฐ™์ด ์ˆ˜์ •ํ•˜๋ฉด ์ž˜ ๋™์ž‘ํ•  ๊ฒƒ ๊ฐ™์€๋ฐ ์™œ ๊ทธ๋Ÿด์ง€ ๊ณ ๋ฏผํ•ด๋ณด์•„์š” :)
@@ -0,0 +1,58 @@ +package nextstep.app.config; + +import nextstep.security.authentication.*; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextRepository; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.filter.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import java.util.List; + +@Configuration +public class SecurityConfig { + + private final MemberDetailService memberDetailService; + + public SecurityConfig(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of(new ExceptionHandlerFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new BasicAuthenticationFilter(authenticationManager()), + new LoginAuthenticationFilter(authenticationManager()))); + + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + return new DaoAuthenticationProvider(memberDetailService, new BasicPasswordMatcher()); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } +}
Java
SecurityContextHolderFilter ๊ฐ€ ๋จผ์ € ์‹คํ–‰์ด ๋˜์–ด์•ผ ์š”์ฒญ์ด ์‹œ์ž‘ํ•˜๊ณ  ๋๋‚  ๋•Œ SecurityContext๋ฅผ ์ ์ ˆํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”. ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋ถ€๋ถ„์ด ๋งž์„๊นŒ์š”?
@@ -0,0 +1,39 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.context.SecurityContextRepository; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + SecurityContext securityContext = securityContextRepository.loadContext(httpRequest); + SecurityContextHolder.setContext(securityContext); + + try { + chain.doFilter(httpRequest, response); + } finally { + securityContextRepository.saveContext(securityContext, httpRequest, httpResponse); + SecurityContextHolder.clearContext(); + } + } +}
Java
์ด์œ ๋ฅผ ์ž˜ ๋ชจ๋ฅด๊ฒ ๋„ค์š”.. ใ… ใ…  ๊ทผ๋ฐ ์ˆ˜์ •ํ•˜๋‹ค๊ฐ€ ๋“  ์ƒ๊ฐ์ธ๋ฐ, ๊ฐ ํ•„ํ„ฐ์—์„œ `securityContextRepository.saveContext` ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์œผ๋‹ˆ๊นŒ SecurityContextHolderFilter์—์„œ๋Š” saveContext ์ˆ˜ํ–‰์„ ์•ˆ ํ•ด๋„ ๋˜์ง€ ์•Š๋‚˜์š”?
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.exception.FilterChainNotFoundException; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.List; + +public class FilterChainProxy extends GenericFilterBean { + + private final List<SecurityFilterChain> filterChains; + + public FilterChainProxy(List<SecurityFilterChain> filterChains) { + this.filterChains = filterChains; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + List<Filter> filters = getFilters(httpRequest); + VirtualFilterChain virtualFilterChain = new VirtualFilterChain(filters, chain); + virtualFilterChain.doFilter(servletRequest, servletResponse); + } + + private List<Filter> getFilters(HttpServletRequest httpRequest) { + return filterChains.stream() + .filter(filterChain -> filterChain.matches(httpRequest)) + .findFirst() + .map(SecurityFilterChain::filters) + .orElseThrow(FilterChainNotFoundException::new); + } + + public static class VirtualFilterChain implements FilterChain { + + private final List<Filter> filters; + private final FilterChain originalChain; + private int currentPosition = 0; + + public VirtualFilterChain(List<Filter> filters, FilterChain originalChain) { + this.filters = filters; + this.originalChain = originalChain; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + if (currentPosition >= filters.size()) { + originalChain.doFilter(request, response); + } else { + Filter filter = filters.get(currentPosition++); + filter.doFilter(request, response, this); + } + } + } +}
Java
ํ•˜๋‚˜์˜ ํ•„ํ„ฐ ์ฒด์ธ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ๋ณด์žฅ๋˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ์ด ์š”์ฒญ์ด filterChain์— ๋งž๋Š” ์š”์ฒญ์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +package nextstep.security.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { + try { + chain.doFilter(request, response); + } catch (Exception e) { + createErrorResponse(e, response); + } + } + + private void createErrorResponse(Throwable e, HttpServletResponse response) throws IOException { + if (e instanceof Exception) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + if (e instanceof AuthenticationException) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + + if (e instanceof IllegalArgumentException) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + } + + ErrorResponse errorResponse = new ErrorResponse(response.getStatus(), e.getMessage()); + String errorResponseJson = errorResponse.toJson(); + response.getWriter().write(errorResponseJson); + } + + public static class ErrorResponse { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private final Integer code; + private final String message; + + public ErrorResponse(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String toJson() throws JsonProcessingException { + return objectMapper.writeValueAsString(this); + } + } +}
Java
ํ•„ํ„ฐ ์ˆœ์„œ๋ฅผ ๋ณ€๊ฒฝํ–ˆ๊ณ  (SecurityContextHolderFilter -> Basic -> Login) SecurityContextHolderFilter ์˜ finally ์ ˆ์—์„œ clearContext๋ฅผ ์ˆ˜ํ–‰ํ•˜๋‹ˆ๊นŒ ๊ตณ์ด ExceptionHandlerFilter์—์„œ ์ˆ˜ํ–‰์„ ์•ˆ ํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋‚ด์šฉ์ด ๋งž์„๊นŒ์š”?
@@ -0,0 +1,58 @@ +package nextstep.app.config; + +import nextstep.security.authentication.*; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextRepository; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.filter.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import java.util.List; + +@Configuration +public class SecurityConfig { + + private final MemberDetailService memberDetailService; + + public SecurityConfig(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of(new ExceptionHandlerFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new BasicAuthenticationFilter(authenticationManager()), + new LoginAuthenticationFilter(authenticationManager()))); + + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + return new DaoAuthenticationProvider(memberDetailService, new BasicPasswordMatcher()); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } +}
Java
> SecurityContextHolderFilter ๊ฐ€ ๋จผ์ € ์‹คํ–‰์ด ๋˜์–ด์•ผ ์š”์ฒญ์ด ์‹œ์ž‘ํ•˜๊ณ  ๋๋‚  ๋•Œ SecurityContext๋ฅผ ์ ์ ˆํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”. ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋ถ€๋ถ„์ด ๋งž์„๊นŒ์š”? ์ •ํ™•ํžˆ ์ดํ•ดํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘
@@ -0,0 +1,58 @@ +package nextstep.app.config; + +import nextstep.security.authentication.*; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextRepository; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.filter.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import java.util.List; + +@Configuration +public class SecurityConfig { + + private final MemberDetailService memberDetailService; + + public SecurityConfig(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of(new ExceptionHandlerFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new BasicAuthenticationFilter(authenticationManager()), + new LoginAuthenticationFilter(authenticationManager()))); + + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + return new DaoAuthenticationProvider(memberDetailService, new BasicPasswordMatcher()); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } +}
Java
HttpSessionSecurityContextRepository๋ฅผ ๋งค๋ฒˆ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ , Spring Bean์œผ๋กœ ๋“ฑ๋กํ•˜์—ฌ ์žฌ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,67 @@ +package nextstep.security.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { + try { + chain.doFilter(request, response); + } catch (Exception e) { + createErrorResponse(e, response); + } + } + + private void createErrorResponse(Throwable e, HttpServletResponse response) throws IOException { + if (e instanceof Exception) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + if (e instanceof AuthenticationException) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + + if (e instanceof IllegalArgumentException) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + } + + ErrorResponse errorResponse = new ErrorResponse(response.getStatus(), e.getMessage()); + String errorResponseJson = errorResponse.toJson(); + response.getWriter().write(errorResponseJson); + } + + public static class ErrorResponse { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private final Integer code; + private final String message; + + public ErrorResponse(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String toJson() throws JsonProcessingException { + return objectMapper.writeValueAsString(this); + } + } +}
Java
> ํ•„ํ„ฐ ์ˆœ์„œ๋ฅผ ๋ณ€๊ฒฝํ–ˆ๊ณ  (SecurityContextHolderFilter -> Basic -> Login) SecurityContextHolderFilter ์˜ finally ์ ˆ์—์„œ clearContext๋ฅผ ์ˆ˜ํ–‰ํ•˜๋‹ˆ๊นŒ ๊ตณ์ด ExceptionHandlerFilter์—์„œ ์ˆ˜ํ–‰์„ ์•ˆ ํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋‚ด์šฉ์ด ๋งž์„๊นŒ์š”? ๋งž์Šต๋‹ˆ๋‹ค ๐Ÿ‘ ์ถ”๊ฐ€๋กœ AuthenticationException ์ด์™ธ์— ๋‹ค๋ฅธ ์˜ˆ์™ธ๋Š” ์–ด๋–ค๊ฒŒ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๊ณ , ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•˜๋ฉด ์ข‹์„์ง€ ๊ณ ๋ฏผํ•ด๋ณด๋Š” ๊ฒƒ๋„ ํ•™์Šต์— ๋„์›€์ด ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Map; + +public class LoginAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public LoginAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication authentication = authenticationManager.authenticate(getAuthentication(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(authentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/login"); + } + + private static UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + validateParameter(parameterMap); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static void validateParameter(Map<String, String[]> parameterMap) { + if (parameterMap.get("username") == null || parameterMap.get("password") == null) { + throw new IllegalArgumentException("Missing required parameter"); + } + } +}
Java
SPRING_SECURITY_CONTEXT_KEY์˜ ์—ญํ• ์ด HttpSessionSecurityContextRepository๋กœ ๋„˜์–ด๊ฐ”์œผ๋‹ˆ, ํ•ด๋‹น ์ƒ์ˆ˜๋„ HttpSessionSecurityContextRepository๋กœ ๋„˜์–ด๊ฐ€๋ฉด ์—ญํ• ์ด ๋ช…ํ™•ํ•ด ์งˆ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Map; + +public class LoginAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public LoginAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication authentication = authenticationManager.authenticate(getAuthentication(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(authentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/login"); + } + + private static UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + validateParameter(parameterMap); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static void validateParameter(Map<String, String[]> parameterMap) { + if (parameterMap.get("username") == null || parameterMap.get("password") == null) { + throw new IllegalArgumentException("Missing required parameter"); + } + } +}
Java
> ์ด์œ ๋ฅผ ์ž˜ ๋ชจ๋ฅด๊ฒ ๋„ค์š”.. ใ… ใ…  ๊ทผ๋ฐ ์ˆ˜์ •ํ•˜๋‹ค๊ฐ€ ๋“  ์ƒ๊ฐ์ธ๋ฐ, ๊ฐ ํ•„ํ„ฐ์—์„œ securityContextRepository.saveContext ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์œผ๋‹ˆ๊นŒ SecurityContextHolderFilter์—์„œ๋Š” saveContext ์ˆ˜ํ–‰์„ ์•ˆ ํ•ด๋„ ๋˜์ง€ ์•Š๋‚˜์š”? ๋ฐ˜๋Œ€๋กœ ์ ‘๊ทผํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ง€๊ธˆ์˜ ๊ตฌ์กฐ์—์„  ๊ฐ ํ•„ํ„ฐ์—์„œ `saveContext`๋ฅผ ํ˜ธ์ถœํ•ด์ค˜์•ผ ํ•˜๋Š”๋ฐ, SecurityContextHolderFilter์—์„œ ๋‹ด๋‹นํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด ๊ฐ ํ•„ํ„ฐ์—์„  SecurityContext์— ๋Œ€ํ•œ ์‹ ๊ฒฝ์„ ์•ˆ์“ฐ๋„๋ก ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,77 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class BasicAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication resultAuthentication = authenticationManager.authenticate(getAuthenticationFrom(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(resultAuthentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/members"); + } + + private static Authentication getAuthenticationFrom(HttpServletRequest httpRequest) { + SecurityContext context = SecurityContextHolder.getContext(); + Authentication authentication = context.getAuthentication(); + if (authentication != null) { + return authentication; + } + + String basicToken = extractToken(httpRequest); + String[] usernameAndPassword = splitToken(basicToken); + + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static String extractToken(HttpServletRequest httpRequest) { + String authorization = httpRequest.getHeader("Authorization"); + return authorization.split(" ")[1]; + } + + private static String[] splitToken(String basicToken) { + String decodedString = Base64Convertor.decode(basicToken); + String[] usernameAndPassword = decodedString.split(":"); + validateToken(usernameAndPassword); + return usernameAndPassword; + } + + private static void validateToken(String[] usernameAndPassword) { + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + } +}
Java
๊ฐ Filter๊ฐ€ SecurityContextRepository์— ๋Œ€ํ•œ ์˜์กด์„ฑ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋„๋ก ๊ตฌํ˜„ํ•ด์ฃผ์…จ๋„ค์š”. ์Šคํ”„๋ง์€ ๋‹ค๋ฅธ Filter์—์„œ SecurityContextRepository์˜ ๋‚ด๋ถ€ ๊ตฌํ˜„์„ ๋ชฐ๋ผ๋„ SecurityContextHolder.getContext()๋ฅผ ํ†ตํ•ด ์ธ์ฆ ์ •๋ณด๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„๋˜์–ด ์žˆ๋Š”๋ฐ์š”. ์ด๋ ‡๊ฒŒ ๊ตฌ์กฐ๋ฅผ ์„ค๊ณ„ํ•œ ์ด์œ ์— ๋Œ€ํ•ด ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,67 @@ +package nextstep.security.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { + try { + chain.doFilter(request, response); + } catch (Exception e) { + createErrorResponse(e, response); + } + } + + private void createErrorResponse(Throwable e, HttpServletResponse response) throws IOException { + if (e instanceof Exception) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + if (e instanceof AuthenticationException) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + + if (e instanceof IllegalArgumentException) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + } + + ErrorResponse errorResponse = new ErrorResponse(response.getStatus(), e.getMessage()); + String errorResponseJson = errorResponse.toJson(); + response.getWriter().write(errorResponseJson); + } + + public static class ErrorResponse { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private final Integer code; + private final String message; + + public ErrorResponse(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String toJson() throws JsonProcessingException { + return objectMapper.writeValueAsString(this); + } + } +}
Java
๋กœ๊ทธ์ธ ์‹œ์— ์ž…๋ ฅ๊ฐ’์ด ๋ˆ„๋ฝ๋์„ ๊ฒฝ์šฐ์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ์ถ”๊ฐ€ํ–ˆ๊ณ , ExceptionHandlerFilter ์—์„œ์˜ ์—๋Ÿฌ ์‘๋‹ต๊ฐ’ ์ƒ์„ฑ ๋กœ์ง์„ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์˜ˆ์ƒ ๋ชปํ•œ ์˜ˆ์™ธ๋Š” 500 ์—๋Ÿฌ ์ฒ˜๋ฆฌํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,56 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Map; + +public class LoginAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public LoginAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication authentication = authenticationManager.authenticate(getAuthentication(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(authentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/login"); + } + + private static UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + validateParameter(parameterMap); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static void validateParameter(Map<String, String[]> parameterMap) { + if (parameterMap.get("username") == null || parameterMap.get("password") == null) { + throw new IllegalArgumentException("Missing required parameter"); + } + } +}
Java
SecurityContextHolderFilter์˜ ์—ญํ• ์— ๋Œ€ํ•ด ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ณด๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,77 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class BasicAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication resultAuthentication = authenticationManager.authenticate(getAuthenticationFrom(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(resultAuthentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/members"); + } + + private static Authentication getAuthenticationFrom(HttpServletRequest httpRequest) { + SecurityContext context = SecurityContextHolder.getContext(); + Authentication authentication = context.getAuthentication(); + if (authentication != null) { + return authentication; + } + + String basicToken = extractToken(httpRequest); + String[] usernameAndPassword = splitToken(basicToken); + + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static String extractToken(HttpServletRequest httpRequest) { + String authorization = httpRequest.getHeader("Authorization"); + return authorization.split(" ")[1]; + } + + private static String[] splitToken(String basicToken) { + String decodedString = Base64Convertor.decode(basicToken); + String[] usernameAndPassword = decodedString.split(":"); + validateToken(usernameAndPassword); + return usernameAndPassword; + } + + private static void validateToken(String[] usernameAndPassword) { + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + } +}
Java
SecurityContextHolderFilter๋งŒ SecurityContextRepository์— ๋Œ€ํ•œ ์˜์กด์„ฑ์„ ๊ฐ€์ง€๋„๋ก ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,67 @@ +package nextstep.security.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { + try { + chain.doFilter(request, response); + } catch (Exception e) { + createErrorResponse(e, response); + } + } + + private void createErrorResponse(Throwable e, HttpServletResponse response) throws IOException { + if (e instanceof Exception) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + if (e instanceof AuthenticationException) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + + if (e instanceof IllegalArgumentException) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + } + + ErrorResponse errorResponse = new ErrorResponse(response.getStatus(), e.getMessage()); + String errorResponseJson = errorResponse.toJson(); + response.getWriter().write(errorResponseJson); + } + + public static class ErrorResponse { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private final Integer code; + private final String message; + + public ErrorResponse(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String toJson() throws JsonProcessingException { + return objectMapper.writeValueAsString(this); + } + } +}
Java
```suggestion try { chain.doFilter(request, response); } catch (AuthenticationException e) { } catch (IllegalArgumentException e) { } catch (Exception e) { } ``` instanceof ๋Œ€์‹  ์œ„์™€ ๊ฐ™์ด ์ž‘์„ฑํ•˜๋Š”๊ฒŒ ๋” ๋ช…ํ™•ํ•  ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
```suggestion className={`loginBtn ${ idValue.indexOf('@') > -1 && pwValue.length >= 5 ? 'loginBtnLive' : '' }`} ``` className์˜ ๋™์  ์‚ฌ์šฉ์„ ์ ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ์ธ๋ผ์ธ ์Šคํƒ€์ผ์˜ ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์•„์„œ, ํŒ€์›์ด class๋ฅผ ์ˆ˜์ •ํ–ˆ์„ ๋•Œ class๊ฐ€ ์ ์šฉ์ด ์•ˆ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•ด์š”. ์กฐ๊ฑด ์—ฐ์‚ฐ์ž๋ฅผ ํ™œ์šฉํ•ด์„œ className์„ ๋™์ ์œผ๋กœ ์“ธ ์ˆ˜ ์žˆ์Œ className={์›๋ž˜ ํด๋ž˜์Šค +ํ™œ์„ฑํ™” ํด๋ž˜์Šค <-- ์กฐ๊ฑด ์—ฐ์‚ฐ์ž๋กœ ํด๋ž˜์Šค ์ถ”๊ฐ€ ์—ฌ๋ถ€ ๊ฒฐ์ •}
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
className ๋™์  ์‚ฌ์šฉ์„ ํ•˜๊ฒŒ ๋˜๋ฉด style ์Šคํ…Œ์ดํŠธ๊ฐ€ ํ•„์š”์—†๊ฒŒ ๋œ๋‹ค๊ณ  ํ•ด์š”! disabled๋„ state๋กœ ๋‚จ๊ฒจ๋‘˜์ง€ ๊ณ ๋ฏผํ•ด๋ณด๋ผ๊ณ  ํ•˜์‹ญ๋‹ˆ๋‹ค (from ๋ฉ˜ํ† ๋‹˜..)
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
className ๋™์  ์‚ฌ์šฉ์„ ํ•˜๊ฒŒ ๋˜๋ฉด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๊ด€๋ จ ํ•จ์ˆ˜๋ฅผ ๋‹ค ์ง€์›Œ๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
```suggestion import { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import './Login.scss'; ``` scss๋ฅผ ๋ฐ‘์œผ๋กœ ๋‚ด๋ ค์ฃผ๋ฉด ์ข‹์„๊ฑฐ๊ฐ™๋„ค์š”
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
ํ›… ๋ฐ‘์œผ๋กœ ๋ถ™์—ฌ์ฃผ๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ์š”?
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
์ปดํฌ๋„ŒํŠธ ์ด๋ฆ„์„ Feed ๋กœ ๋ฐ”๊ฟ”๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!! ์ด๋ฆ„์— ์˜๋ฏธ๋ฅผ ๋” ๋‹ด์•„์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
mainRight๋„ ์ปดํฌ๋„ŒํŠธ๋กœ ๋งŒ๋“ค์–ด์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ์ด๋ ‡๊ฒŒ ํ•ด์ฃผ๋ฉด main.js ๋‚ด์šฉ, scss ๋‚ด์šฉ๋„ ๋” ๊ฐ„๋‹จํ•ด์งˆ ๊ฒƒ ๊ฐ™์Œ! ```suggestion <MainRight /> ```
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
```suggestion <Footer /> ``` ์ปดํฌ๋„ŒํŠธ๋กœ ๋ถ„๋ฆฌํ•ด์ฃผ๊ณ , footer ์‹œ๋ฉ˜ํ‹ฑ ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์ข‹์„ ๋“ฏ!
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
๊ฐ ๋ฉ”๋‰ด๋ฅผ JS ํŒŒ์ผ์— ์ €์žฅํ•˜๊ณ , map ๋ฉ”์†Œ๋“œ๋กœ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ˆ˜์ •ํ•ด๋ณด๋ฉด ์ข‹์„ ๋“ฏํ•ด์šฉ
@@ -0,0 +1,16 @@ +.main { + background-color: #fafafa; + + main { + display: flex; + justify-content: center; + align-items: flex-start; + margin: 0px 8px 8px 8px; + + .feeds { + width: 750px; + padding-top: 80px; + padding-bottom: 30px; + } + } +}
Unknown
์ด๋Ÿฐ ์„ ํƒ์ž ํ™œ์šฉ์œผ๋กœ ์Šคํฌ๋กค ๊ฐ์ถ”์‹  ๋ถ€๋ถ„ ์ข‹๋„ค์š”..
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
feedcontainer ์•ˆ feed
@@ -1,7 +1,49 @@ import './Nav.scss'; +import '../../styles/variables.scss'; +import { Link } from 'react-router-dom'; function Nav() { - return <></>; + return ( + <div className="nav"> + <nav className="navbar"> + <div className="navbarLeft1"> + <div className="navbarLeft1Inner"> + <Link to="/" className="navbarItem logoImg"> + <img alt="logoIcon" className="navIcon" src="/images/logo.png" /> + </Link> + <Link to="/" className="navbarItem logoFont"> + Westagram + </Link> + </div> + </div> + <div className="navbarLeft2"> + <div className="searchWrapper navbarItem"> + <img alt="searchIcon" src="/images/search.png" /> + <input placeholder="๊ฒ€์ƒ‰" /> + </div> + </div> + <div className="navbarRight"> + <Link to="/" className="navbarItem"> + <img + alt="exploreIcon" + className="navIcon" + src="/images/explore.png" + /> + </Link> + <Link to="/" className="navbarItem"> + <img alt="heartIcon" className="navIcon" src="/images/heart.png" /> + </Link> + <Link to="/" className="navbarItem"> + <img + alt="profileIcon" + className="navIcon" + src="/images/profile.png" + /> + </Link> + </div> + </nav> + </div> + ); } export default Nav;
JavaScript
๊ณตํ†ต ํŒŒ์ผ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
state๋ผ๋Š” ๋ช…์นญ์ด ๋ฌด์Šจ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š”์ง€ ์•Œ ์ˆ˜ ์—†์Œ. ๋ช…ํ™•ํ•œ ๋ช…์นญ์œผ๋กœ ์ˆ˜์ •
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
disabled, style ๋“ฑ์€ state๋กœ ๋งŒ๋“ค ํ•„์š” ์—†์Œ. [๋ฆฌ์•กํŠธ๋กœ ์‚ฌ๊ณ ํ•˜๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html) ์ฐธ๊ณ  1. ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ props๋ฅผ ํ†ตํ•ด ์ „๋‹ฌ๋ฉ๋‹ˆ๊นŒ? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. 2. ์‹œ๊ฐ„์ด ์ง€๋‚˜๋„ ๋ณ€ํ•˜์ง€ ์•Š๋‚˜์š”? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. 3. ์ปดํฌ๋„ŒํŠธ ์•ˆ์˜ ๋‹ค๋ฅธ state๋‚˜ props๋ฅผ ๊ฐ€์ง€๊ณ  ๊ณ„์‚ฐ ๊ฐ€๋Šฅํ•œ๊ฐ€์š”? ๊ทธ๋ ‡๋‹ค๋ฉด state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
- ๊ธฐ๋Šฅ์„ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์€ ์ข‹์Œ - ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋กœ ์‚ฌ์šฉํ•  ํ•„์š” ์—†์ด, ์กฐ๊ฑด ์ž์ฒด๋กœ boolean์ด ๋  ์ˆ˜ ์žˆ์Œ ```suggestion const checkId = idValue => { return idValue.includes('@'); }; const checkPw = pwValue => { return pwValue.length >= 5; }; ``` - ์ถ”๊ฐ€์ ์œผ๋กœ, ```js const isInputValid = idValue.includes('@') && pwValue.length >= 5 ``` ์ด๋Ÿฐ ์‹์œผ๋กœ ํ•œ๊บผ๋ฒˆ์— ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค์–ด ์ฒ˜๋ฆฌํ•  ์ˆ˜๋„ ์žˆ์Œ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๋ช…์นญ๋งŒ ๋ดค์„ ๋•Œ๋Š” id ๋ถ€๋ถ„๋งŒ ๊ด€๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜์ธ ๊ฒƒ ๊ฐ™์€๋ฐ, ๋™์ž‘์„ ๋ณด๋ฉด ์•„๋‹˜. ์ˆ˜์ •
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น! ```suggestion const { type, value } = event.target; if (type === 'text') { setState(value); } else if (type === 'password') { setPasswordValue(value); } ```
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
JS๋กœ ๊ตฌํ˜„ํ•˜๋˜ ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ ํ•˜์…จ๋Š”๋ฐ, ๊ธฐ์กด state๋กœ ๊ณ„์‚ฐ์ด ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํ•„์š”ํ•œ state
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๊น€ํ˜œ์ง„ ๋ฉ˜ํ† ๋‹˜ ๋ฆฌ๋ทฐ ๋ฐ˜์˜ํ•˜๊ธฐ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
+์‚ผํ•ญ์—ฐ์‚ฐ์ž์˜ ์กฐ๊ฑด์€ ์œ„ ๋ฆฌ๋ทฐ์ฒ˜๋Ÿผ ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜๊ธฐ
@@ -0,0 +1,14 @@ +import './Comment.scss'; + +function Comment({ userName, content }) { + return ( + <div className="comment"> + <p> + <strong className="commentMan">{userName}</strong> + {content} + </p> + </div> + ); +} + +export default Comment;
JavaScript
๋งค๊ฐœ๋ณ€์ˆ˜ ์ž๋ฆฌ์—์„œ ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น ๊ตณ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
- ์žฌํ• ๋‹น๋˜์ง€ ์•Š๋Š” ๋ณ€์ˆ˜๋Š” const๋กœ ์„ ์–ธํ•˜๊ธฐ - ์ด ๋ถ€๋ถ„์€ ๋ณ€์ˆ˜ ์„ ์–ธ๋ณด๋‹จ ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น ์ ์šฉํ•˜๊ธฐ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
- input์˜ value๊ฐ€ ๋“ค์–ด์˜ค๋Š” ๋ถ€๋ถ„์ธ๋ฐ, ์ดˆ๊ธฐ๊ฐ’์ด string์ด ์•„๋‹Œ ๋ฐฐ์—ด์ด ๋“ค์–ด์žˆ์Œ - cmtContents๋ผ๋Š” ๋ณ€์ˆ˜๋ช…๊ณผ ๋ฐฐ์—ด์ธ ์ดˆ๊ธฐ๊ฐ’์˜ ์กฐํ•ฉ์ด ๋ฐฐ์—ด ๋ฐ์ดํ„ฐ๋ฅผ ์—ฐ์ƒ์‹œํ‚ด - ๋ช…ํ™•ํ•˜์ง€๋งŒ ๊ฐ„๊ฒฐํ•œ state๋ช…์œผ๋กœ ์ˆ˜์ •. ex) `comment` / `commentList`
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
ํ•จ์ˆ˜๋ช… ์ˆ˜์ •! - comment๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜ - ์—”ํ„ฐํ‚ค๋ฅผ ์ณค์„ ๋•Œ ์œ„ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰์‹œํ‚ค๋Š” ํ•จ์ˆ˜ ๋กœ ๋ถ„ํ• ํ•˜๋ฉด ์ข‹์„ ๋“ฏ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
๋™์ผํ•œ ์Šคํƒ€์ผ์„ ๊ฐ€์ง€๋Š” ๋ถ€๋ถ„์ธ๋ฐ, one two three ์ด๋Ÿฐ ์‹์œผ๋กœ ๋‚˜ํƒ€๋‚ผ ํ•„์š” ์—†์ด ๋‚ด์šฉ์„ ํฌ๊ด„ํ•˜๋Š” ๋ช…์นญ์˜ ๋™์ผํ•œ className์œผ๋กœ ์‚ฌ์šฉ
@@ -0,0 +1,132 @@ +.feed { + background-color: white; + margin-bottom: 50px; + + .feedTop { + display: flex; + justify-content: space-between; + position: relative; + padding: 10px; + + .feedTopOne { + display: flex; + align-items: center; + + .profileLogo { + display: flex; + align-items: center; + justify-content: center; + height: 35px; + width: 35px; + margin-right: 10px; + color: white; + background-color: black; + border-radius: 50%; + font-size: 7px; + font-weight: bold; + overflow: hidden; // ๋ถ€๋ชจ div๋งŒํผ ์ด๋ฏธ์ง€ ์ž๋ฆ„ + + .profileLogoImg { + width: 100%; + height: 100%; + object-fit: cover; // ๊ฐ€๋กœ, ์„ธ๋กœ ๋น„์œจ์ด ์•ˆ ๋งž์œผ๋ฉด ๋”ฑ ๋งž๊ฒŒ ์•ˆ ์ฐŒ๊ทธ๋Ÿฌ์ง€๊ฒŒ ๋งž์ถฐ์คŒ. + } + } + + .profileNameOne { + margin-bottom: 0px; + font-size: 15px; + font-weight: bold; + } + + .profileNameTwo { + color: #a3a49a; + font-size: 12px; + font-weight: bold; + } + } + + .fa-ellipsis-h { + position: absolute; + right: 20px; + top: 20px; + } + } + + .feedImg { + width: 100%; + height: 500px; + } + + .feedThree { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px; + font-size: 25px; + + .fa-heart, + .fa-comment { + margin-right: 10px; + } + } + + .feedFour { + display: flex; + align-items: center; + padding: 0px 10px 10px 10px; + + .man { + width: 20px; + height: 20px; + margin-right: 10px; + border-radius: 50%; + } // ์œ„ ์ฝ”๋“œ ์ฒ˜๋Ÿผ ํ•˜๋ ค๋ฉด div๋กœ ์ด๋ฏธ์ง€ ํ•œ๋ฒˆ ๋” ๊ฐ์จ์„œ ๊ทธ div์— overflow:hidden ์ฃผ๊ณ  + // imgํŒŒ์ผ์— width: 100%, height: 100%, object-fit: cover์ฃผ๋ฉด ๋จ + + .feedFourWord, + .feedFourWordTwo { + font-weight: bold; + } + } + + .feedFive { + padding: 0px 10px 3px 10px; + + .feedFiveWord { + font-weight: bold; + } + } + + .comment { + padding-top: 5px; + padding-left: 5px; + padding-bottom: 5px; + } + + .postTime { + display: inline-block; + padding: 10px 10px 15px 10px; + color: #9c9c9c; + } + + .commentSection { + position: relative; + + .comment { + width: 100%; + padding: 15px 10px; + border: 1px solid #f3f3f3; + } + + .postButton { + position: absolute; + bottom: 13px; + right: 20px; + color: #c5e1fc; + background-color: white; + border: 1px solid white; + font-size: 15px; + } + } +}
Unknown
- article ํƒœ๊ทธ๊ฐ€ ์•„๋‹ˆ๋ผ feed๋ผ๋Š” className์œผ๋กœ nestingํ•˜๊ธฐ - ์ตœ์ƒ์œ„ div๋ฅผ article๋กœ ๋ฐ”๊พธ๊ณ  1 depth ์ค„์ด๋ฉด ๋  ๋“ฏ
@@ -0,0 +1,40 @@ +package nextstep.security.context; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class SecurityContextHolderFilter implements Filter { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + + try { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) servletRequest); + + if (securityContext != null) { + SecurityContextHolder.setContext(securityContext); + } + + filterChain.doFilter(servletRequest, servletResponse); + + SecurityContext afterSecurityContext = SecurityContextHolder.getContext(); + securityContextRepository.saveContext(afterSecurityContext, (HttpServletRequest) servletRequest, + (HttpServletResponse) servletResponse); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
`SecurityContextHolderFilter`๋Š” ๊ฐ€์žฅ ๋จผ์ € SecurityContext๋ฅผ ๊ด€๋ฆฌํ•˜๋ฉฐ, ๋งˆ์ง€๋ง‰์œผ๋กœ SecurityContext๋ฅผ ๊ด€๋ฆฌํ•ด์ฃผ๋Š” ์—ญํ• ์„ ํ•ด์š”. ์œ„์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด `SecurityContext.clearContext`๊ฐ€ ์‹คํ–‰์ด ์–ด๋ ค์›Œ๋ณด์—ฌ์š”.
@@ -0,0 +1,40 @@ +package nextstep.security.context; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class SecurityContextHolderFilter implements Filter { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + + try { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) servletRequest); + + if (securityContext != null) { + SecurityContextHolder.setContext(securityContext); + } + + filterChain.doFilter(servletRequest, servletResponse); + + SecurityContext afterSecurityContext = SecurityContextHolder.getContext(); + securityContextRepository.saveContext(afterSecurityContext, (HttpServletRequest) servletRequest, + (HttpServletResponse) servletResponse); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
053f96ece76768a3b187188eaf41110f9593b65e `finally`๋ฅผ ํ†ตํ•ด ์ตœ์ข…์ ์œผ๋กœ `clear`๋ฅผ ํ•  ์ˆ˜ ์žˆ๋Š” ๊ตฌ์กฐ๋กœ ๋ณ€๊ฒฝ ํ•ด ๋ณด์•˜์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package nextstep.security.filter.converter; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; + +import java.util.Map; + +public class LoginFormAuthenticationConverter implements AuthenticationConverter { + + @Override + public Authentication convert(final HttpServletRequest request) { + final Map<String, String[]> parameterMap = request.getParameterMap(); + + String username; + String password; + + try { + username = parameterMap.get("username")[0]; + password = parameterMap.get("password")[0]; + } catch (RuntimeException e) { + throw new IllegalArgumentException(e); + } + + return new UsernamePasswordAuthenticationToken(username, password); + } +}
Java
```suggestion try { String username = parameterMap.get("username")[0]; String password = parameterMap.get("password")[0]; return new UsernamePasswordAuthenticationToken(username, password); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } ``` ๊ฐ€ ์กฐ๊ธˆ ๋” ๋ณ€์ˆ˜๋ฅผ ๋ถˆ๋ณ€ํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๋Š” ์•ˆ์ •์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š” :)
@@ -0,0 +1,33 @@ +package nextstep.security.filter.converter; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.app.util.Base64Convertor; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; + +public class BasicAuthenticationConverter implements AuthenticationConverter { + + private static final String AUTHORIZATION = "Authorization"; + + @Override + public Authentication convert(HttpServletRequest request) { + final String authorization = request.getHeader(AUTHORIZATION); + + final String username; + final String password; + + try { + final String credentials = authorization.split("Basic ")[1]; + final String decodedString = Base64Convertor.decode(credentials); + + final String[] usernameAndPassword = decodedString.split(":"); + + username = usernameAndPassword[0]; + password = usernameAndPassword[1]; + } catch (RuntimeException e) { + throw new IllegalArgumentException(); + } + + return new UsernamePasswordAuthenticationToken(username, password); + } +}
Java
```suggestion final String username = usernameAndPassword[0]; final String password = usernameAndPassword[1]; return new UsernamePasswordAuthenticationToken(username, password); } catch (RuntimeException e) { throw new IllegalArgumentException(); } ``` ์œ„์™€ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,33 @@ +package nextstep.security.filter.converter; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.app.util.Base64Convertor; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; + +public class BasicAuthenticationConverter implements AuthenticationConverter { + + private static final String AUTHORIZATION = "Authorization"; + + @Override + public Authentication convert(HttpServletRequest request) { + final String authorization = request.getHeader(AUTHORIZATION); + + final String username; + final String password; + + try { + final String credentials = authorization.split("Basic ")[1]; + final String decodedString = Base64Convertor.decode(credentials); + + final String[] usernameAndPassword = decodedString.split(":"); + + username = usernameAndPassword[0]; + password = usernameAndPassword[1]; + } catch (RuntimeException e) { + throw new IllegalArgumentException(); + } + + return new UsernamePasswordAuthenticationToken(username, password); + } +}
Java
`LoginFormAuthenticationConverter`์™€ ` BasicAuthenticationConveter` ๋ชจ๋‘ ์˜ˆ์™ธ๊ฐ€ ๋‚˜๋Š” ์ƒํ™ฉ์„ ์ถ”์ถœํ•˜๊ธฐ ์ „์— ์ฒ˜๋ฆฌํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ์˜ˆ๋ฅผ๋“ค๋ฉด ํ˜„์žฌ ์ƒํ™ฉ์—์„œ๋Š” `Basic` split ํ•˜๊ณ  ๋‚ด๋ถ€์ ์œผ๋กœ ์•Œ์•„์„œ ์˜ˆ์™ธ๊ฐ€ ํ„ฐ์ง€๊ธธ ๊ธฐ๋Œ€ํ•˜๊ธฐ๋ณด๋‹ค๋Š”, ํ—ค๋”์˜ ๊ฐ’ ์•ˆ์— `Basic`์œผ๋กœ ํŒจํ„ด์ด ์—†์œผ๋ฉด ์‹คํŒจ๋กœ fast fail ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๊ฒ ๋„ค์š”.
@@ -0,0 +1,33 @@ +package nextstep.security.filter.converter; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.app.util.Base64Convertor; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; + +public class BasicAuthenticationConverter implements AuthenticationConverter { + + private static final String AUTHORIZATION = "Authorization"; + + @Override + public Authentication convert(HttpServletRequest request) { + final String authorization = request.getHeader(AUTHORIZATION); + + final String username; + final String password; + + try { + final String credentials = authorization.split("Basic ")[1]; + final String decodedString = Base64Convertor.decode(credentials); + + final String[] usernameAndPassword = decodedString.split(":"); + + username = usernameAndPassword[0]; + password = usernameAndPassword[1]; + } catch (RuntimeException e) { + throw new IllegalArgumentException(); + } + + return new UsernamePasswordAuthenticationToken(username, password); + } +}
Java
ํ‘œ์ค€์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์ง€๋งŒ `convert`๋กœ์ง์— ๋“ค์–ด์˜จ ์ด์ƒ ์ธ์ฆ์ด ์ž˜๋ชป๋˜์—ˆ๋‹ค๋Š” ๊ฒƒ์„ ๋ช…์‹œํ•˜๊ธฐ ์œ„ํ•ด์„œ `AuthenticationException`๋ฅผ ๋˜์ ธ์ฃผ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ์‹ค์ œ๋กœ๋Š” `Basic`์Šคํ‚ด์ด ์ž˜๋ชป๋˜์—ˆ๋˜ ๊ฒƒ ๊ฐ™์€ ์ผ€์ด์Šค๋“ค์„ ์„ธ๋ถ„ํ™”ํ•˜์—ฌ `BadCredentialsException`๋ฅผ ๋‚ ๋ฆฌ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,89 @@ +package nextstep.security.filter; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.authentication.Authentication; + +import java.io.IOException; +import nextstep.security.authentication.AuthenticationException; +import nextstep.security.filter.converter.AuthenticationConverter; + +public class BasicAuthenticationFilter implements Filter { + + public static final String AUTHORIZATION = "Authorization"; + private static final String BASIC_AUTH_PREFIX = "Basic "; + + private final AuthenticationManager authenticationManager; + private final AuthenticationConverter authenticationConverter; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationConverter authenticationConverter) { + this.authenticationManager = authenticationManager; + this.authenticationConverter = authenticationConverter; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (isAuthenticated()) { + chain.doFilter(request, response); + return; + } + + final String authorization = ((HttpServletRequest) request).getHeader(AUTHORIZATION); + + if (!isBasicAuthentication(authorization)) { + chain.doFilter(request, response); + return; + } + + try { + final Authentication authentication = authenticationConverter.convert((HttpServletRequest) request); + + final Authentication authenticatedAuthentication = authenticationManager.authenticate(authentication); + + if (!authenticatedAuthentication.isAuthenticated()) { + throw new AuthenticationException(); + } + + saveAuthentication(authenticatedAuthentication); + } catch (IllegalArgumentException | AuthenticationException e) { + SecurityContextHolder.clearContext(); + ((HttpServletResponse) response).setStatus(401); + return; + } + + chain.doFilter(request, response); + } + + /** + * SecurityContext์— ์ •๋ณด๊ฐ€ ์œ ํšจํ•œ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. + */ + private boolean isAuthenticated() { + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + return authentication != null && authentication.isAuthenticated(); + } + + /** + * Basic ํ˜•์‹์˜ ์ธ์ฆ ์ •๋ณด์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. + */ + private boolean isBasicAuthentication(final String authorization) { + return authorization != null && authorization.startsWith(BASIC_AUTH_PREFIX); + } + + /** + * ์ธ์ฆ ๋œ authorization ๊ฐ์ฒด๋ฅผ, context์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. + */ + private void saveAuthentication(final Authentication authentication) { + SecurityContext securityContext = SecurityContextHolder.getContext(); + securityContext.setAuthentication(authentication); + SecurityContextHolder.setContext(securityContext); + } +}
Java
`Converter`๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์…จ์œผ๋‹ˆ spring security ์ด์•ผ๊ธฐ๋ฅผ ํ•ด๋ณด๋ฉด `BasicAuthenticationConverter`์—์„œ ์ด๋ฏธ header์— ๋Œ€ํ•œ ๊ฒ€์ฆ์„ ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— `BasicAuthenticationFilter`์—์„œ๋Š” ์ด๋Ÿฐ ๊ฒ€์ฆ์ด ๋”ฐ๋กœ ํ•„์š”ํ•˜์ง„ ์•Š์•„์š”. `AUTHORIZATION`๋ฅผ ์ด ํด๋ž˜์Šค๊ฐ€ ๋“ค๊ณ  ์žˆ์„ ํ•„์š”๊ฐ€ ์—†๋Š”๊ฑฐ์ฃ . ๊ทธ๋ž˜์„œ ์‹ค์ œ ๊ตฌํ˜„์ฒด๋ฅผ ๋ณด๋ฉด ๋ฐ”๋กœ converter๋กœ ๋‚ด๋ณด๋‚ด๊ณ , converter๋Š” header์— Authorization์ด ์—†์œผ๋ฉด null์„ ๋‚ด๋ณด๋‚ด `Filter`๋Š” null์„ ๋ฐ›์œผ๋ฉด dofilter-returnํ•˜๋Š” ํ˜•ํƒœ๋กœ ๊ตฌ์„ฑ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +package nextstep.security.context; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class SecurityContextHolderFilter implements Filter { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + + try { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) servletRequest); + + if (securityContext != null) { + SecurityContextHolder.setContext(securityContext); + } + + filterChain.doFilter(servletRequest, servletResponse); + + SecurityContext afterSecurityContext = SecurityContextHolder.getContext(); + securityContextRepository.saveContext(afterSecurityContext, (HttpServletRequest) servletRequest, + (HttpServletResponse) servletResponse); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
`loadContext`๋Š” try-finally ์•ˆ์— ๋“ค์–ด๊ฐˆ ํ•„์š”๋Š” ์—†์–ด์š”. ๋‹จ์ˆœํžˆ load๋งŒ ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— load์—์„œ ์˜ˆ์™ธ๊ฐ€ ํ„ฐ์ ธ๋„ Context๋ฅผ ์ดˆ๊ธฐํ™”ํ•  ๊ฒƒ์ด ์—†์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,50 @@ +package nextstep.app.config; + +import java.util.List; +import nextstep.app.MemberService; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.filter.BasicAuthenticationFilter; +import nextstep.security.authentication.DaoAuthenticationProvider; +import nextstep.security.filter.DefaultSecurityFilterChain; +import nextstep.security.filter.FilterChainProxy; +import nextstep.security.filter.LoginFormAuthenticationFilter; +import nextstep.security.authentication.ProviderManager; +import nextstep.security.filter.SecurityFilterChain; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolderFilter; +import nextstep.security.filter.converter.BasicAuthenticationConverter; +import nextstep.security.filter.converter.LoginFormAuthenticationConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +@Configuration +class FilterConfig { + + private final MemberService memberService; + + public FilterConfig(MemberService memberService) { + this.memberService = memberService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(new FilterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of( + new SecurityContextHolderFilter(new HttpSessionSecurityContextRepository()) + , new BasicAuthenticationFilter(authenticationManager(), new BasicAuthenticationConverter()) + , new LoginFormAuthenticationFilter(authenticationManager(), new LoginFormAuthenticationConverter()) + ) + ); + } + + @Bean + public AuthenticationManager authenticationManager() { + return new ProviderManager(new DaoAuthenticationProvider(memberService)); + } +}
Java
`authenticationManager()`๋ฅผ ํ˜ธ์ถœํ•ด์„œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ๋ณด๋‹ค๋Š” ๋นˆ์„ ๋“ฑ๋กํ•ด๋‘์—ˆ๋‹ค๋ฉด ๋“ฑ๋ก๋œ ๋นˆ์„ ์‚ฌ์šฉํ•˜๋„๋ก ๋ณ€๊ฒฝํ•ด์ฃผ์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,27 @@ +package nextstep.security.context; + +public class SecurityContextHolder { + + private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>(); + + public static SecurityContext getContext() { + SecurityContext context = contextHolder.get(); + if (context == null) { + context = createEmptyContext(); + contextHolder.set(context); + } + return context; + } + + public static SecurityContext createEmptyContext() { + return new SecurityContextImpl(); + } + + public static void setContext(SecurityContext context) { + contextHolder.set(context); + } + + public static void clearContext() { + contextHolder.remove(); + } +}
Java
`SecurityContextHolder`๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋Š” Filter๋“ค์ด ๋งŽ์€๋ฐ ์‹ค์ œ๋กœ ์ด๋ ‡๊ฒŒ ๊ตฌ์„ฑํ•˜๊ฒŒ ๋˜๋Š” ๊ฒฝ์šฐ ๊ตฌํ˜„์ฒด์— ์˜์กดํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ…Œ์ŠคํŠธํ•˜๊ธฐ ํž˜๋“  ๊ตฌ์กฐ๊ฐ€ ๋  ์ˆ˜ ์žˆ์–ด์š”. ํ”„๋ ˆ์ž„์›Œํฌ๋“ค์—์„œ๋Š” testableํ•œ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ์ด ํ™•์žฅ์„ฑ ์žˆ๊ณ , ๋ณธ์ธ๋“ค์˜ ๋ณต์žกํ•œ ์ฝ”๋“œ๋“ค์„ ์•ˆ์ •์ ์œผ๋กœ ํ…Œ์ŠคํŠธ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๋Œ€๋ถ€๋ถ„์˜ ์ฝ”๋“œ๋ฅผ ์ถ”์ƒํ™”ํ•ด๋‘๋Š” ํŽธ์ธ๋ฐ์š”. spring security์—์„œ๋„ ์ด๋ฅผ ์œ„ํ•ด์„œ `SecurityContextHolder`๋ฅผ ๋ฐ”๋กœ ์“ฐ๊ธฐ๋ณด๋‹ค๋Š” ํ•œ๋ฒˆ ๋” ๋ž˜ํ•‘ํ•œ ์ถ”์ƒํ™” ํด๋ž˜์Šค๋ฅผ ๋‘๊ณ  ์‚ฌ์šฉํ•˜๋Š” ์  ์ฐธ๊ณ ํ•˜์—ฌ ๋„˜์–ด๊ฐ€์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/core/context/SecurityContextHolderStrategy.java
@@ -0,0 +1,36 @@ +package com.doubleowner.revibe.global.common.service; + +import com.doubleowner.revibe.global.exception.CommonException; +import com.doubleowner.revibe.global.exception.errorCode.ErrorCode; +import com.doubleowner.revibe.global.util.S3Uploader; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@Service +@RequiredArgsConstructor +public class ImageService { + private final S3Uploader s3Uploader; + + public String UploadImage(String image, MultipartFile file) { + try { + if (image != null) { + s3Uploader.deleteImage(image); + } + return s3Uploader.upload(file); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); + } + } + + public void deleteImage(String image) { + try { + s3Uploader.deleteImage(image); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_DELETE_IMAGE); + } + } + +}
Java
_:hammer_and_wrench: Refactor suggestion_ **ํŒŒ์ผ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค** `file` ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋Œ€ํ•œ null ์ฒดํฌ์™€ ํŒŒ์ผ ํฌ๊ธฐ, ํƒ€์ž… ๋“ฑ์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๊ฐ€ ๋ˆ„๋ฝ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ž…๋ ฅ์œผ๋กœ ์ธํ•œ ์˜ˆ์™ธ๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ๊ฒ€์ฆ ๋กœ์ง์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒ€์ฆ ๋กœ์ง ์ถ”๊ฐ€๋ฅผ ์ œ์•ˆํ•ฉ๋‹ˆ๋‹ค: ```diff public String UploadImage(String image, MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new CommonException(ErrorCode.INVALID_FILE); + } + validateFileSize(file); + validateFileType(file); try { ``` ์ถ”๊ฐ€๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒ€์ฆ ๋ฉ”์„œ๋“œ ๊ตฌํ˜„์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค: ```java private void validateFileSize(MultipartFile file) { long maxSize = 5 * 1024 * 1024; // 5MB if (file.getSize() > maxSize) { throw new CommonException(ErrorCode.FILE_TOO_LARGE); } } private void validateFileType(MultipartFile file) { String contentType = file.getContentType(); if (contentType == null || !contentType.startsWith("image/")) { throw new CommonException(ErrorCode.INVALID_FILE_TYPE); } } ``` <!-- This is an auto-generated comment by CodeRabbit -->
@@ -0,0 +1,36 @@ +package com.doubleowner.revibe.global.common.service; + +import com.doubleowner.revibe.global.exception.CommonException; +import com.doubleowner.revibe.global.exception.errorCode.ErrorCode; +import com.doubleowner.revibe.global.util.S3Uploader; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@Service +@RequiredArgsConstructor +public class ImageService { + private final S3Uploader s3Uploader; + + public String UploadImage(String image, MultipartFile file) { + try { + if (image != null) { + s3Uploader.deleteImage(image); + } + return s3Uploader.upload(file); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_UPLOAD_IMAGE); + } + } + + public void deleteImage(String image) { + try { + s3Uploader.deleteImage(image); + } catch (IOException e) { + throw new CommonException(ErrorCode.FAILED_DELETE_IMAGE); + } + } + +}
Java
_:hammer_and_wrench: Refactor suggestion_ **๋ฉ”์„œ๋“œ ์ด๋ฆ„์ด Java ๋„ค์ด๋ฐ ์ปจ๋ฒค์…˜์„ ์œ„๋ฐ˜ํ•ฉ๋‹ˆ๋‹ค** `UploadImage` ๋ฉ”์„œ๋“œ ์ด๋ฆ„์ด ์นด๋ฉœ ์ผ€์ด์Šค ๊ทœ์น™์„ ๋”ฐ๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. Java ๋ฉ”์„œ๋“œ ์ด๋ฆ„์€ ์†Œ๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•˜๋Š” ๊ฒƒ์„ ์ œ์•ˆํ•ฉ๋‹ˆ๋‹ค: ```diff - public String UploadImage(String image, MultipartFile file) { + public String uploadImage(String image, MultipartFile file) { ``` <!-- suggestion_start --> <details> <summary>๐Ÿ“ Committable suggestion</summary> > โ€ผ๏ธ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. `````suggestion public String uploadImage(String image, MultipartFile file) { ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->