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: 소셜 로그인 마이그레이션 #255

Merged
merged 4 commits into from
Nov 1, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.codiary.backend.domain.member.controller;

import com.codiary.backend.domain.member.dto.response.MemberResponseDTO;
import com.codiary.backend.domain.member.dto.response.Oauth2ResponseDTO;
import com.codiary.backend.domain.member.service.SocialLoginService;
import com.codiary.backend.global.apiPayload.ApiResponse;
import com.codiary.backend.global.apiPayload.code.status.SuccessStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("api/v2/oauth")
@Tag(name = "Social Login API", description = "소셜 로그인 관련 API입니다.")
public class SocialLoginController {

private final SocialLoginService socialLoginService;

@GetMapping("/login/kakao_url")
@Operation(summary = "카카오 로그인 url 요청")
public ApiResponse<Oauth2ResponseDTO> kakaoLogin() {
String url = socialLoginService.getKakaoRedirectUrl();
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, new Oauth2ResponseDTO(url));
}

@PostMapping("/login/kakao")
@Operation(summary = "카카오로 로그인")
public ApiResponse<MemberResponseDTO.MemberTokenResponseDTO> kakaoToken(@RequestParam String code) {
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, socialLoginService.kakaoLogin(code));
}

@GetMapping("/login/naver_url")
@Operation(summary = "네이버 로그인 url 요청")
public ApiResponse<Oauth2ResponseDTO> naverLogin() {
String url = socialLoginService.getNaverRedirectUrl();
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, new Oauth2ResponseDTO(url));
}

@PostMapping("/login/naver")
@Operation(summary = "네이버로 로그인")
public ApiResponse<MemberResponseDTO.MemberTokenResponseDTO> naverToken(
@RequestParam String code,
@RequestParam String state
) {
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, socialLoginService.naverLogin(code, state));
}

@GetMapping("/login/github_url")
@Operation(summary = "깃허브 로그인 url 요청")
public ApiResponse<Oauth2ResponseDTO> githubLogin() {
String url = socialLoginService.getGithubRedirectUrl();
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, new Oauth2ResponseDTO(url));
}

@PostMapping("/login/github")
@Operation(summary = "깃허브로 로그인")
public ApiResponse<MemberResponseDTO.MemberTokenResponseDTO> githubToken(@RequestParam String code) {
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, socialLoginService.githubLogin(code));
}

@GetMapping("/login/google_url")
@Operation(summary = "구글 로그인 url 요청")
public ApiResponse<Oauth2ResponseDTO> googleLogin() {
String url = socialLoginService.getGoogleRedirectUrl();
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, new Oauth2ResponseDTO(url));
}

@PostMapping("/login/google")
@Operation(summary = "구글로 로그인")
public ApiResponse<MemberResponseDTO.MemberTokenResponseDTO> googleToken(@RequestParam String code) {
return ApiResponse.onSuccess(SuccessStatus.MEMBER_OK, socialLoginService.googleLogin(code));
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.codiary.backend.domain.member.repository;

import com.codiary.backend.domain.member.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -173,10 +175,12 @@ public MemberResponseDTO.MemberTokenResponseDTO googleLogin(String code) {
.tokenInfo(tokenInfo)
.memberId(member.getMemberId())
.build();

}

private String getGoogleToken(String codeString) {
// %2F -> / 로 변환해주지 않으면 오류 발생
codeString = URLDecoder.decode(codeString, StandardCharsets.UTF_8);

String path = "https://oauth2.googleapis.com/token";
String clientId = "?client_id=" + googleClientId;
String clientSecret = "&client_secret=" + googleClientSecret;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.codiary.backend.global.jwt.EmailPasswordAuthenticationFilter;
import com.codiary.backend.global.jwt.JwtAuthenticationFilter;
import com.codiary.backend.global.jwt.JwtTokenProvider;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -16,8 +17,6 @@
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
Expand Down Expand Up @@ -51,6 +50,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
authorize -> authorize
// Member 관련 접근
.requestMatchers("/api/v2/auth/**").permitAll()
.requestMatchers("/api/v2/oauth/**").permitAll()
// Post 관련 접근
.requestMatchers("/api/v2/post/search").permitAll()
// Comment 관련 접근
Expand Down
15 changes: 10 additions & 5 deletions src/main/java/com/codiary/backend/global/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package com.codiary.backend.global.jwt;

import com.codiary.backend.domain.member.security.CustomMemberDetailsService;
import io.jsonwebtoken.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Date;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -16,10 +24,6 @@
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.security.Key;
import java.util.Date;
import java.util.stream.Collectors;

@Slf4j
@Component
public class JwtTokenProvider { // 토큰 제작 & 토큰으로 유저 정보 제공
Expand Down Expand Up @@ -97,6 +101,7 @@ public TokenInfo generateToken(String email, Long memberId) {
.grantType(BEARER_TYPE)
.accessToken(accessToken)
.refreshToken(refreshToken)
.refreshTokenExpirationTime(new Date(now + REFRESH_TOKEN_EXPIRE_TIME))
.build();
}

Expand Down