Skip to content
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

[톰캣 구현하기 1 & 2단계] 제이미(임정수) 미션 제출합니다 #353

Merged
merged 53 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
46f891f
feat: resource 디렉터리에 있는 파일의 경로 찾기 추가
JJ503 Sep 2, 2023
ca33494
feat: resource 디렉터리에 있는 파일의 경로 찾기 추가
JJ503 Sep 2, 2023
e0c536e
feat: I/O stream을 통한 파일의 내용 읽기 추가
JJ503 Sep 2, 2023
56155b6
feat: IOStream 테스트 문제 해결
JJ503 Sep 3, 2023
53aa530
feat: GET /index.html 응답하기 추가
JJ503 Sep 4, 2023
4f92442
feat: css 지원하기 추가
JJ503 Sep 4, 2023
015661f
feat: Query String 파싱을 통한 로그인 페이지 접속 추가
JJ503 Sep 4, 2023
287756a
test: 1단계 테스트 추가
JJ503 Sep 4, 2023
ab6fff9
feat: 로그인 여부에 따른 페이지 이동 추가
JJ503 Sep 4, 2023
4f348df
feat: POST 방식으로 회원가입하기 추가
JJ503 Sep 4, 2023
22f284a
refactor: 로그인을 POST 방식으로 변경
JJ503 Sep 4, 2023
b79e696
feat: Cookie 설정 및 Cookie를 통한 로그인 추가
JJ503 Sep 4, 2023
a989302
feat: Session 구현하기 추가
JJ503 Sep 4, 2023
b3d3c92
style: 사용하지 않는 import문 제거
JJ503 Sep 4, 2023
a223e8c
test: 조건 변경으로 인한 테스트 제거
JJ503 Sep 4, 2023
7b719fe
style: 필요없는 log 제거
JJ503 Sep 4, 2023
c0298e3
refactor: 코드 중복 해결
JJ503 Sep 4, 2023
6dee7cd
init: 처음 상태로 초기화
JJ503 Sep 6, 2023
70f6ca8
feat: http 메서드 추가
JJ503 Sep 6, 2023
12368be
feat: http 버전 추가
JJ503 Sep 6, 2023
e2d7046
feat: request의 start line 추가
JJ503 Sep 6, 2023
454f3be
refactor: 상수 접근 제어자 변경
JJ503 Sep 6, 2023
5477e77
feat: header, headers 추가
JJ503 Sep 6, 2023
ca69602
feat: request 추가
JJ503 Sep 6, 2023
ee72d84
rename: HttpVersion 패키지 변경
JJ503 Sep 6, 2023
b9bf80e
feat: 상태 코드 추가
JJ503 Sep 6, 2023
e7435cd
feat: StartLine 추가
JJ503 Sep 6, 2023
6517976
feat: 응답 header, headers 추가
JJ503 Sep 6, 2023
bd9456a
feat: Response 추가
JJ503 Sep 6, 2023
84ca3a1
feat: Body 추가
JJ503 Sep 6, 2023
953cabf
feat: ContentType 추가
JJ503 Sep 6, 2023
133f9eb
feat: Response 추가
JJ503 Sep 7, 2023
bbf82ca
refactor: Request의 header가 빈 값 전까지라는 조건 추가
JJ503 Sep 7, 2023
6627de9
refactor: response에 대한 값 설정에 대한 로직 분리
JJ503 Sep 7, 2023
5e94550
refactor: 개행 수정 및 상수화
JJ503 Sep 7, 2023
633988d
feat: 파일 요청에 대한 응답 추가
JJ503 Sep 7, 2023
9da3687
fix: enum 이름이 아닌 값과 비교하는 문제 해결
JJ503 Sep 7, 2023
9e59746
refactor: try-catch 문 제거
JJ503 Sep 7, 2023
1d8c741
feat: QueryString 추가
JJ503 Sep 7, 2023
50d5ba1
refactor: 변수 및 상수 네이밍을 명확하게 수정
JJ503 Sep 7, 2023
d516bf2
refactor: queryString을 Option 타입으로 변경
JJ503 Sep 7, 2023
28bc767
feat: 로그인 기능 추가
JJ503 Sep 7, 2023
3f2d528
feat: 로그인 성공 여부에 따른 처리 추가
JJ503 Sep 7, 2023
667258a
feat: 요청 body 추가
JJ503 Sep 7, 2023
e0d1b37
feat: POST 로그인 요청에 대한 처리 추가
JJ503 Sep 7, 2023
56707b1
feat: POST 로그인 요청에 대한 처리 추가
JJ503 Sep 7, 2023
160ee64
feat: 가입에 대한 GET 요청 처리 추가
JJ503 Sep 7, 2023
8d9f164
feat: 가입에 대한 POST 요청 처리 추가
JJ503 Sep 7, 2023
43e069a
feat: 로그인 시 쿠키 세팅 추가
JJ503 Sep 7, 2023
357a846
feat: 로그인 페이지 접속 시 JSESSION 쿠키 확인 로직 추가
JJ503 Sep 7, 2023
e3b7d3b
feat: JSESSION 쿠키와 Session을 통한 자동 로그인 기능 추가
JJ503 Sep 7, 2023
e5d36ec
refactor: session의 타입을 ConcurrentHashMap로 변경
JJ503 Sep 7, 2023
336ca0e
feat: 인메모리 db에 id 자동 증가 기능 추가
JJ503 Sep 7, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: Cookie 설정 및 Cookie를 통한 로그인 추가
  • Loading branch information
JJ503 committed Sep 4, 2023
commit b79e696f91205357fcde288476f3a76182f1a8fb
63 changes: 56 additions & 7 deletions tomcat/src/main/java/org/apache/coyote/http11/Http11Processor.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import static java.util.stream.Collectors.toMap;

Expand Down Expand Up @@ -53,7 +55,7 @@ public void process(final Socket connection) {
log.info("uri : {}", uri);

if ("GET".equals(method)) {
final var response = getResponse(uri);
final var response = getResponse(bufferedReader, uri);

outputStream.write(response.getBytes());
outputStream.flush();
Expand Down Expand Up @@ -125,10 +127,13 @@ private Response getPostResponse(final BufferedReader bufferedReader, String req

private Response loginSuccess(final User user) {
log.info("User{id={}, account={}, email={}, pasword={}", user.getId(), user.getAccount(), user.getEmail(), user.getPassword());
return new Response(HttpStatus.FOUND, "/index.html");
final var uuid = UUID.randomUUID();
final Map<String, String> cookie = new HashMap<>();
cookie.put("JSESSIONID", uuid.toString());
return new Response(HttpStatus.FOUND, "/index.html", cookie);
}

private String getResponse(final String uri) throws IOException {
private String getResponse(final BufferedReader bufferedReader, final String uri) throws IOException {
if ("/".equals(uri)) {
final var content = "Hello world!";
return String.join("\r\n",
Expand All @@ -139,29 +144,73 @@ private String getResponse(final String uri) throws IOException {
content);
}

final var responseBody = getResponseBody(uri);
final var responseBody = getResponseBody(bufferedReader, uri);

return getContent(uri, responseBody);
}

private String getContent(final String uri, final Response responseBody) throws IOException {
if (responseBody.getCookies().isEmpty()) {
final URL resource = ClassLoader.getSystemClassLoader().getResource("static/" + responseBody.getContent());
final File file = new File(URLDecoder.decode(Objects.requireNonNull(resource)
.getPath(), StandardCharsets.UTF_8));
final String content = new String(Files.readAllBytes(file.toPath()));

return String.join("\r\n",
"HTTP/1.1 " + responseBody.getHttpStatus().getCode() + " " + responseBody.getHttpStatus().name() + " ",
getContentType(uri),
getContentLength(content),
"",
content);
}

return getContentWithCookie(uri, responseBody);
}

private String getContentWithCookie(final String uri, final Response responseBody) throws IOException {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

헤더에 쿠키, content type, content length 말고 다른 정보도 추가된다면 어떻게 될까요? 그때마다 메서드를 따로따로 만들어야 한다면 불편할 것 같습니다.

final URL resource = ClassLoader.getSystemClassLoader().getResource("static/" + responseBody.getContent());
final File file = new File(URLDecoder.decode(Objects.requireNonNull(resource).getPath(), StandardCharsets.UTF_8));
final File file = new File(URLDecoder.decode(Objects.requireNonNull(resource)
.getPath(), StandardCharsets.UTF_8));
final String content = new String(Files.readAllBytes(file.toPath()));

return String.join("\r\n",
final String test = String.join("\r\n",
"HTTP/1.1 " + responseBody.getHttpStatus().getCode() + " " + responseBody.getHttpStatus().name() + " ",
getCookies(responseBody.getCookies()),
getContentType(uri),
getContentLength(content),
"",
content);
System.out.println(test);
return test;
}

private Response getResponseBody(final String uri) {
private String getCookies(final Map<String, String> cookies) {
if (cookies.isEmpty()) {
return null;
}

return "Set-Cookie: JSESSIONID=" + cookies.get("JSESSIONID");
}

private Response getResponseBody(final BufferedReader bufferedReader, final String uri) throws IOException {
if ("/register".equals(uri)) {
return new Response(HttpStatus.OK, "register.html");
}
if ("/login".equals(uri)) {
var request = bufferedReader.readLine();
while (request != null && !"".equals(request)) {
if (request.contains("Cookie")) {
request = request.replaceAll(" ", "");
final var cookie = request.split(":")[1];
final Map<String, String> cookies = Arrays.stream(cookie.split(","))
.map(value -> value.split("="))
.collect(toMap(key -> key[0], value -> value[1]));
if (cookies.containsKey("JSESSIONID")) {
return new Response(HttpStatus.OK, "index.html");
}
}
request = bufferedReader.readLine();
}
return new Response(HttpStatus.OK, "login.html");
}

Expand Down
15 changes: 15 additions & 0 deletions tomcat/src/main/java/org/apache/coyote/http11/Response.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
package org.apache.coyote.http11;

import java.util.HashMap;
import java.util.Map;

public class Response {

private final HttpStatus httpStatus;
private final String content;
private final Map<String, String> cookies;

public Response(final HttpStatus httpStatus, final String content) {
this.httpStatus = httpStatus;
this.content = content;
this.cookies = new HashMap<>();
}

public Response(final HttpStatus httpStatus, final String content, final Map<String, String> cookies) {
this.httpStatus = httpStatus;
this.content = content;
this.cookies = cookies;
}

public HttpStatus getHttpStatus() {
Expand All @@ -17,4 +28,8 @@ public HttpStatus getHttpStatus() {
public String getContent() {
return content;
}

public Map<String, String> getCookies() {
return cookies;
}
}