Skip to content

Commit

Permalink
#25 사용자 로그인 API 기능 추가
Browse files Browse the repository at this point in the history
 - /api/userLogin 추가
 - 로그인 대상 정보 확인 및 토큰 발행
 - 로그인 유지여부 상태 업데이트 처리
  • Loading branch information
developer-Fwa committed May 23, 2022
1 parent 7b8a7a4 commit a2e4aad
Show file tree
Hide file tree
Showing 13 changed files with 287 additions and 41 deletions.
4 changes: 4 additions & 0 deletions src/main/java/kr/co/hconnect/common/ApiResponseCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ public enum ApiResponseCode {
* 격리상태 내역이 존재하지 않는 경우
*/
NOT_FOUND_QUARANTINE_INFO("14"),
/**
* 사용자 정보가 존재하지 않는 경우
*/
NOT_FOUND_USER_INFO("15"),

/**
* 내원중인 격리/입소내역이 존재하지 않는 경우
Expand Down
30 changes: 15 additions & 15 deletions src/main/java/kr/co/hconnect/controller/LoginController.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package kr.co.hconnect.controller;

import kr.co.hconnect.service.UserService;
import kr.co.hconnect.vo.LoginVO;
import kr.co.hconnect.vo.SessionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -14,6 +12,7 @@
/**
* 로그인 컨트롤러
*/
@Deprecated
@Controller
@RequestMapping("/login")
public class LoginController {
Expand Down Expand Up @@ -48,20 +47,21 @@ public ModelAndView checkLogin(@RequestParam(value = "userId") String userId
, @RequestParam(value = "password") String password
, HttpServletRequest request) {

// 로그인 정보 조회
LoginVO loginVO = service.selectLoginInfo(userId, password);
// 로그인 사용자 정보 세션에 설정
if (loginVO.getUserVO() != null) {
SessionVO sessionVO = new SessionVO();
sessionVO.setUserId(loginVO.getUserVO().getUserId());
sessionVO.setUserNm(loginVO.getUserVO().getUserNm());
sessionVO.setCenterId(loginVO.getUserVO().getCenterId());
request.getSession().setAttribute("sessionVO", sessionVO);
}
// // 로그인 정보 조회
// LoginVO loginVO = service.selectLoginInfo(userId, password);
//
// // 로그인 사용자 정보 세션에 설정
// if (loginVO.getUserVO() != null) {
// SessionVO sessionVO = new SessionVO();
// sessionVO.setUserId(loginVO.getUserVO().getUserId());
// sessionVO.setUserNm(loginVO.getUserVO().getUserNm());
// sessionVO.setCenterId(loginVO.getUserVO().getCenterId());
// request.getSession().setAttribute("sessionVO", sessionVO);
// }
//
ModelAndView mv = new ModelAndView("jsonView");
mv.addObject("loginFailMessage", loginVO.getFailMessage()); // 로그인 실패 사유
// mv.addObject("loginFailMessage", loginVO.getFailMessage()); // 로그인 실패 사유
mv.addObject("loginFailMessage", ""); // 로그인 실패 사유
return mv;
}

Expand Down
42 changes: 42 additions & 0 deletions src/main/java/kr/co/hconnect/domain/UserLoginInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package kr.co.hconnect.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;

/**
* 사용자 로그인 정보
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
public class UserLoginInfo implements Serializable {

private static final long serialVersionUID = -1773620410222057699L;

/**
* 아이디
*/
@NotNull(message = "{validation.null.loginId}")
private String loginId;

/**
* 비밀번호
*/
@NotNull(message = "{validation.null.password}")
@Size(max = 20, message = "{validation.size.password}")
private String password;

/**
* 로그인 유지 여부
*/
@Pattern(regexp = "^[YN]$")
private String rememberYn;
}
23 changes: 23 additions & 0 deletions src/main/java/kr/co/hconnect/domain/UserLoginResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package kr.co.hconnect.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
* 로그인 응답 정보
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
public class UserLoginResponse extends BaseResponse {

private static final long serialVersionUID = -2461380484928982120L;

/**
* AccessToken
*/
private String token;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package kr.co.hconnect.exception;

/**
* 사용자 정보 미존재 Exception
*/
public class NotFoundUserInfoException extends RuntimeException {

private static final long serialVersionUID = 2009383189724700722L;

/**
* 오류 내역
*/
private final String errorMessage;

public NotFoundUserInfoException(String errorMessage) {
this.errorMessage = errorMessage;
}

@Override
public String getMessage() {
return errorMessage;
}
}
24 changes: 24 additions & 0 deletions src/main/java/kr/co/hconnect/jwt/TokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.jsonwebtoken.*;
import kr.co.hconnect.common.TokenStatus;
import kr.co.hconnect.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -60,9 +61,32 @@ public String createToken() {
.setIssuedAt(now) // 발급시간
.setExpiration(validityInterval) // 만료시간
.signWith(key, keyAlg) // 키정보 및 해싱 알고리즘 정보
.claim("tokenType", "app")
.compact();
}

/**
* web 사용자 토큰 생성
*
* @return 토큰 정보
*/
public String createUserToken(UserVO userVO) {
Date now = new Date();
// 토큰 만료시간
Date validityInterval = new Date(now.getTime() + this.validity);

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE) // 헤더 타입 지정
.setIssuer("HealthConnect") // 발급자 정보
.setIssuedAt(now) // 발급시간
.setExpiration(validityInterval) // 만료시간
.signWith(key, keyAlg) // 키정보 및 해싱 알고리즘 정보
.claim("tokenType", "web")
.claim("userId", userVO.getUserId())
.claim("userNm", userVO.getUserNm())
.compact();
}

/**
* 토큰 유효성 확인
*
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/kr/co/hconnect/repository/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ public void updateUser(UserVO vo) {
update("kr.co.hconnect.sqlmapper.updateUser",vo);
}

/**
* 로그인 정보 업데이트
* @param vo UserVO
*/
public void updateUserLoginInfo(UserVO vo) {
update("kr.co.hconnect.sqlmapper.updateUserLoginInfo", vo);
}

/**
*유저정보 삭제
* @param userId 유저Id
Expand Down
79 changes: 79 additions & 0 deletions src/main/java/kr/co/hconnect/rest/UserLoginRestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package kr.co.hconnect.rest;

import kr.co.hconnect.common.ApiResponseCode;
import kr.co.hconnect.domain.UserLoginInfo;
import kr.co.hconnect.domain.UserLoginResponse;
import kr.co.hconnect.exception.InvalidRequestArgumentException;
import kr.co.hconnect.exception.NotFoundUserInfoException;
import kr.co.hconnect.exception.NotMatchPatientPasswordException;
import kr.co.hconnect.jwt.TokenProvider;
import kr.co.hconnect.service.UserService;
import kr.co.hconnect.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserLoginRestController {

private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginRestController.class);

private final TokenProvider tokenProvider;

/**
* 사용자 서비스
*/
private final UserService userService;

/**
* 생성자
* @param tokenProvider Token 관리
* @param userService 사용자 서비스
*/
public UserLoginRestController(TokenProvider tokenProvider, UserService userService) {
this.tokenProvider = tokenProvider;
this.userService = userService;
}

/**
* 로그인 정보 확인
*/
@RequestMapping(value="/userLogin", method = RequestMethod.POST)
public UserLoginResponse checkLogin(@Valid @RequestBody UserLoginInfo userLoginInfo, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new InvalidRequestArgumentException(bindingResult);
}

UserLoginResponse userLoginResponse = new UserLoginResponse();

try {
// 로그인 정보 조회
UserVO userVO = userService.selectLoginInfo(userLoginInfo);

// 사용자 로그인 정보 업데이트
userVO.setRememberYn(userLoginInfo.getRememberYn());
userService.updateUserLoginInfo(userVO);

// Token 발행
String token = tokenProvider.createUserToken(userVO);

userLoginResponse.setCode(ApiResponseCode.SUCCESS.getCode());
userLoginResponse.setMessage("로그인 성공");
userLoginResponse.setToken(token);
} catch (NotFoundUserInfoException e) {
userLoginResponse.setCode(ApiResponseCode.NOT_FOUND_USER_INFO.getCode());
userLoginResponse.setMessage(e.getMessage());
} catch (NotMatchPatientPasswordException e) {
userLoginResponse.setCode(ApiResponseCode.NOT_MATCH_PATIENT_PASSWORD.getCode());
userLoginResponse.setMessage(e.getMessage());
}

return userLoginResponse;
}

}
Loading

0 comments on commit a2e4aad

Please sign in to comment.