[Practice] 사용자 관련 API 만들기 (7)

2021. 4. 19. 01:39Spring/Practice

1. 문제

  • 로그인 시 에러가 발생하는 경우 로그에 기록하는 기능

 

 

 

2. 풀이

- application.yml (Log 파일  설정)

...

logging:
  level:
    org.hibernate.SQL: trace
    org.hibernate.type: trace

  file:
    name: ./logs/spring-jpa.log

- ApiLoginController.java

package com.example.jpa.sample.user.controller;

import com.example.jpa.sample.common.exception.BizException;
import com.example.jpa.sample.common.model.ResponseResult;
import com.example.jpa.sample.notice.model.ResponseError;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.model.UserLogin;
import com.example.jpa.sample.user.model.UserLoginToken;
import com.example.jpa.sample.user.service.UserService;
import com.example.jpa.sample.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Slf4j
@RequiredArgsConstructor
@RestController
public class ApiLoginController {

    private final UserService userService;

    /*
    // 문제 6
    @PostMapping("/api/login")
    public ResponseEntity<?> login(@RequestBody @Valid UserLogin userLogin, Errors errors) {

        if(errors.hasErrors()) {
            return ResponseResult.fail("입력값이 정확하지 않습니다.", ResponseError.of(errors.getAllErrors()));
        }

        User user = null;

        try {
            user = userService.login(userLogin);
        } catch(BizException e) {
            return ResponseResult.fail(e.getMessage());
        }

        UserLoginToken userLoginToken = JwtUtils.createToken(user);
        if(userLoginToken == null) {
            return ResponseResult.fail("JWT 생성에 실패하였습니다.");
        }

        return ResponseResult.success(userLoginToken);
    }
     */

    // 문제 7
    @PostMapping("/api/login")
    public ResponseEntity<?> login(@RequestBody @Valid UserLogin userLogin, Errors errors) {

        log.info("#################################");
        log.info("로그인 함수");

        if(errors.hasErrors()) {
            return ResponseResult.fail("입력값이 정확하지 않습니다.", ResponseError.of(errors.getAllErrors()));
        }

        User user = null;

        try {
            user = userService.login(userLogin);
        } catch(BizException e) {
            log.info("로그인 에러: " + e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }

        UserLoginToken userLoginToken = JwtUtils.createToken(user);
        if(userLoginToken == null) {
            log.info("JWT 생성 에러");
            return ResponseResult.fail("JWT 생성에 실패하였습니다.");
        }

        return ResponseResult.success(userLoginToken);
    }
}
728x90