컨트롤러


    @PostMapping("/signup")
    public ApiResult signup(@RequestBody SignupRequestDto requestDto) {
        userService.signup(requestDto);
        return new ApiResult("회원가입 성공", HttpStatus.OK.value());
    }

    @PostMapping("/login")
    public ApiResult login(@RequestBody LoginRequestDto requestDto, HttpServletResponse response) {
        userService.login(requestDto, response);
        return new ApiResult("로그인 성공", HttpStatus.OK.value());
    }
}

 

서비스

    public void signup(SignupRequestDto requestDto) {
        String username = requestDto.getUsername();
        String password = requestDto.getPassword();
        String role = requestDto.getRole();

        // 회원 중복 확인
        Optional<User> found = userRepository.findByUsername(username);
        if (found.isPresent()) {
            throw new HanghaeBlogException(HanghaeBlogErrorCode.IN_USED_USERNAME, null);
        }

        User userEntity = new User(username, password, role);
        userRepository.save(userEntity);
    }​
    public void login(LoginRequestDto requestDto, HttpServletResponse response) {
        String username = requestDto.getUsername();
        String password = requestDto.getPassword();

        User user = userRepository.findByUsername(username).orElseThrow(
                () -> new HanghaeBlogException(HanghaeBlogErrorCode.NOT_FOUND_USER, null)
        );

        if (!user.getPassword().equals(password)) {
            throw new HanghaeBlogException(HanghaeBlogErrorCode.WRONG_PASSWORD, null);
        }

        response.addHeader(JwtUtil.AUTHORIZATION_HEADER, jwtUtil.createToken(user.getUsername()));
    }

 

 

JWT에서 유저 정보 조회

    public User checkToken(HttpServletRequest request) {

        String token = this.resolveToken(request);
        Claims claims;

        User userEntity = null;

        if (token != null) {
            if (this.validateToken(token)) {
                // 토큰에서 사용자 정보 가져오기
                claims = this.getUserInfoFromToken(token);

            } else {
                throw new HanghaeBlogException(HanghaeBlogErrorCode.INVALID_TOKEN, null);
            }

            // 토큰에서 가져온 사용자 정보를 사용하여 DB 조회
            userEntity = userRepository.findByUsername(claims.getSubject()).orElseThrow(
                    () -> new HanghaeBlogException(HanghaeBlogErrorCode.NOT_FOUND_USER, null)
            );
        }
        return userEntity;
    }

'TIL > WEEK7' 카테고리의 다른 글

영속성 전이 Cascade  (0) 2023.06.29
개인과제 글 수정 기능 구현  (0) 2023.06.27
쿠키, 세션, 토큰, JWT  (0) 2023.06.26

+ Recent posts