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

feat : userAPI , jwt인증 interceptor 구현, @NoAuth 커스텀어노테이션구현 #14

Merged
merged 1 commit into from
May 16, 2023
Merged
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
21 changes: 21 additions & 0 deletions src/main/java/com/wakeUpTogetUp/togetUp/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package com.wakeUpTogetUp.togetUp.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wakeUpTogetUp.togetUp.config.interceptor.AuthenticationInterceptor;
import com.wakeUpTogetUp.togetUp.utils.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final JwtService jwtService;
private final ObjectMapper objectMapper;

@Override
public void addCorsMappings(CorsRegistry registry) {
Expand All @@ -23,4 +31,17 @@ public void addCorsMappings(CorsRegistry registry) {
// 해당 옵션 사용시 allowedOrigins를 * (전체)로 설정할 수 없다.
.allowCredentials(true);
}

@Override
public void addInterceptors(InterceptorRegistry reg){
reg.addInterceptor(new AuthenticationInterceptor(jwtService,objectMapper))
.order(1)
.addPathPatterns("/app/users")
.excludePathPatterns("/app/group");
// .addPathPatterns("/**"); //interceptor 작업이 필요한 path를 모두 추가한다.

//.excludePathPatterns("app/accounts","/app/accounts/auth","app/videos/**");
// 인가작업에서 제외할 API 경로를 따로 추가할수도 있으나, 일일히 따로 추가하기 어려우므로 어노테이션을 따로 만들어 해결한다.
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.wakeUpTogetUp.togetUp.config.annotation;

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

@Retention(RetentionPolicy.RUNTIME) //어노테이션 레벨을 결정짓는다.
@Target({ElementType.TYPE, ElementType.METHOD})//선언된 어노테이션이 적용될수 있는 위치를 결정. TYPE-class,interface,enum에 적용.
public @interface NoAuth {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.wakeUpTogetUp.togetUp.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wakeUpTogetUp.togetUp.common.exception.BaseException;
import com.wakeUpTogetUp.togetUp.config.annotation.NoAuth;
import com.wakeUpTogetUp.togetUp.utils.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
public class AuthenticationInterceptor implements HandlerInterceptor {
private final JwtService jwtService;
private final ObjectMapper objectMapper; //자바 객체를 json으로 serialization

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean check=checkAnnotation(handler, NoAuth.class);

if(check) return true;

try{
int userNumByJwt = jwtService.getUserNum();

request.setAttribute("userId",userNumByJwt);
}catch(BaseException exception){
String requestURI= request.getRequestURI();

Map<String,String> map=new HashMap<>();
map.put("requestURI","/app/accounts/auth?redirectURI="+requestURI);
//redirectURI는 로그인 절차가 끝내고 다시 시도했던 페이지로 돌아가기 위해 JSON 정보에 포함시킨다.
String json=objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
response.getWriter().write(json);

return false;
}
return true;
}

private boolean checkAnnotation(Object handler,Class cls){
HandlerMethod handlerMethod=(HandlerMethod) handler;
if(handlerMethod.getMethodAnnotation(cls)!=null){ //해당 어노테이션이 존재하면 true.
return true;
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.wakeUpTogetUp.togetUp.common.exception.BaseException;
import com.wakeUpTogetUp.togetUp.common.dto.BaseResponse;
import com.wakeUpTogetUp.togetUp.common.ResponseStatus;
import com.wakeUpTogetUp.togetUp.config.annotation.NoAuth;
import com.wakeUpTogetUp.togetUp.group.dto.request.GroupReq;
import com.wakeUpTogetUp.togetUp.group.dto.response.GroupRes;

Expand All @@ -13,6 +14,7 @@
import javax.validation.Valid;
import java.util.List;


@RestController
@RequiredArgsConstructor
@RequestMapping("/app/group")
Expand Down Expand Up @@ -89,6 +91,7 @@ public BaseResponse<GroupRes> updateGroup(
* @param groupId
* @return
*/
@NoAuth
@DeleteMapping("{groupId}")
@ResponseBody
public BaseResponse<ResponseStatus> deleteGroup(
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/wakeUpTogetUp/togetUp/security.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.wakeUpTogetUp.togetUp;

public class security {
}
99 changes: 94 additions & 5 deletions src/main/java/com/wakeUpTogetUp/togetUp/users/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,24 @@
import com.wakeUpTogetUp.togetUp.common.exception.BaseException;
import com.wakeUpTogetUp.togetUp.common.dto.BaseResponse;
import com.wakeUpTogetUp.togetUp.common.ResponseStatus;
import com.wakeUpTogetUp.togetUp.config.annotation.NoAuth;
import com.wakeUpTogetUp.togetUp.group.dto.request.GroupReq;
import com.wakeUpTogetUp.togetUp.group.dto.response.GroupRes;
import com.wakeUpTogetUp.togetUp.users.dto.request.LoginReq;
import com.wakeUpTogetUp.togetUp.users.dto.request.PatchUserReq;
import com.wakeUpTogetUp.togetUp.users.dto.request.UserReq;
import com.wakeUpTogetUp.togetUp.users.dto.response.UserInfoRes;
import com.wakeUpTogetUp.togetUp.users.dto.response.UserRes;
import com.wakeUpTogetUp.togetUp.users.dto.response.UserTokenRes;
import com.wakeUpTogetUp.togetUp.users.oauth.GetSocialOAuthRes;
import com.wakeUpTogetUp.togetUp.users.oauth.OAuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;


@RestController
Expand All @@ -22,19 +31,99 @@ public class UserController {
private final UserService userService;
private final OAuthService oAuthService;


/**
* 회원가입
* @param userReq
* @return
*/
@NoAuth
@ResponseBody
@PostMapping("/new") //
public BaseResponse<UserRes> join(@RequestBody UserReq form) {
@PostMapping() //
public BaseResponse<UserRes> join(@RequestBody UserReq userReq) {
try {
System.out.println("로그인"+form);
UserRes userRes=userService.createUser(form);
System.out.println("안녕");
UserRes userRes=userService.createUser(userReq);
return new BaseResponse<>(ResponseStatus.SUCCESS,userRes);
} catch (BaseException exception) {
return new BaseResponse<>((exception.getStatus()));
}
}

/**
*
* @param loginReq
* @return
*/
@NoAuth
@PostMapping("/login")
public BaseResponse<UserTokenRes> login(@RequestBody LoginReq loginReq) {
String token = userService.createToken(loginReq);
return new BaseResponse<>(ResponseStatus.SUCCESS,new UserTokenRes(token, "bearer"));
}


/**
*유저 전체 GET
* @return
*/
@NoAuth
@ResponseBody
@GetMapping("list")
public BaseResponse<List<UserRes>> getUserAll(){
List<UserRes> UserResList = userService.getUserAll();

return new BaseResponse<>(ResponseStatus.SUCCESS, UserResList);
}


/**
* 유저 한명 get
* @param userId
* @return
*/

@ResponseBody
@GetMapping("{userId}")
public BaseResponse<UserInfoRes> getUser(@PathVariable Integer userId){
System.out.println("정보");
UserInfoRes userInfoRes = userService.getUser(userId);
return new BaseResponse<>(ResponseStatus.SUCCESS, userInfoRes);
}

/**
*
* @param userId
* @param patchUserReq
* @return
*/
@PatchMapping("{userId}")
@ResponseBody
public BaseResponse<UserInfoRes> updateUser(
@PathVariable Integer userId,
@RequestBody PatchUserReq patchUserReq
) {

UserInfoRes userInfoRes = userService.editUser(userId, patchUserReq);
return new BaseResponse<>(ResponseStatus.SUCCESS, userInfoRes);
}

/**
* 유저삭제
* @param userId
* @return
*/
@DeleteMapping("{userId}")
@ResponseBody
public BaseResponse<ResponseStatus> deleteUser(
@PathVariable @Valid Integer userId
) {

userService.deleteUser(userId);

return new BaseResponse(ResponseStatus.SUCCESS);
}


/**
* 유저 소셜 로그인으로 리다이렉트 해주는 url
* [GET] /accounts/auth
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
int countByEmail(String email);

User findByEmail(String email);
// private final EntityManager em;
// public void save(User user) {
// em.persist(user);
Expand Down
Loading