-
Notifications
You must be signed in to change notification settings - Fork 90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[유안] 3단계 - HTTP 웹 서버 구현 미션 제출합니다. #205
Open
KimSeongGyu1
wants to merge
8
commits into
woowacourse:kimseonggyu1
Choose a base branch
from
KimSeongGyu1:step_3
base: kimseonggyu1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
eadf898
refactor: 로그 출력 방식 변경
ddaaac 02a3382
docs: 3단계 요구사항 작성
ddaaac 16db5f2
feat: 로그인 기능 구현
ddaaac e1ed618
feat: 동적으로 html을 만들어주는 객체 구현
ddaaac e0c4614
feat: AuthFilter 구현
ddaaac 9ec52d9
feat: 유저 리스트에 대한 request behavior 구현
ddaaac a1b4a7e
refactor: 분기문 리팩토링
ddaaac 8b3307c
feat: HttpSession Api 일부 구현
ddaaac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package http.session; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.UUID; | ||
import java.util.stream.Collectors; | ||
|
||
public class HttpSession { | ||
private UUID id = UUID.randomUUID(); | ||
private Map<String, Object> attributes = new HashMap<>(); | ||
|
||
public void setAttribute(String name, Object value) { | ||
attributes.put(name, value); | ||
} | ||
|
||
public Object getAttribute(String name) { | ||
return attributes.get(name); | ||
} | ||
|
||
public void removeAttribute(String name) { | ||
attributes.remove(name); | ||
} | ||
|
||
public void invalidate() { | ||
attributes.clear(); | ||
} | ||
|
||
public UUID getId() { | ||
return id; | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
String sessionId = String.format("jsessionid=%s; ", id.toString()); | ||
String attributes = this.attributes.entrySet() | ||
.stream() | ||
.filter(this::exclude) | ||
.map(this::parseAttribute) | ||
.collect(Collectors.joining("; ")); | ||
return sessionId + attributes; | ||
} | ||
|
||
private boolean exclude(Map.Entry<String, Object> entry) { | ||
return !entry.getKey().equals("userId") && !entry.getValue().equals(false); | ||
} | ||
|
||
private String parseAttribute(Map.Entry<String, Object> entry) { | ||
if (entry.getValue().equals(true)) { | ||
return entry.getKey(); | ||
} | ||
return String.format("%s=%s", entry.getKey(), entry.getValue().toString()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package http.session; | ||
|
||
import java.util.*; | ||
import java.util.stream.Stream; | ||
|
||
public class HttpSessionStorage { | ||
private static Map<UUID, HttpSession> sessions = new HashMap<>(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sessions 에는 여러 Request Thread가 동시에 접근 가능하기 때문에 |
||
|
||
public static HttpSession generate(String userId) { | ||
HttpSession httpSession = new HttpSession(); | ||
httpSession.setAttribute("userId", userId); | ||
sessions.put(httpSession.getId(), httpSession); | ||
return httpSession; | ||
} | ||
|
||
public static boolean isValidSession(String cookie) { | ||
String[] attributes = cookie.split("; "); | ||
Optional<String> jsessionid = Stream.of(attributes) | ||
.filter(it -> it.startsWith("jsessionid")) | ||
.map(it -> it.substring("jsessionid=".length())) | ||
.findAny(); | ||
|
||
try { | ||
return sessions.containsKey(UUID.fromString(jsessionid.get())); | ||
} catch (IllegalArgumentException | NoSuchElementException | NullPointerException e) { | ||
return false; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package implementedbehavior; | ||
|
||
import db.DataBase; | ||
import http.request.RequestEntity; | ||
import http.response.HttpStatus; | ||
import http.response.ResponseEntity; | ||
import webserver.requestmapping.DynamicHtmlGenerator; | ||
import webserver.requestmapping.behavior.RequestBehavior; | ||
|
||
public class UserListBehavior implements RequestBehavior { | ||
@Override | ||
public void behave(RequestEntity requestEntity, ResponseEntity responseEntity) { | ||
responseEntity.status(HttpStatus.OK) | ||
.body(DynamicHtmlGenerator.applyHandlebar("user/list", DataBase.findAll())); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package implementedbehavior; | ||
|
||
import db.DataBase; | ||
import http.request.Params; | ||
import http.request.RequestEntity; | ||
import http.response.HttpStatus; | ||
import http.response.ResponseEntity; | ||
import http.session.HttpSession; | ||
import http.session.HttpSessionStorage; | ||
import model.User; | ||
import webserver.requestmapping.behavior.RequestBehavior; | ||
|
||
import java.util.Objects; | ||
|
||
public class UserLoginBehavior implements RequestBehavior { | ||
@Override | ||
public void behave(RequestEntity requestEntity, ResponseEntity responseEntity) { | ||
Params userInfo = Params.from(requestEntity.getHttpBody().getContent()); | ||
if (isValid(userInfo)) { | ||
HttpSession session = HttpSessionStorage.generate(userInfo.findValueBy("userId")); | ||
responseEntity.status(HttpStatus.FOUND) | ||
.addHeader("Location", "/index.html") | ||
.addHeader("Set-Cookie", session.toString()); | ||
} else { | ||
responseEntity.status(HttpStatus.FOUND) | ||
.addHeader("Location", "/user/login_failed.html"); | ||
} | ||
} | ||
|
||
private boolean isValid(Params userInfo) { | ||
String userId = userInfo.findValueBy("userId"); | ||
String password = userInfo.findValueBy("password"); | ||
User user = DataBase.findUserById(userId); | ||
return Objects.nonNull(user) && user.hasPasswordOf(password); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package implementedfilter; | ||
|
||
import http.request.RequestEntity; | ||
import http.response.HttpStatus; | ||
import http.response.ResponseEntity; | ||
import http.session.HttpSessionStorage; | ||
import webserver.filter.Filter; | ||
|
||
import java.util.Arrays; | ||
import java.util.List; | ||
|
||
public class AuthFilter implements Filter { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. filter로 처리한 점 👏👏👏👏👏 |
||
private static final List<String> PATH_PATTERN = Arrays.asList( | ||
"/user/list" | ||
); | ||
|
||
@Override | ||
public boolean doFilter(RequestEntity requestEntity, ResponseEntity responseEntity) { | ||
String path = requestEntity.getHttpUrl().getPath(); | ||
String cookie = requestEntity.getHttpHeader().findOrEmpty("Cookie"); | ||
if (PATH_PATTERN.contains(path) && isNotAuthorized(cookie)) { | ||
responseEntity.status(HttpStatus.FOUND).addHeader("Location", "/user/login.html"); | ||
return false; | ||
} | ||
return true; | ||
} | ||
|
||
private boolean isNotAuthorized(String cookie) { | ||
return !HttpSessionStorage.isValidSession(cookie); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
src/main/java/webserver/requestmapping/DynamicHtmlGenerator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package webserver.requestmapping; | ||
|
||
import com.github.jknack.handlebars.Handlebars; | ||
import com.github.jknack.handlebars.Template; | ||
import com.github.jknack.handlebars.io.ClassPathTemplateLoader; | ||
import com.github.jknack.handlebars.io.TemplateLoader; | ||
|
||
import java.io.IOException; | ||
|
||
public class DynamicHtmlGenerator { | ||
public static String applyHandlebar(String path, Object model) { | ||
TemplateLoader loader = new ClassPathTemplateLoader(); | ||
loader.setPrefix("/templates"); | ||
loader.setSuffix(".html"); | ||
Handlebars handlebars = new Handlebars(loader); | ||
|
||
try { | ||
Template template = handlebars.compile(path); | ||
return template.apply(model); | ||
} catch (IOException e) { | ||
throw new RuntimeException(); | ||
} | ||
} | ||
} |
14 changes: 9 additions & 5 deletions
14
src/main/java/webserver/requestmapping/RequestMappingStorage.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
session의 invalidate 메소드가 호출된 후에는 해당 세션은 사용하지 못하는 것으로 알고 있어요.
아래 링크 한번 읽어보시고, 한번 검색해보시면 좋을 것 같아요 :)
https://love2taeyeon.tistory.com/entry/invalidate%EC%9D%80-%EC%84%B8%EC%85%98%EC%9D%84-%EC%86%8C%EB%A9%B8%EC%8B%9C%ED%82%A4%EB%8A%94-%EA%B2%83%EC%9D%B4-%EC%95%84%EB%8B%88%EB%9D%BC-%EB%AC%B4%ED%9A%A8%ED%99%94-%EC%8B%9C%ED%82%AC%EB%BF%90%EC%9D%B4%EB%8B%A4