Skip to content

Commit

Permalink
Merge pull request #4 from KAKAO-TOUR-API-CONTEST/develop
Browse files Browse the repository at this point in the history
FEAT : add a headerInterceptor
  • Loading branch information
femmefatalehaein authored Aug 11, 2024
2 parents 4da8797 + 12ea6df commit 96aedea
Show file tree
Hide file tree
Showing 19 changed files with 287 additions and 123 deletions.
5 changes: 3 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,16 @@ dependencies {
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
//implementation 'org.springframework.boot:spring-boot-starter-security'

implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
//JWT 의존성 추가
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'
//implementation 'org.springframework.boot:spring-boot-starter-security'

compileOnly 'org.projectlombok:lombok'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/example/ai_jeju/config/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ public class AppConfig {
public RestTemplate restTemplate() {
return new RestTemplate();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.example.ai_jeju.config;

import com.example.ai_jeju.jwt.TokenProvider;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class HeaderCheckInterceptor implements HandlerInterceptor {

private final static String HEADER_AUTHORIZATION = "Authorization";
private final static String TOKEN_PREFIX = "Bearer ";
@Autowired
private TokenProvider tokenProvider;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 예시로 "X-Custom-Header"라는 헤더를 확인
String headerValue = request.getHeader("access-token");

String authorizationHeader = request.getHeader(HEADER_AUTHORIZATION);

// 가져온 값에서 접두사 제거
String token = getAccesToken(authorizationHeader);

// 가져온 토큰이 유효한지 확인하고, 유효한 때는 인증정보 설정한다.
System.out.println("토큰 유효성 검사"+tokenProvider.validToken(token));


// 헤더가 올바르면 요청을 진행
return true;
}

private String getAccesToken(String authorizationHeader){
System.out.println("get Access Token 실행");

if(authorizationHeader != null && authorizationHeader.startsWith(TOKEN_PREFIX)){

System.out.println("get Access Token : " + authorizationHeader.substring(TOKEN_PREFIX.length()));

return authorizationHeader.substring(TOKEN_PREFIX.length());
}
else{
System.out.println("Access Token 없음");
}
return null;
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/example/ai_jeju/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.example.ai_jeju.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Autowired
private HeaderCheckInterceptor headerCheckInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
// 모든 경로에 대해 인터셉터를 적용 (필요에 따라 경로를 지정할 수 있음)
registry.addInterceptor(headerCheckInterceptor).addPathPatterns("/**");
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.example.ai_jeju.controller;


import com.example.ai_jeju.domain.Restaurant;
import com.example.ai_jeju.domain.Stay;
import com.example.ai_jeju.service.MainVIewService;
Expand All @@ -14,30 +13,21 @@ public class MainViewController {
@Autowired
private MainVIewService mainViewService;

/*
@GetMapping("/mainList")
public ResponseEntity<String> signOut(@RequestBody WithdrawRequest withdrawRequest) {
String response = userService.withDraw(withdrawRequest);
return ResponseEntity.ok(response);
}*/

/*
@GetMapping("/mainList")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
*/

@GetMapping("/restaurant/detailList")
public Restaurant getUserById(@RequestParam int restaurantId) {
return mainViewService.getRestaurantList(restaurantId);
}


@GetMapping("/stay/detailList")
public Stay getStayById(@RequestParam int stayId) {
return mainViewService.getStayList(stayId);
}
// @GetMapping("/stay/detailList")
// public Stay getStayById(@RequestParam int stayId) {
// return mainViewService.getStayList(stayId);
// }
//
//
// @GetMapping("/play/detailList")
// public Stay getStayById(@RequestParam int stayId) {
// return mainViewService.getStayList(stayId);
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,13 @@ public ResponseEntity<User> getUserById(@RequestParam Long userId) {
}
}


@PutMapping("/mypage/nickname")
public ResponseEntity<String> updateNickname(@RequestParam Long userId, @RequestBody Map<String, String> request) {
String nickname = request.get("nickname");
myPageService.updateNickname(userId, nickname);
return ResponseEntity.ok("Nickname changed");
}

//sns프로필 사용하기로 했었나? 사용하면 user쪽에 entity변수 하나 추가해서 해야함
/*
@PutMapping("/mypage/snsprofile")
public ResponseEntity<String> updateSnsProfile(@RequestParam Long userId, @RequestBody Map<String, String> request) {
String snsprofile = request.get("snsprofile");
myPageService.updateSnsProfile(id, snsprofile);
return ResponseEntity.ok("snsprofile change");
}*/

//프로필 이미지 변경
@PutMapping("/mypage/profileimg")
Expand Down
11 changes: 8 additions & 3 deletions src/main/java/com/example/ai_jeju/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import com.example.ai_jeju.dto.SignUpRequest;
import com.example.ai_jeju.dto.WithdrawRequest;
import com.example.ai_jeju.handler.SignUpHandler;
import com.example.ai_jeju.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
Expand All @@ -17,13 +20,15 @@ public class UserController {
@Autowired
private UserService userService;



//회원가입
/*여기 확인해보자*/
@PostMapping("/signup")
public ResponseEntity<String> signUp(@RequestBody SignUpRequest signUpRequest) throws IOException {
String response = userService.signUp(signUpRequest);
public void signUp(@RequestBody SignUpRequest signUpRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
//String response = userService.signUp(signUpRequest);
//System.out.println(response);
return ResponseEntity.ok(response);
userService.signUp(signUpRequest,request,response);
}


Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/example/ai_jeju/domain/Child.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class Child {
private Long userId;

@Column
private Date birthDate;
private String birthDate;

@Column
private String childName;
Expand Down
40 changes: 40 additions & 0 deletions src/main/java/com/example/ai_jeju/domain/Play.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.example.ai_jeju.domain;


import jakarta.persistence.*;
import lombok.*;

@Table(name="play")
@NoArgsConstructor(access= AccessLevel.PROTECTED) //기본생성자
@Getter
@Entity
@AllArgsConstructor // 모든 필드를 초기화하는 생성자
@Builder // 빌더 패턴
public class Play {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "playId", updatable = false, unique = true)
int playId;

@Column(name = "playName", updatable = false)
String playName;

@Column(name = "latitude", updatable = false)
double latitude;

@Column(name = "longitude", updatable = false)
double longitude;

@Column(name = "addr", updatable = false)
String address;

@Column(name = "dc", updatable = false)
int chair;

@Column(name = "nokidsZone", updatable = false)
Boolean nokidsZone;

@Column(name = "operation_time", updatable = false)
int operationTime;
}
2 changes: 2 additions & 0 deletions src/main/java/com/example/ai_jeju/domain/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ public RefreshToken update(String newRefreshToken){
}




}
2 changes: 0 additions & 2 deletions src/main/java/com/example/ai_jeju/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,13 @@ public class User {

@Column(name="email", nullable = false, unique = true)
private String email;

//실명
@Column(name = "name")
private String name;

@Column(name = "nickname")
private String nickname;


@Column(name = "provider")
private String provider;

Expand Down
29 changes: 29 additions & 0 deletions src/main/java/com/example/ai_jeju/filter/HeaderCheckFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.ai_jeju.filter;

import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

public class HeaderCheckFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

// 예시로 "X-Custom-Header"라는 헤더를 확인
String headerValue = request.getHeader("X-Custom-Header");

if (headerValue == null || !headerValue.equals("ExpectedValue")) {
// 헤더가 없거나 예상된 값이 아닐 경우 요청을 차단
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write("Missing or Invalid Header");
return;
}

// 헤더가 올바르면 다음 필터로 진행
filterChain.doFilter(request, response);
}
}
Loading

0 comments on commit 96aedea

Please sign in to comment.