Skip to content

Commit

Permalink
Merge branch 'develop' into feature/#8-upload-image
Browse files Browse the repository at this point in the history
  • Loading branch information
ymkim97 authored Nov 13, 2023
2 parents a18c223 + 0d084fa commit 1700d5a
Show file tree
Hide file tree
Showing 48 changed files with 5,678 additions and 1,127 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@

import com.moabam.api.dto.AuthorizationCodeRequest;
import com.moabam.api.dto.AuthorizationCodeResponse;
import com.moabam.api.dto.AuthorizationMapper;
import com.moabam.api.dto.AuthorizationTokenInfoResponse;
import com.moabam.api.dto.AuthorizationTokenRequest;
import com.moabam.api.dto.AuthorizationTokenResponse;
import com.moabam.api.dto.LoginResponse;
import com.moabam.api.dto.OAuthMapper;
import com.moabam.api.dto.PublicClaim;
import com.moabam.global.common.util.CookieUtils;
import com.moabam.global.common.util.GlobalConstant;
import com.moabam.global.config.OAuthConfig;
import com.moabam.global.config.TokenConfig;
import com.moabam.global.error.exception.BadRequestException;
import com.moabam.global.error.model.ErrorMessage;

Expand All @@ -25,9 +27,10 @@

@Service
@RequiredArgsConstructor
public class AuthenticationService {
public class AuthorizationService {

private final OAuthConfig oAuthConfig;
private final TokenConfig tokenConfig;
private final OAuth2AuthorizationServerRequestService oauth2AuthorizationServerRequestService;
private final MemberService memberService;
private final JwtProviderService jwtProviderService;
Expand Down Expand Up @@ -55,13 +58,13 @@ public AuthorizationTokenInfoResponse requestTokenInfo(AuthorizationTokenRespons
public LoginResponse signUpOrLogin(HttpServletResponse httpServletResponse,
AuthorizationTokenInfoResponse authorizationTokenInfoResponse) {
LoginResponse loginResponse = memberService.login(authorizationTokenInfoResponse);
issueServiceToken(httpServletResponse, loginResponse.id());
issueServiceToken(httpServletResponse, loginResponse.publicClaim());

return loginResponse;
}

private String getAuthorizationCodeUri() {
AuthorizationCodeRequest authorizationCodeRequest = OAuthMapper.toAuthorizationCodeRequest(oAuthConfig);
AuthorizationCodeRequest authorizationCodeRequest = AuthorizationMapper.toAuthorizationCodeRequest(oAuthConfig);
return generateQueryParamsWith(authorizationCodeRequest);
}

Expand Down Expand Up @@ -91,7 +94,8 @@ private void validAuthorizationGrant(String code) {
}

private AuthorizationTokenResponse issueTokenToAuthorizationServer(String code) {
AuthorizationTokenRequest authorizationTokenRequest = OAuthMapper.toAuthorizationTokenRequest(oAuthConfig,
AuthorizationTokenRequest authorizationTokenRequest = AuthorizationMapper.toAuthorizationTokenRequest(
oAuthConfig,
code);
MultiValueMap<String, String> uriParams = generateTokenRequest(authorizationTokenRequest);
ResponseEntity<AuthorizationTokenResponse> authorizationTokenResponse =
Expand All @@ -115,9 +119,14 @@ private MultiValueMap<String, String> generateTokenRequest(AuthorizationTokenReq
return contents;
}

private void issueServiceToken(HttpServletResponse response, Long id) {
response.addHeader("token_type", "Bearer");
response.addCookie(CookieUtils.tokenCookie("access_token", jwtProviderService.provideAccessToken(id)));
response.addCookie(CookieUtils.tokenCookie("refresh_token", jwtProviderService.provideRefreshToken(id)));
public void issueServiceToken(HttpServletResponse response, PublicClaim publicClaim) {
response.addCookie(
CookieUtils.typeCookie("Bearer", tokenConfig.getRefreshExpire()));
response.addCookie(
CookieUtils.tokenCookie("access_token", jwtProviderService.provideAccessToken(publicClaim),
tokenConfig.getRefreshExpire()));
response.addCookie(
CookieUtils.tokenCookie("refresh_token", jwtProviderService.provideRefreshToken(),
tokenConfig.getRefreshExpire()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.moabam.api.dto.AuthorizationMapper;
import com.moabam.api.dto.PublicClaim;
import com.moabam.global.config.TokenConfig;
import com.moabam.global.error.exception.UnauthorizedException;
import com.moabam.global.error.model.ErrorMessage;
Expand All @@ -19,25 +21,25 @@ public class JwtAuthenticationService {

private final TokenConfig tokenConfig;

public boolean isTokenValid(String token) {
public boolean isTokenExpire(String token) {
try {
Jwts.parserBuilder()
.setSigningKey(tokenConfig.getKey())
.build()
.parseClaimsJwt(token);
return true;
} catch (ExpiredJwtException expiredJwtException) {
.parseClaimsJws(token);
return false;
} catch (ExpiredJwtException expiredJwtException) {
return true;
} catch (Exception exception) {
throw new UnauthorizedException(ErrorMessage.AUTHENTICATIE_FAIL);
throw new UnauthorizedException(ErrorMessage.AUTHENTICATE_FAIL);
}
}

public String parseEmail(String token) {
public PublicClaim parseClaim(String token) {
String claims = token.split("\\.")[1];
String decodeClaims = new String(Base64.getDecoder().decode(claims));
JSONObject jsonObject = new JSONObject(decodeClaims);

return (String)jsonObject.get("id");
return AuthorizationMapper.toPublicClaim(jsonObject);
}
}
28 changes: 20 additions & 8 deletions src/main/java/com/moabam/api/application/JwtProviderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

import org.springframework.stereotype.Service;

import com.moabam.api.dto.PublicClaim;
import com.moabam.global.config.TokenConfig;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
Expand All @@ -16,15 +18,27 @@ public class JwtProviderService {

private final TokenConfig tokenConfig;

public String provideAccessToken(long id) {
return generateToken(id, tokenConfig.getAccessExpire());
public String provideAccessToken(PublicClaim publicClaim) {
return generateIdToken(publicClaim, tokenConfig.getAccessExpire());
}

public String provideRefreshToken(long id) {
return generateToken(id, tokenConfig.getRefreshExpire());
public String provideRefreshToken() {
return generateCommonInfo(tokenConfig.getRefreshExpire());
}

private String generateToken(long id, long expireTime) {
private String generateIdToken(PublicClaim publicClaim, long expireTime) {
return commonInfo(expireTime)
.claim("id", publicClaim.id())
.claim("nickname", publicClaim.nickname())
.claim("role", publicClaim.role())
.compact();
}

private String generateCommonInfo(long expireTime) {
return commonInfo(expireTime).compact();
}

private JwtBuilder commonInfo(long expireTime) {
Date issueDate = new Date();
Date expireDate = new Date(issueDate.getTime() + expireTime);

Expand All @@ -34,8 +48,6 @@ private String generateToken(long id, long expireTime) {
.setIssuer(tokenConfig.getIss())
.setIssuedAt(issueDate)
.setExpiration(expireDate)
.claim("id", id)
.signWith(tokenConfig.getKey(), SignatureAlgorithm.HS256)
.compact();
.signWith(tokenConfig.getKey(), SignatureAlgorithm.HS256);
}
}
6 changes: 2 additions & 4 deletions src/main/java/com/moabam/api/application/MemberService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import com.moabam.api.domain.entity.Member;
import com.moabam.api.domain.repository.MemberRepository;
import com.moabam.api.domain.repository.MemberSearchRepository;
import com.moabam.api.domain.repository.NotificationRepository;
import com.moabam.api.dto.AuthorizationTokenInfoResponse;
import com.moabam.api.dto.LoginResponse;
import com.moabam.api.dto.MemberMapper;
Expand All @@ -28,7 +27,6 @@ public class MemberService {

private final MemberRepository memberRepository;
private final MemberSearchRepository memberSearchRepository;
private final NotificationRepository notificationRepository;

public Member getById(Long memberId) {
return memberRepository.findById(memberId)
Expand All @@ -38,9 +36,9 @@ public Member getById(Long memberId) {
@Transactional
public LoginResponse login(AuthorizationTokenInfoResponse authorizationTokenInfoResponse) {
Optional<Member> member = memberRepository.findBySocialId(authorizationTokenInfoResponse.id());
Member loginMember = member.orElse(signUp(authorizationTokenInfoResponse.id()));
Member loginMember = member.orElseGet(() -> signUp(authorizationTokenInfoResponse.id()));

return MemberMapper.toLoginResponse(loginMember.getId(), member.isEmpty());
return MemberMapper.toLoginResponse(loginMember, member.isEmpty());
}

private Member signUp(Long socialId) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/moabam/api/domain/entity/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public class Member extends BaseTimeEntity {
@Builder
private Member(Long id, Long socialId, String nickname, Bug bug) {
this.id = id;
this.socialId = socialId;
this.socialId = requireNonNull(socialId);
this.nickname = requireNonNull(nickname);
this.profileImage = BaseImageUrl.PROFILE_URL;
this.bug = requireNonNull(bug);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.moabam.api.dto;

import org.json.JSONObject;

import com.moabam.api.domain.entity.enums.Role;
import com.moabam.global.config.OAuthConfig;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OAuthMapper {
public final class AuthorizationMapper {

public static AuthorizationCodeRequest toAuthorizationCodeRequest(OAuthConfig oAuthConfig) {
return AuthorizationCodeRequest.builder()
Expand All @@ -25,4 +28,16 @@ public static AuthorizationTokenRequest toAuthorizationTokenRequest(OAuthConfig
.clientSecret(oAuthConfig.client().clientSecret())
.build();
}

public static PublicClaim toPublicClaim(JSONObject jsonObject) {
return PublicClaim.builder()
.id(Long.valueOf(jsonObject.get("id").toString()))
.nickname(jsonObject.getString("nickname"))
.role(jsonObject.getEnum(Role.class, "role"))
.build();
}

public static AuthorizationMember toAuthorizationMember(PublicClaim publicClaim) {
return new AuthorizationMember(publicClaim.id(), publicClaim.nickname(), publicClaim.role());
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/moabam/api/dto/AuthorizationMember.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.moabam.api.dto;

import com.moabam.api.domain.entity.enums.Role;

public record AuthorizationMember(
Long id,
String nickname,
Role role
) {

}
6 changes: 4 additions & 2 deletions src/main/java/com/moabam/api/dto/LoginResponse.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.moabam.api.dto;

import com.fasterxml.jackson.annotation.JsonUnwrapped;

import lombok.Builder;

@Builder
public record LoginResponse(
Long id,
boolean isSignUp
boolean isSignUp,
@JsonUnwrapped PublicClaim publicClaim
) {

}
14 changes: 6 additions & 8 deletions src/main/java/com/moabam/api/dto/MemberMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ public static Member toMember(Long socialId, String nickName) {
.build();
}

public static LoginResponse toLoginResponse(Long memberId) {
public static LoginResponse toLoginResponse(Member member, boolean isSignUp) {
return LoginResponse.builder()
.id(memberId)
.build();
}

public static LoginResponse toLoginResponse(Long memberId, boolean isSignUp) {
return LoginResponse.builder()
.id(memberId)
.publicClaim(PublicClaim.builder()
.id(member.getId())
.nickname(member.getNickname())
.role(member.getRole())
.build())
.isSignUp(isSignUp)
.build();
}
Expand Down
43 changes: 43 additions & 0 deletions src/main/java/com/moabam/api/dto/PathMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.moabam.api.dto;

import static java.util.Objects.*;

import java.util.List;

import org.springframework.http.HttpMethod;

import com.moabam.api.domain.entity.enums.Role;
import com.moabam.global.common.handler.PathResolver;

import jakarta.annotation.Nonnull;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PathMapper {

public static PathResolver.Path parsePath(String uri) {
return parsePath(uri, null, null);
}

public static <T> PathResolver.Path parsePath(String uri, @Nonnull List<T> params) {
if (!params.isEmpty() && params.get(0) instanceof Role) {
return parsePath(uri, (List<Role>)params, null);
}
return parsePath(uri, null, (List<HttpMethod>)params);
}

private static PathResolver.Path parsePath(String uri, List<Role> roles, List<HttpMethod> methods) {
PathResolver.Path.PathBuilder pathBuilder = PathResolver.Path.builder().uri(uri);

if (nonNull(roles)) {
pathBuilder.roles(roles);
}

if (nonNull(methods)) {
pathBuilder.httpMethods(methods);
}

return pathBuilder.build();
}
}
15 changes: 15 additions & 0 deletions src/main/java/com/moabam/api/dto/PublicClaim.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.moabam.api.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.moabam.api.domain.entity.enums.Role;

import lombok.Builder;

@Builder
public record PublicClaim(
Long id,
@JsonIgnore String nickname,
@JsonIgnore Role role
) {

}
12 changes: 6 additions & 6 deletions src/main/java/com/moabam/api/presentation/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.moabam.api.application.AuthenticationService;
import com.moabam.api.application.AuthorizationService;
import com.moabam.api.dto.AuthorizationCodeResponse;
import com.moabam.api.dto.AuthorizationTokenInfoResponse;
import com.moabam.api.dto.AuthorizationTokenResponse;
Expand All @@ -21,21 +21,21 @@
@RequiredArgsConstructor
public class MemberController {

private final AuthenticationService authenticationService;
private final AuthorizationService authorizationService;

@GetMapping
public void socialLogin(HttpServletResponse httpServletResponse) {
authenticationService.redirectToLoginPage(httpServletResponse);
authorizationService.redirectToLoginPage(httpServletResponse);
}

@GetMapping("/login/kakao/oauth")
@ResponseStatus(HttpStatus.OK)
public LoginResponse authorizationTokenIssue(@ModelAttribute AuthorizationCodeResponse authorizationCodeResponse,
HttpServletResponse httpServletResponse) {
AuthorizationTokenResponse tokenResponse = authenticationService.requestToken(authorizationCodeResponse);
AuthorizationTokenResponse tokenResponse = authorizationService.requestToken(authorizationCodeResponse);
AuthorizationTokenInfoResponse authorizationTokenInfoResponse =
authenticationService.requestTokenInfo(tokenResponse);
authorizationService.requestTokenInfo(tokenResponse);

return authenticationService.signUpOrLogin(httpServletResponse, authorizationTokenInfoResponse);
return authorizationService.signUpOrLogin(httpServletResponse, authorizationTokenInfoResponse);
}
}
Loading

0 comments on commit 1700d5a

Please sign in to comment.