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

[Spring Data JPA] 이지은 미션 제출합니다 #65

Open
wants to merge 5 commits into
base: jelee2555
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
// implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

implementation 'dev.akkinoc.spring.boot:logback-access-spring-boot-starter:4.0.0'

implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-gson:0.11.2'
implementation 'org.projectlombok:lombok:1.18.22'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.rest-assured:rest-assured:5.3.1'
Expand Down
8 changes: 8 additions & 0 deletions src/main/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## 5단계 요구사항
### 내 예약 목록 조회 API 구현
- [x] 내 예약 목록 응답 api 만들 때 새로운 DTO
- [x] Reservation 테이블 수정
- [x] 관리자가 어드민 화면에서 예약 생성 시, name을 string으로
- [x] 사용자가 예약 생성 시, 로그인 정보를 이용하여 member id를 reservation에 저장


25 changes: 25 additions & 0 deletions src/main/java/roomescape/AdminInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package roomescape;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import roomescape.member.Member;
import roomescape.member.MemberService;

public class AdminInterceptor implements HandlerInterceptor {
private MemberService memberService;

public AdminInterceptor(MemberService memberService) {
this.memberService = memberService;
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Member member = memberService.getMemberFromCookie(request);

if (member == null || !member.getRole().equals("ADMIN")) {
response.setStatus(401);
}
return true;
}
}
40 changes: 40 additions & 0 deletions src/main/java/roomescape/LoginMember.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package roomescape;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class LoginMember {
private Long id;
private String name;
private String email;
private String role;

public LoginMember(Long id, String name, String email, String role) {
this.id = id;
this.name = name;
this.email = email;
this.role = role;
}

public Long getId() {
return id;
}

public String getName() {
return name;
}

public String getEmail() {
return email;
}

public String getRole() {
return role;
}


}


36 changes: 36 additions & 0 deletions src/main/java/roomescape/LoginMemberArgumentResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package roomescape;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import roomescape.auth.AuthorizationExtractor;
import roomescape.member.Member;
import roomescape.member.MemberDao;
import roomescape.member.MemberService;

import java.util.Arrays;

public class LoginMemberArgumentResolver implements HandlerMethodArgumentResolver {
private MemberService memberService;
public LoginMemberArgumentResolver(MemberService memberService) {
this.memberService = memberService;
}

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(LoginMember.class);
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) webRequest.getNativeRequest();

Member member = memberService.getMemberFromCookie(httpServletRequest);

return new LoginMember(member.getId(), member.getName(), member.getEmail(), member.getRole());
}
}
29 changes: 29 additions & 0 deletions src/main/java/roomescape/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package roomescape;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import roomescape.auth.AuthorizationExtractor;
import roomescape.member.MemberDao;
import roomescape.member.MemberService;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MemberService memberService;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new LoginMemberArgumentResolver(memberService));
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AdminInterceptor(memberService)).addPathPatterns("/admin/**");
}
}
47 changes: 47 additions & 0 deletions src/main/java/roomescape/auth/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package roomescape.auth;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import roomescape.member.MemberResponse;

@RestController
public class AuthController {
private final AuthService authService;

public AuthController(AuthService authService) {
this.authService = authService;
}

@PostMapping("/login")
public ResponseEntity<TokenResponse> login(@RequestBody TokenRequest tokenRequest, HttpServletResponse response) {
TokenResponse tokenResponse = authService.createToken(tokenRequest);

// cookie 생성
Cookie cookie = new Cookie("token", tokenResponse.getAccessToken());
cookie.setHttpOnly(true);
cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.ok().body(tokenResponse);
}

@GetMapping("/login/check")
public ResponseEntity<MemberResponse> checkLogin(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
String token = extractTokenFromCookie(cookies);
MemberResponse memberResponse = authService.findMemberByToken(token);
return ResponseEntity.ok().body(memberResponse);
}

private String extractTokenFromCookie(Cookie[] cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("token")){
return cookie.getValue();
}
}
return "";
}
}
41 changes: 41 additions & 0 deletions src/main/java/roomescape/auth/AuthService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package roomescape.auth;

import org.springframework.stereotype.Service;
import roomescape.member.Member;
import roomescape.member.MemberDao;
import roomescape.member.MemberResponse;

@Service
public class AuthService {
private MemberDao memberDao;
private TokenProvider tokenProvider;
private AuthorizationExtractor authorizationExtractor;

public AuthService(MemberDao memberDao, TokenProvider tokenProvider, AuthorizationExtractor authorizationExtractor) {
this.memberDao = memberDao;
this.tokenProvider = tokenProvider;
this.authorizationExtractor = authorizationExtractor;
}

public Member findMember(String email, String password) {
Member member = memberDao.findByEmailAndPassword(email, password);
if (member == null) {
throw new IllegalArgumentException();
}
return memberDao.findByEmailAndPassword(email, password);
}

public TokenResponse createToken(TokenRequest tokenRequest) {
Member member = findMember(tokenRequest.getEmail(), tokenRequest.getPassword());

String accessToken = tokenProvider.createToken(member);

return new TokenResponse(accessToken);
}

public MemberResponse findMemberByToken(String token) {
Long id = authorizationExtractor.extractMemberId(token);
Member member = memberDao.findById(id);
return new MemberResponse(member.getId(), member.getName(), member.getEmail());
}
}
29 changes: 29 additions & 0 deletions src/main/java/roomescape/auth/AuthorizationExtractor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package roomescape.auth;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import roomescape.member.Member;
import roomescape.member.MemberDao;

@Component
public class AuthorizationExtractor {
private String secretKey = "Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E=";
private MemberDao memberDao;

public AuthorizationExtractor(MemberDao memberDao) {
this.memberDao = memberDao;
}

public Long extractMemberId (String token) {
Long memberId = Long.valueOf(Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(secretKey.getBytes()))
.build()
.parseClaimsJws(token)
.getBody().getSubject());
return memberId;
}


}

23 changes: 23 additions & 0 deletions src/main/java/roomescape/auth/TokenProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package roomescape.auth;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import roomescape.member.Member;

import java.nio.charset.StandardCharsets;

@Component
public class TokenProvider {
private String secretKey = "Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E=";

public String createToken(Member member) {
String accessToken = Jwts.builder()
.setSubject(member.getId().toString())
.claim("name", member.getName())
.claim("role", member.getRole())
.signWith(Keys.hmacShaKeyFor(secretKey.getBytes()))
.compact();
return accessToken;
}
}
23 changes: 23 additions & 0 deletions src/main/java/roomescape/auth/TokenRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package roomescape.auth;

public class TokenRequest {
private String email;
private String password;

public TokenRequest() {

}

public TokenRequest(String email, String password) {
this.email = email;
this.password = password;
}

public String getEmail() {
return email;
}

public String getPassword() {
return password;
}
}
17 changes: 17 additions & 0 deletions src/main/java/roomescape/auth/TokenResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package roomescape.auth;

public class TokenResponse {
private String accessToken;

public TokenResponse() {

}

public TokenResponse(String accessToken) {
this.accessToken = accessToken;
}

public String getAccessToken() {
return accessToken;
}
}
11 changes: 11 additions & 0 deletions src/main/java/roomescape/member/Member.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
package roomescape.member;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
private String role;

public Member() {

}
public Member(Long id, String name, String email, String role) {
this.id = id;
this.name = name;
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/roomescape/member/MemberController.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package roomescape.member;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/roomescape/member/MemberDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,17 @@ public Member findByName(String name) {
name
);
}

public Member findById(Long id) {
return jdbcTemplate.queryForObject(
"SELECT id, name, email, role FROM member WHERE id = ?",
(rs, rowNum) -> new Member(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email"),
rs.getString("role")
),
id
);
}
}
Loading