Skip to content

Commit

Permalink
🛠️Feat #23: [Security] User Security 완성
Browse files Browse the repository at this point in the history
  • Loading branch information
DDonghyeo committed Jul 27, 2023
1 parent 921e7a8 commit 2e33b3a
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 77 deletions.
2 changes: 1 addition & 1 deletion src/main/java/com/umc/DongnaeFriend/config/JwtConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
public class JwtConfig {

@Value("${jwt.secret-key}")
public static String SECRET_KEY;
public String SECRET_KEY;

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.umc.DongnaeFriend.config;

import com.umc.DongnaeFriend.security.JwtTokenFilter;

import com.umc.DongnaeFriend.global.security.JwtTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Expand Down Expand Up @@ -30,4 +31,3 @@ protected void configure(HttpSecurity http) throws Exception {

// 나머지 코드는 이전 예제와 동일
}

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand Down Expand Up @@ -35,9 +36,7 @@ public class accountBookSharingController {
@GetMapping("/search")

public ResponseEntity<?> searchAll(@RequestParam("keyword") String keyword, @RequestParam("category") int category, Pageable pageable) {
log.info("searching : " + keyword + category);
List<SharingDto.ListResponse> res = accountBookSharingService.searchByKeyword(keyword, category, pageable);
log.info("res ");
return ResponseEntity.ok(res);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.umc.DongnaeFriend.domain.dongnae.dto.DongnaeBoardDto;
import com.umc.DongnaeFriend.domain.dongnae.respository.DongnaeBoardRepository;
import com.umc.DongnaeFriend.domain.dongnae.service.DongnaeBoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -14,6 +15,7 @@
* [ 가계부 공유 ]
* */

@Slf4j
@RestController
@RequestMapping("/town-information")
public class DongnaeBoardController {
Expand Down Expand Up @@ -53,6 +55,9 @@ public ResponseEntity<?> getLocation() {
public ResponseEntity<?> getBoards(@RequestParam("keyword") String keyword,
@RequestParam("category") int category,
@RequestParam("sortBy") int sort) {


log.info("User Id: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return ResponseEntity.ok(dongnaeBoardService.searchByKeyword(keyword, category, sort));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
import com.umc.DongnaeFriend.global.util.JwtTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

Expand All @@ -25,6 +28,7 @@ public class UserController {
@Autowired
UserService userService;

@Autowired
JwtTokenProvider jwtTokenProvider;


Expand All @@ -34,19 +38,24 @@ public class UserController {
* 인증 절차
*/
@PostMapping("/login")
public ResponseEntity<?> userLogin(@RequestBody UserDto.Request request) {
public ResponseEntity<?> userLogin(@RequestParam("accessToken") String accessToken, HttpServletRequest request, HttpServletResponse httpServletResponse) {
log.info("LoginController 진입");

// if (!type.equals("kakao")) {
// throw new CustomException(ErrorCode.SERVER_ERROR);
// }


try {
log.info("userLogin 진입");
//사용자 정보 가져오기
HashMap<String, Object> userInfo = kakaoService.getUserInfo(request.getAccessToken());
HashMap<String, Object> userInfo = kakaoService.getUserInfo(accessToken);

//사용자 확인 기존 회원 -> 넘어가고, 없는 회원 -> 회원가입
userService.userValidation(userInfo);

//토큰 생성
String access_token = jwtTokenProvider.createAccessToken((Long) userInfo.get("userId"));
log.info("access_token : {}", access_token);
return ResponseEntity.ok(access_token);
UserDto.Response response = userService.userValidation(userInfo);

return ResponseEntity.ok(response);

} catch (IOException e) {
throw new CustomException(ErrorCode.INVALID_AUTH_TOKEN);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.umc.DongnaeFriend.domain.user.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

public class UserDto {
Expand All @@ -16,6 +17,7 @@ public static class Request {
}

@Getter
@Builder
@AllArgsConstructor
public static class Response {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.umc.DongnaeFriend.domain.type.YesNo;
import javax.persistence.*;
import lombok.*;
import org.springframework.lang.Nullable;

@Getter
@Builder
Expand All @@ -29,6 +30,7 @@ public class User extends BaseTimeEntity {

@ManyToOne(fetch = LAZY)
@JoinColumn(name = "dongnae_id")
@Nullable
private Dongnae dongnae;

@Column(nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findById(Long id);

Optional<User> findByRefreshToken(String refresh_token);

Optional<User> findByKakaoId(Long id);
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.umc.DongnaeFriend.domain.user.service;


import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.HashMap;

public interface KakaoService {


@SuppressWarnings("unchecked")
HashMap<String, Object> getUserInfo(String access_Token) throws IOException;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
Expand All @@ -12,6 +13,7 @@
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class KakaoServiceimpl implements KakaoService {

Expand Down Expand Up @@ -52,23 +54,26 @@ public HashMap<String, Object> getUserInfo(String access_Token) throws IOExcepti
Map<String, Object> jsonMap = objectMapper.readValue(result, new TypeReference<Map<String, Object>>() {
});


System.out.println(jsonMap.get("properties"));

Long id = (Long) jsonMap.get("id");
Map<String, Object> properties = (Map<String, Object>) jsonMap.get("properties");
Map<String, Object> kakao_account = (Map<String, Object>) jsonMap.get("kakao_account");
Map<String, Object> profile = (Map<String, Object>) kakao_account.get("profile");

// System.out.println(properties.get("nickname"));
// System.out.println(kakao_account.get("email"));
log.info("profile : " + profile.toString());
log.info("kakao_acount : " + kakao_account.toString());

String nickname = properties.get("nickname").toString();
String profileImage = properties.get("profile_image").toString();
String email = kakao_account.get("email").toString();
String gender = kakao_account.get("gender").toString();
String age = kakao_account.get("age").toString();

userInfo.put("id", id);
userInfo.put("nickname", nickname);
userInfo.put("profileImage", profileImage);
userInfo.put("email", email);
userInfo.put("gender", gender);
userInfo.put("age", age);


return userInfo;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.umc.DongnaeFriend.domain.type.Age;
import com.umc.DongnaeFriend.domain.type.Gender;
import com.umc.DongnaeFriend.domain.type.YesNo;
import com.umc.DongnaeFriend.domain.user.dto.UserDto;
import com.umc.DongnaeFriend.domain.user.entity.User;
import com.umc.DongnaeFriend.domain.user.repository.UserRepository;
import com.umc.DongnaeFriend.global.exception.CustomException;
Expand All @@ -25,53 +26,80 @@ public class UserService {

KakaoService kakaoService;

@Autowired
JwtTokenProvider jwtTokenProvider;

public void userValidation(HashMap<String, Object> userInfo) {
Optional<User> user= userRepository.findById((Long) userInfo.get("userId"));

public UserDto.Response userValidation(HashMap<String, Object> userInfo) {
Long kakao_id = (Long) userInfo.get("id");
Optional<User> user= userRepository.findByKakaoId(kakao_id);
if (user.isEmpty()) {
userRegister(userInfo);
User new_user = userRegister(userInfo);
return UserDto.Response.builder()
.accessToken(jwtTokenProvider.createAccessToken(new_user.getId()))
.refreshToken(new_user.getRefreshToken())
.build();
} else {
return UserDto.Response.builder()
.accessToken(jwtTokenProvider.createAccessToken(user.get().getId()))
.refreshToken(user.get().getRefreshToken())
.build();
}

}


//유저 회원가입
public void userRegister(HashMap<String, Object> userInfo) {
//유저 회원가입 -> Refresh Token을 return
public User userRegister(HashMap<String, Object> userInfo) {
//필수
String nickName = userInfo.get("nickname").toString();
//필수
String email = userInfo.get("email").toString();

Optional<String> gender = Optional.ofNullable(userInfo.get("gender").toString());
String strGender = "";
log.info("Gender : {}", gender.get());
if(gender.get()=="F"){
strGender="여성";
}else {
strGender = "남성";
}
log.info("strGender : {}", strGender);


Optional<String> age = Optional.ofNullable(userInfo.get("age").toString());
String[] ageRange = age.get().split("-");


// refreshToken userId를 claim 으로 생성 뒤, User의 필드에 넣고 User를 저장
String refresh_Token = jwtTokenProvider.createRefreshToken((Long) userInfo.get("usreId"));

userRepository.save(
String profileImage = userInfo.get("profileImage").toString();

Long kakaoId = (Long) userInfo.get("id");

// Optional<String> gender = Optional.ofNullable(userInfo.get("gender").toString());
// String strGender = "";
// log.info("Gender : {}", gender.get());
// if(gender.get()=="F"){
// strGender="여성";
// }else {
// strGender = "남성";
// }
// log.info("strGender : {}", strGender);
//
//
// Optional<String> age = Optional.ofNullable(userInfo.get("age").toString());
// String[] ageRange = age.get().split("-");
//
//
// // refreshToken userId를 claim 으로 생성 뒤, User의 필드에 넣고 User를 저장
String refresh_Token = jwtTokenProvider.createRefreshToken((Long) userInfo.get("id"));

return userRepository.save(
User.builder()
.nickname(nickName)
// .dongnae(
//
// )
.email(email)
//TODO : Gender 결정[O]
.gender(Gender.valueOf(strGender))
.gender(
// Gender.valueOf(strGender)
Gender.MALE
)
//TODO : Age 결정[O]
.age(Age.valueOf(ageRange[0]+"대"))
.age(
// Age.valueOf(ageRange[0]+"대")
Age.AGE20
)
.townCert(YesNo.NO)
.townCertCnt(0)
.infoCert(YesNo.NO)
.profileImage(profileImage)
.kakaoId(kakaoId)
.refreshToken(refresh_Token)
.build()
);
Expand All @@ -91,4 +119,6 @@ public String createAccessTokenFromRefreshToken(String refreshToken) {

return accessToken;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ protected ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgument
}

//일반 예외처리
@ExceptionHandler({Exception.class})
protected ResponseEntity<?> handleServerException(Exception ex) {
CustomException exception = new CustomException(SERVER_ERROR);
return ResponseEntity
.status(SERVER_ERROR.getHttpStatus())
.body(new ErrorResponse(exception));
}
// @ExceptionHandler({Exception.class})
// protected ResponseEntity<?> handleServerException(Exception ex) {
// CustomException exception = new CustomException(SERVER_ERROR);
// return ResponseEntity
// .status(SERVER_ERROR.getHttpStatus())
// .body(new ErrorResponse(exception));
// }
}
Loading

0 comments on commit 2e33b3a

Please sign in to comment.