rest controller practice : 로그인, jwt생성

This commit is contained in:
haerong22
2021-03-15 19:37:45 +09:00
parent 895ef4732d
commit 0e7bfbf018
6 changed files with 92 additions and 16 deletions

View File

@@ -1,6 +1,8 @@
package com.example.restcontroller;
import com.example.restcontroller.board.exception.BoardTypeNotFoundException;
import com.example.restcontroller.common.exception.BizException;
import com.example.restcontroller.common.model.ResponseResult;
import com.example.restcontroller.notice.exception.AlreadyDeletedException;
import com.example.restcontroller.notice.exception.DuplicateNoticeException;
import com.example.restcontroller.notice.exception.NoticeNotFoundException;
@@ -22,9 +24,10 @@ public class GlobalExceptionHandler {
UserNotFoundException.class,
ExistsEmailException.class,
PasswordNotMatchException.class,
BoardTypeNotFoundException.class })
BoardTypeNotFoundException.class,
BizException.class })
public ResponseEntity<?> badRequest(RuntimeException e) {
return new ResponseEntity<>(ResponseMessage.fail(e.getMessage()), HttpStatus.BAD_REQUEST);
return ResponseResult.fail(e.getMessage());
}
@ExceptionHandler(DataIntegrityViolationException.class)
@@ -39,6 +42,6 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exception(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.OK);
return ResponseResult.fail(e.getMessage());
}
}

View File

@@ -1,17 +1,18 @@
package com.example.restcontroller.common.model;
import com.example.restcontroller.board.entity.BoardReport;
import com.example.restcontroller.board.model.ServiceResult;
import com.example.restcontroller.user.model.ResponseMessage;
import org.springframework.http.ResponseEntity;
import java.util.List;
public class ResponseResult {
public static ResponseEntity<?> fail(String message) {
return ResponseEntity.badRequest().body(ResponseMessage.fail(message));
return fail(message, null);
}
public static <T> ResponseEntity<?> fail(String message, T data) {
return ResponseEntity.badRequest().body(ResponseMessage.fail(message, data));
}
public static ResponseEntity<?> success() {

View File

@@ -0,0 +1,39 @@
package com.example.restcontroller.user.controller;
import com.example.restcontroller.common.exception.BizException;
import com.example.restcontroller.common.model.ResponseResult;
import com.example.restcontroller.notice.model.ResponseError;
import com.example.restcontroller.user.entity.User;
import com.example.restcontroller.user.model.UserLogin;
import com.example.restcontroller.user.model.UserLoginToken;
import com.example.restcontroller.user.service.UserService;
import com.example.restcontroller.util.JWTUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
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;
@RestController
@RequiredArgsConstructor
public class ApiLoginController {
private final UserService userService;
@PostMapping("/api/login")
public ResponseEntity<?> chapter4_1(@RequestBody @Valid UserLogin userLogin, BindingResult bindingResult) {
if (bindingResult.hasFieldErrors()) {
return ResponseResult.fail("입력값이 정확하지 않습니다.", ResponseError.of(bindingResult.getFieldErrors()));
}
User user = userService.login(userLogin);
UserLoginToken userLoginToken = JWTUtils.createToken(user)
.orElseThrow(() -> new BizException("JWT 생성에 실패하였습니다."));
return ResponseResult.success(userLoginToken);
}
}

View File

@@ -1,10 +1,8 @@
package com.example.restcontroller.user.service;
import com.example.restcontroller.board.model.ServiceResult;
import com.example.restcontroller.user.model.UserNoticeCount;
import com.example.restcontroller.user.model.UserLogCount;
import com.example.restcontroller.user.model.UserResponse;
import com.example.restcontroller.user.model.UserSummary;
import com.example.restcontroller.user.entity.User;
import com.example.restcontroller.user.model.*;
import java.util.List;
@@ -23,4 +21,6 @@ public interface UserService {
ServiceResult addInterestUser(Long id, String email);
ServiceResult deleteInterestUser(Long id, String email);
User login(UserLogin userLogin);
}

View File

@@ -2,16 +2,15 @@ package com.example.restcontroller.user.service;
import com.example.restcontroller.board.model.ServiceResult;
import com.example.restcontroller.common.exception.BizException;
import com.example.restcontroller.user.entity.User;
import com.example.restcontroller.user.entity.UserInterest;
import com.example.restcontroller.user.entity.UserStatus;
import com.example.restcontroller.user.model.UserNoticeCount;
import com.example.restcontroller.user.model.UserLogCount;
import com.example.restcontroller.user.model.UserResponse;
import com.example.restcontroller.user.model.UserSummary;
import com.example.restcontroller.user.model.*;
import com.example.restcontroller.user.repository.UserCustomRepository;
import com.example.restcontroller.user.repository.UserInterestRepository;
import com.example.restcontroller.user.repository.UserRepository;
import com.example.restcontroller.util.PasswordUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -131,4 +130,17 @@ public class UserServiceImpl implements UserService {
userInterestRepository.delete(userInterestEntity);
return ServiceResult.success();
}
@Override
public User login(UserLogin userLogin) {
User userEntity = userRepository.findByEmail(userLogin.getEmail())
.orElseThrow(() -> new BizException("회원 정보가 존재하지 않습니다."));
if (!PasswordUtils.equalPassword(userLogin.getPassword(), userEntity.getPassword())) {
throw new BizException("일치하는 정보가 없습니다.");
}
return userEntity;
}
}

View File

@@ -5,14 +5,35 @@ import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.example.restcontroller.common.model.ResponseResult;
import com.example.restcontroller.user.entity.User;
import com.example.restcontroller.user.exception.PasswordNotMatchException;
import com.example.restcontroller.user.model.UserLoginToken;
import lombok.experimental.UtilityClass;
import org.springframework.security.crypto.bcrypt.BCrypt;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Optional;
@UtilityClass
public class JWTUtils {
private final String KEY = "kim";
private static final String KEY = "kim";
private static final String CLAIM_USER_ID = "user_id";
public static Optional<UserLoginToken> createToken(User user) {
String token = JWT.create()
.withExpiresAt(Timestamp.valueOf(LocalDateTime.now().plusMinutes(30)))
.withClaim(CLAIM_USER_ID, user.getId())
.withSubject(user.getEmail())
.withIssuer(user.getEmail())
.sign(Algorithm.HMAC512("kim".getBytes()));
return Optional.of(UserLoginToken.builder()
.token(token)
.build());
}
public static String getIssuer(String token) {
return JWT.require(Algorithm.HMAC512(KEY.getBytes()))