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

Feature/security #32

Open
wants to merge 10 commits into
base: dev
Choose a base branch
from
Open
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ repositories {

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
Expand All @@ -41,6 +42,10 @@ dependencies {
//swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'

//jwt
implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.5'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.alom.dorundorunbe.domain.auth.dto;

public record AuthUserDto(
String socialId,
String email
) {
public static AuthUserDto of (String socialId, String email) {
return new AuthUserDto(socialId, email);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.alom.dorundorunbe.domain.auth.dto;

import com.alom.dorundorunbe.domain.user.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.OAuth2User;

import java.util.Collection;
import java.util.Map;

public class PrincipalUserDetails implements UserDetails, OAuth2User {

private final User principalUser;
private final Map<String, Object> attributes;

public PrincipalUserDetails(User user) {
this(user, null);
}

public PrincipalUserDetails(User user, Map<String, Object> attributes) {
this.principalUser = user;
this.attributes = attributes;
}

@Override
public String getName() {
return String.valueOf(principalUser.getId());
}

@Override
public Map<String, Object> getAttributes() {
return attributes;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}

@Override
public String getPassword() {
return null;
}

@Override
public String getUsername() {
return principalUser.getEmail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.alom.dorundorunbe.domain.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OAuthFailureHandler implements AuthenticationFailureHandler {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException {

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(objectMapper.writeValueAsString("로그인에 실패하였습니다."));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.alom.dorundorunbe.domain.auth.handler;

import com.alom.dorundorunbe.domain.auth.dto.PrincipalUserDetails;
import com.alom.dorundorunbe.domain.auth.provider.JwtTokenProvider;
import com.alom.dorundorunbe.domain.auth.token.AccessToken;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OAuthSuccessHandler implements AuthenticationSuccessHandler {

private final JwtTokenProvider jwtTokenProvider;

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) {
// 유저 정보 추출 -> jwt access 토큰 생성 -> access 토큰을 헤더에 저장

PrincipalUserDetails userDetails = (PrincipalUserDetails) authentication.getPrincipal();

AccessToken accessToken = jwtTokenProvider.generateAccessToken(userDetails.getUsername());

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpStatus.OK.value());
response.setHeader("Authorization", "Bearer " + accessToken.token());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.alom.dorundorunbe.domain.auth.provider;

import com.alom.dorundorunbe.domain.auth.token.AccessToken;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtTokenProvider {

@Value("${jwt.accessExpirationTime}")
private Long ACCESS_EXPIRATION_TIME;

private final SecretKey secretKey;

@Autowired
public JwtTokenProvider(@Value("${jwt.secret}") String secret) {
this.secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
}

public AccessToken generateAccessToken(String username) {
String token = Jwts.builder()
.subject(username)
.claim("type", "access")
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + ACCESS_EXPIRATION_TIME))
.signWith(secretKey)
.compact();

return AccessToken.of(token);
}

public Boolean validateToken(String token) {
try {
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload()
.getExpiration()
.after(new Date());
} catch (ExpiredJwtException e) {
throw new RuntimeException("만료된 토큰입니다.");
} catch (Exception e) {
throw new RuntimeException("올바르지 않은 토큰입니다.");
}
}

public String getSubject(String token) {
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.alom.dorundorunbe.domain.auth.provider;

import com.alom.dorundorunbe.domain.auth.dto.AuthUserDto;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OAuth2AttributeProvider {

public AuthUserDto convertUserAttribute(String registrationId, OAuth2User oAuth2User) {

if (registrationId.equals("kakao")) {
return kakaoUserAttribute(oAuth2User);
}

return null;
}

private AuthUserDto kakaoUserAttribute(OAuth2User oAuth2User) {
Map<String, Object> attribute = oAuth2User.getAttributes();
Map<String, Object> kakaoAccount = (Map<String, Object>) attribute.get("kakao_account");
// Map<String, Object> profile = (Map<String, Object>) kakaoAccount.get("profile");

return AuthUserDto.of(attribute.get("id").toString(), kakaoAccount.get("email").toString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.alom.dorundorunbe.domain.auth.service;

import com.alom.dorundorunbe.domain.auth.dto.AuthUserDto;
import com.alom.dorundorunbe.domain.auth.dto.PrincipalUserDetails;
import com.alom.dorundorunbe.domain.auth.provider.OAuth2AttributeProvider;
import com.alom.dorundorunbe.domain.user.domain.User;
import com.alom.dorundorunbe.domain.user.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;

import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class PrincipalUserDetailsService extends DefaultOAuth2UserService implements UserDetailsService {

private final OAuth2AttributeProvider oAuth2AttributeProvider;
private final UserService userService;

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
// userRequest: (로그인 요청 -> 인가 코드 -> 토큰 -> 사용자 정보)의 프로세스에서 최종적으로 반환된 사용자 정보
// 사용자 정보 추출 -> email로 회원 존재 확인 -> 회원을 등록하거나 업데이트 -> 회원을 OAuth2User로 감싸서 반환

// 사용자 정보 (registrationId + attribute + etc)
OAuth2User oAuth2User = super.loadUser(userRequest);

AuthUserDto authUserDto = oAuth2AttributeProvider
.convertUserAttribute(userRequest.getClientRegistration().getRegistrationId(), oAuth2User);

User user = userService.findByEmail(authUserDto.email()).orElse(registerUser(authUserDto));

return new PrincipalUserDetails(user);
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.findByEmail(username)
.orElseThrow();

return new PrincipalUserDetails(user);
}

private User registerUser(AuthUserDto authUserDto) {
// age과 gender의 경우 oauth 로그인으로 바로 가져오려면 사업자 정보 등록이 필요해서 이 부분은 논의 필요

return User.builder()
.socialId(authUserDto.socialId())
.email(authUserDto.email())
.cash(0L)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.alom.dorundorunbe.domain.auth.token;

public record AccessToken(
String token
) {
public static AccessToken of(String token) {
return new AccessToken(token);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.alom.dorundorunbe.domain.doodle.repository;

import com.alom.dorundorunbe.domain.doodle.domain.Doodle;
import com.alom.dorundorunbe.domain.doodle.domain.UserDoodle;
import com.alom.dorundorunbe.domain.user.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserDoodleRepository extends JpaRepository<UserDoodle, Long> {
Optional<UserDoodle> findByDoodleAndUser(Long doodleId, Long userId);
Optional<UserDoodle> findByDoodleAndUser(Doodle doodle, User user);

}
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public void deleteParticipant(Long doodleId, Long userId){
orElseThrow(()->new RuntimeException("존재하지 않는 Doodle 입니다."));
User user = userRepository.findById(userId).
orElseThrow(()->new RuntimeException("존재하지 않는 유저 ID 입니다."));
UserDoodle userDoodle = userDoodleRepository.findByDoodleAndUser(doodleId, userId).
UserDoodle userDoodle = userDoodleRepository.findByDoodleAndUser(doodle, user).
orElseThrow(()->new RuntimeException("유저가 해당 Doodle에 존재하지 않습니다."));

userDoodleRepository.delete(userDoodle);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ public ResponseEntity<String> updateByName(UserUpdateDTO userDTO, String usernam
if(checkNickNameDuplicate(userDTO.getNickname()))
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Nickname already exists");
existingUser.setNickname(userDTO.getNickname());
existingUser.setAge(userDTO.getAge());
existingUser.setName(userDTO.getName());
userRepository.save(existingUser);
return ResponseEntity.status(HttpStatus.OK).body("User updated successfully");
Expand Down

This file was deleted.

23 changes: 10 additions & 13 deletions src/main/java/com/alom/dorundorunbe/domain/user/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,34 @@ public class User extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// 임의로 추가한 필드 -> kakao 로그인 구현 시 수정
@Column(name = "kakao_id", nullable = false, unique = true)
private String kakaoId;
// 소셜 로그인 서비스의 사용자 id (사용자 인증 시 필요)
private String socialId;

// 소셜 로그인 시 받아올 정보 -> 두런 내에서 사용자 식별에 사용
@Column(nullable = false, unique = true)
private String email;

// 앱 내에서 사용할 닉네임 (ㅇㅇ두)
@Column(nullable = false, unique = true, length = 32)
private String nickname;

// 필요 없는 필드 같음
@Column(nullable = false, length = 32)
private String name;

@Column(nullable = false, length = 50)
private String email;

private int age;

// 없애야 하는 필드!!
private String password;

@OneToOne(mappedBy = "user") //ranking 객체를 참조하는데, 이때 ranking 내의 user가 관계 주인
private Ranking ranking;

@Enumerated(EnumType.STRING)
private Gender gender;

@Column(nullable = false)
private Long cash;

@Enumerated(EnumType.STRING)
@Column(nullable = true)
private Tier tier; // BACKGROUND 업적일 때 사용 (유저의 티어와 매칭)

@Column(nullable = true, length = 64)
@Column(length = 64)
private String background; // BACKGROUND 업적일 때 보상 배경

public void updateCash(Long cash) {
Expand Down
Loading