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>
+ ์ธ
+ <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>
+ ์ธ
+ <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>
+ ์ธ
+ <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>
+ ์ธ
+ <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 --> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.