-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from TeamUStory/feat/naver
Naver 로그인 작업 완료 PR(ver.2)
- Loading branch information
Showing
11 changed files
with
359 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletions
75
src/main/java/com/elice/ustory/global/oauth/naver/NaverController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package com.elice.ustory.global.oauth.naver; | ||
|
||
import com.elice.ustory.domain.user.dto.LoginResponse; | ||
import com.elice.ustory.domain.user.dto.LogoutResponse; | ||
import com.elice.ustory.domain.user.service.UserService; | ||
import com.elice.ustory.global.exception.dto.ErrorResponse; | ||
import io.swagger.v3.oas.annotations.Operation; | ||
import io.swagger.v3.oas.annotations.media.Content; | ||
import io.swagger.v3.oas.annotations.media.Schema; | ||
import io.swagger.v3.oas.annotations.responses.ApiResponse; | ||
import io.swagger.v3.oas.annotations.responses.ApiResponses; | ||
import io.swagger.v3.oas.annotations.tags.Tag; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.stereotype.Controller; | ||
import org.springframework.ui.Model; | ||
import org.springframework.web.bind.annotation.GetMapping; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RequestMethod; | ||
import org.springframework.web.bind.annotation.RequestParam; | ||
|
||
import java.util.HashMap; | ||
|
||
@Tag(name = "NAVER", description = "NAVER OAUTH API") | ||
@Controller | ||
@Slf4j | ||
@RequestMapping | ||
@RequiredArgsConstructor | ||
public class NaverController { | ||
private final NaverOauth naverOauth; | ||
private final NaverService naverService; | ||
private final UserService userService; | ||
|
||
@Operation(summary = "NAVER LOGIN API", description = "네이버 로그인") | ||
@ApiResponses({ | ||
@ApiResponse(responseCode = "200", description = "Ok", content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponse.class))), | ||
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))), | ||
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) | ||
}) | ||
|
||
@RequestMapping(value = "/login/oauth2/code/naver", method = {RequestMethod.GET, RequestMethod.POST}) | ||
public ResponseEntity<LoginResponse> naverLogin(@RequestParam(name = "code") String code, | ||
@RequestParam(name = "state") String state, | ||
HttpServletResponse response) { | ||
String naverAccessToken = naverOauth.getNaverToken(code, state); | ||
HashMap<String, Object> userInfo = naverOauth.getUserInfoFromNaverToken(naverAccessToken); | ||
|
||
String nickname = (String) userInfo.get("nickname"); | ||
String naverEmail = (String) userInfo.get("email"); | ||
|
||
if(!userService.checkExistByEmail(naverEmail)){ | ||
naverService.naverSignUp(nickname, naverEmail); | ||
} | ||
|
||
LoginResponse loginResponse = naverService.naverLogin(naverEmail, response, naverAccessToken); | ||
|
||
log.info("[naverLogin] 네이버 닉네임: {}", nickname); | ||
return ResponseEntity.ok().body(loginResponse); | ||
} | ||
|
||
@Operation(summary = "NAVER LOGOUT API", description = "네이버 로그아웃") | ||
@ApiResponses({ | ||
@ApiResponse(responseCode = "200", description = "Ok", content = @Content(mediaType = "application/json", schema = @Schema(implementation = LogoutResponse.class))), | ||
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))), | ||
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) | ||
}) | ||
@RequestMapping(value = "/auth/logout/naver", method = {RequestMethod.GET, RequestMethod.POST}) | ||
public ResponseEntity<LogoutResponse> naverLogout(HttpServletRequest request) { | ||
LogoutResponse logoutResponse = naverService.naverLogout(request); | ||
return ResponseEntity.ok().body(logoutResponse); | ||
} | ||
} |
89 changes: 89 additions & 0 deletions
89
src/main/java/com/elice/ustory/global/oauth/naver/NaverOauth.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
package com.elice.ustory.global.oauth.naver; | ||
|
||
import com.google.gson.JsonElement; | ||
import com.google.gson.JsonObject; | ||
import com.google.gson.JsonParser; | ||
import lombok.Getter; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.http.HttpEntity; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.HttpMethod; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.LinkedMultiValueMap; | ||
import org.springframework.util.MultiValueMap; | ||
import org.springframework.web.client.RestTemplate; | ||
|
||
import java.nio.charset.StandardCharsets; | ||
import java.util.HashMap; | ||
import java.util.Objects; | ||
|
||
@Slf4j | ||
@Component | ||
@Getter | ||
public class NaverOauth { | ||
@Value("${naver.clientId}") | ||
private String naverClientId; | ||
|
||
@Value("${naver.secret}") | ||
private String naverSecretKey; | ||
|
||
@Value("${naver.loginRedirectUri}") | ||
private String naverLoginRedirectUri; | ||
|
||
@Value("${naver.logoutRedirectUri}") | ||
private String naverLogoutRedirectUri; | ||
|
||
@Value("${naver.tokenUri}") | ||
private String naverTokenUri; | ||
|
||
@Value("${naver.userInfo}") | ||
private String userInfoUri; | ||
|
||
public String getNaverToken(String code, String state){ | ||
RestTemplate restTemplate = new RestTemplate(); | ||
HttpHeaders headers = new HttpHeaders(); | ||
|
||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); | ||
params.add("grant_type", "authorization_code"); | ||
params.add("client_id", naverClientId); | ||
params.add("client_secret", naverSecretKey); | ||
params.add("code", code); | ||
params.add("state", state); | ||
|
||
HttpEntity<MultiValueMap<String, String>> naverTokenRequest = new HttpEntity<>(params, headers); | ||
ResponseEntity<String> response = restTemplate.exchange(naverTokenUri, HttpMethod.POST, naverTokenRequest, String.class); | ||
|
||
String responseBody = response.getBody(); | ||
JsonObject asJsonObject = null; | ||
if(responseBody != null) asJsonObject = JsonParser.parseString(responseBody).getAsJsonObject(); | ||
return asJsonObject.get("access_token").getAsString(); | ||
} | ||
|
||
public HashMap<String, Object> getUserInfoFromNaverToken(String accessToken){ | ||
HashMap<String, Object> userInfo = new HashMap<>(); | ||
|
||
RestTemplate restTemplate = new RestTemplate(); | ||
HttpHeaders headers = new HttpHeaders(); | ||
headers.add("Authorization", "Bearer " + accessToken); | ||
|
||
HttpEntity<MultiValueMap<String, String>> naverUserInfoRequest = new HttpEntity<>(headers); | ||
|
||
ResponseEntity<String> response = restTemplate.exchange(userInfoUri, HttpMethod.POST, naverUserInfoRequest, String.class); | ||
log.info("response = {}", response); | ||
String responseBody = response.getBody(); | ||
if(responseBody != null){ | ||
responseBody = new String(responseBody.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); | ||
} | ||
JsonElement element = JsonParser.parseString(Objects.requireNonNull(responseBody)); | ||
|
||
String nickname = element.getAsJsonObject().get("response").getAsJsonObject().get("nickname").getAsString(); | ||
String email = element.getAsJsonObject().get("response").getAsJsonObject().get("email").getAsString(); | ||
|
||
userInfo.put("nickname", nickname); | ||
userInfo.put("email", email); | ||
|
||
return userInfo; | ||
} | ||
} |
102 changes: 102 additions & 0 deletions
102
src/main/java/com/elice/ustory/global/oauth/naver/NaverService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
package com.elice.ustory.global.oauth.naver; | ||
|
||
import com.elice.ustory.domain.diary.entity.Color; | ||
import com.elice.ustory.domain.diary.entity.Diary; | ||
import com.elice.ustory.domain.diary.entity.DiaryCategory; | ||
import com.elice.ustory.domain.diary.repository.DiaryRepository; | ||
import com.elice.ustory.domain.diaryUser.entity.DiaryUser; | ||
import com.elice.ustory.domain.diaryUser.entity.DiaryUserId; | ||
import com.elice.ustory.domain.diaryUser.repository.DiaryUserRepository; | ||
import com.elice.ustory.domain.user.dto.LoginResponse; | ||
import com.elice.ustory.domain.user.dto.LogoutResponse; | ||
import com.elice.ustory.domain.user.entity.Users; | ||
import com.elice.ustory.domain.user.repository.UserRepository; | ||
import com.elice.ustory.domain.user.service.UserService; | ||
import com.elice.ustory.global.exception.model.NotFoundException; | ||
import com.elice.ustory.global.jwt.JwtTokenProvider; | ||
import com.elice.ustory.global.jwt.JwtUtil; | ||
import com.elice.ustory.global.redis.naver.NaverTokenService; | ||
import com.elice.ustory.global.redis.refresh.RefreshTokenService; | ||
import com.elice.ustory.global.util.RandomGenerator; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.stereotype.Service; | ||
|
||
import java.util.UUID; | ||
|
||
@Service | ||
@Slf4j | ||
@RequiredArgsConstructor | ||
public class NaverService { | ||
private final UserRepository userRepository; | ||
private final DiaryRepository diaryRepository; | ||
private final DiaryUserRepository diaryUserRepository; | ||
private final UserService userService; | ||
private final RefreshTokenService refreshTokenService; | ||
private final NaverTokenService naverTokenService; | ||
private final JwtTokenProvider jwtTokenProvider; | ||
private final JwtUtil jwtUtil; | ||
private final RandomGenerator randomGenerator; | ||
private final PasswordEncoder passwordEncoder; | ||
|
||
public void naverSignUp(String naverNickname, String naverEmail){ | ||
String randomPassword = String.valueOf(UUID.randomUUID()).substring(0,8); | ||
String encodedPassword = passwordEncoder.encode(randomPassword); | ||
String generatedNickname = naverNickname + "#" + randomGenerator.generateRandomPostfix(); | ||
|
||
Users builtUser = Users.addUserBuilder() | ||
.email(naverEmail) | ||
.loginType(Users.LoginType.NAVER) | ||
.name(naverNickname) | ||
.nickname(generatedNickname) | ||
.password(encodedPassword) | ||
.profileImgUrl("") | ||
.profileDescription("자기소개") | ||
.build(); | ||
|
||
userRepository.save(builtUser); | ||
|
||
Diary userDiary = new Diary( | ||
String.format("%s의 다이어리", builtUser.getNickname()), | ||
"기본 DiaryImgUrl", | ||
DiaryCategory.INDIVIDUAL, | ||
String.format("%s의 개인 다이어리", builtUser.getNickname()), | ||
Color.RED | ||
); | ||
diaryRepository.save(userDiary); | ||
diaryUserRepository.save(new DiaryUser(new DiaryUserId(userDiary,builtUser))); | ||
} | ||
|
||
public LoginResponse naverLogin(String naverEmail, HttpServletResponse response, String naverToken){ | ||
Users loginUser = userRepository.findByEmail(naverEmail) | ||
.orElseThrow(() -> new NotFoundException("해당 유저를 찾을 수 없습니다.")); | ||
|
||
String accessToken = jwtTokenProvider.createAccessTokenSocial(loginUser.getId(), naverToken, loginUser.getLoginType()); | ||
String refreshToken = jwtTokenProvider.createRefreshToken(); | ||
|
||
LoginResponse loginResponse = LoginResponse.builder() | ||
.accessToken(accessToken) | ||
.refreshToken(refreshToken) | ||
.build(); | ||
|
||
log.info("[getLogInResult] LogInResponse 객체에 값 주입"); | ||
response.addHeader("Authorization", accessToken); | ||
|
||
refreshTokenService.saveTokenInfo(loginUser.getId(), refreshToken, accessToken, 60 * 60 * 24 * 7); | ||
naverTokenService.saveNaverTokenInfo(loginUser.getId(), naverToken, accessToken); | ||
|
||
log.info("[logIn] 정상적으로 로그인되었습니다. id : {}, token : {}", loginUser.getId(), loginResponse.getAccessToken()); | ||
return loginResponse; | ||
} | ||
|
||
public LogoutResponse naverLogout(HttpServletRequest request) { | ||
String accessToken = jwtUtil.getTokenFromRequest(request); | ||
naverTokenService.removeNaverTokenInfo(accessToken); | ||
userService.logout(request); | ||
|
||
return LogoutResponse.builder().success(true).build(); | ||
} | ||
} |
Oops, something went wrong.