Skip to content

Commit

Permalink
feat : Auth 모듈 구현
Browse files Browse the repository at this point in the history
* Controller를 통해 경로마다 함수 라우팅 하고 Service를 통해 세부 로직 구현
* TypeScript의 기존 로직과 동일
* WebClient를 통해 액세스 토큰 받아옴
* 시간이 매우 걸려 개선의 여지가 많음
  • Loading branch information
sk000801 committed Mar 11, 2024
1 parent 94963dd commit 2a5f834
Show file tree
Hide file tree
Showing 2 changed files with 187 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package catchytape.spring.auth.controller;

import org.springframework.web.bind.annotation.RestController;

import catchytape.spring.auth.controller.dto.UserSignupRequest;
import catchytape.spring.auth.controller.dto.UserAuthResponse;
import catchytape.spring.auth.controller.dto.UserLoginRequest;
import catchytape.spring.auth.controller.dto.UserRefreshRequest;
import catchytape.spring.auth.service.AuthService;
import catchytape.spring.auth.service.RedisService;
import catchytape.spring.common.exception.CatchyException;
import catchytape.spring.recentPlayed.RecentPlayed;
import catchytape.spring.user.User;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/users")
public class AuthController {

private final AuthService authService;

@PostMapping(value="/signup", consumes="application/json;charset=UTF-8")
public ResponseEntity<UserAuthResponse> signup(@RequestBody UserSignupRequest request) throws CatchyException{
log.info("POST /users/signup - body = nickname: " + request.nickname());

return ResponseEntity.ok(authService.signup(request.idToken(), request.nickname()));
}

@PostMapping(value="/login", consumes="application/json;charset=UTF-8")
public ResponseEntity<UserAuthResponse> login(@RequestBody UserLoginRequest request) throws CatchyException {
log.info("POST /users/signup - body = idToken: ");

return ResponseEntity.ok(authService.login(request.idToken()));
}

@PostMapping(value="/refresh", consumes="application/json;charset=UTF-8")
public ResponseEntity<UserAuthResponse> refresh(@RequestBody UserRefreshRequest request) throws CatchyException {
log.info("POST /users/refresh - body = refreshToken: ", request.refreshToken());

return ResponseEntity.ok(this.authService.refreshToken(request.refreshToken()));
}

@GetMapping("/test")
public ResponseEntity<User> test() throws CatchyException {
return ResponseEntity.ok(this.authService.test());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package catchytape.spring.auth.service;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;

import catchytape.spring.auth.controller.dto.UserAuthResponse;
import catchytape.spring.auth.service.dto.GoogleTokenResponse;
import catchytape.spring.common.exception.CatchyException;
import catchytape.spring.user.User;
import catchytape.spring.user.UserRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.UUID;

@Slf4j
@Service
@AllArgsConstructor
@Transactional
public class AuthService {
private final RedisService redisService;
private final JwtService jwtService;
private final UserRepository userRepository;

public String getUserEmail(String googleIdToken) throws CatchyException {
String googleApiUrl = "https://oauth2.googleapis.com/tokeninfo?id_token="+googleIdToken;

try {
WebClient client = WebClient.create();
GoogleTokenResponse response = client.get()
.uri(googleApiUrl)
.retrieve()
.bodyToMono(GoogleTokenResponse.class)
.block();

if(response.email() == null) {
throw new CatchyException("UNAUTHORIZED", "EXPIRED_TOKEN");
}

return response.email();

} catch(Exception e) {
if(e instanceof CatchyException) {
throw e;
}

throw new CatchyException("INTERNAL_SERVER_ERROR", "SERVER_ERROR");
}
}

public UserAuthResponse login(String userEmail) throws CatchyException {
try {
User user = this.userRepository.findByUserEmail(userEmail);

if(user == null) {
throw new CatchyException("UNAUTHORIZED", "NOT_EXIST_USER");
}

String userId = user.getUserId();
String refreshId = UUID.randomUUID().toString();
this.redisService.setValue(refreshId, userId);

return this.jwtService.generateJwtToken(userId, refreshId);
} catch(Exception e) {
if(e instanceof CatchyException) {
throw e;
}

throw new CatchyException("INTERNAL_SERVER_ERROR", "SERVER_ERROR");
}
}

public UserAuthResponse signup(String googleIdToken, String nickname) throws CatchyException {
try {
String userEmail = this.getUserEmail(googleIdToken);

if(this.userRepository.findByUserEmail(userEmail) != null) {
throw new CatchyException("BAD_REQUEST", "ALREADY_EXIST_EMAIL");
}

String userId = UUID.randomUUID().toString();
User newUser = new User(userId, nickname, userEmail);
this.userRepository.save(newUser);

return this.login(userEmail);
} catch(Exception e) {
if(e instanceof CatchyException) {
throw e;
}

throw new CatchyException("INTERNAL_SERVER_ERROR", "SERVER_ERROR");
}
}

public UserAuthResponse refreshToken(String refreshToken) throws CatchyException {
try {
this.jwtService.isValidToken(refreshToken);

String refreshId = this.jwtService.decodeToken("refresh_id", refreshToken);

String userId = this.redisService.getValue(refreshId);

if(userId == null) {
throw new CatchyException("UNAUTHORIZED", "NOT_EXIST_USER");
}

String newRefreshId = UUID.randomUUID().toString();
this.redisService.deleteValue(refreshId);
this.redisService.setValue(newRefreshId, userId);

return this.jwtService.generateJwtToken(userId, newRefreshId);
} catch(Exception e) {
if(e instanceof CatchyException) {
throw e;
}

throw new CatchyException("INTERNAL_SERVER_ERROR", "SERVER_ERROR");
}
}

public User test() {
User user = this.userRepository.findByUserEmail("[email protected]");
return user;
}
}

0 comments on commit 2a5f834

Please sign in to comment.