Merge remote-tracking branch 'origin/devs/ums' into main-design-layout
# Conflicts: # src/main/resources/templates/views/apps/login/login.html
This commit is contained in:
@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
@Component
|
||||
@@ -18,6 +19,12 @@ public class AuthNumberGenerator {
|
||||
}
|
||||
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
log.warn("가상 인증코드 활성화 상태 - {}", portalProperties.getAuthVirtualCode());
|
||||
}
|
||||
|
||||
|
||||
public String generateAuthNumber() {
|
||||
if (StringUtils.hasLength(portalProperties.getAuthVirtualCode())) {
|
||||
log.info("가상 인증코드 활성화 상태 - {}", portalProperties.getAuthVirtualCode());
|
||||
|
||||
@@ -22,10 +22,10 @@ public class AuthNumberServiceImpl implements AuthNumberService {
|
||||
private final AuthNumberGenerator generator;
|
||||
private final MessageSender messageSender;
|
||||
|
||||
@Value("${auth-ttl:300}")
|
||||
@Value("${portal.auth-ttl:300}")
|
||||
private int authNumberExpirationTime;
|
||||
|
||||
@Value("${auth.resend.limit.seconds:30}")
|
||||
@Value("${portal.auth.resend_limit_seconds:30}")
|
||||
private int resendLimitSeconds;
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -39,7 +39,6 @@ public class MessageSender {
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported message type: " + msgType);
|
||||
}
|
||||
|
||||
messageHandlerService.publishEvent(code, recipient, params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ public class AccountController {
|
||||
private final UserFacade userFacade;
|
||||
private final OrgRegisterFacade orgRegisterFacade;
|
||||
private final AgreementsFacade agreementsFacade;
|
||||
private final com.eactive.apim.portal.apps.user.facade.AuthFacade authFacade;
|
||||
|
||||
|
||||
@PostMapping("/confirm_password")
|
||||
@@ -326,4 +327,115 @@ public class AccountController {
|
||||
return "redirect:/mypage";
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/mypage/verification-email")
|
||||
public String showVerificationEmailPage(Model model) {
|
||||
try {
|
||||
// 현재 로그인한 사용자 정보 가져오기
|
||||
PortalAuthenticatedUser currentUser = SecurityUtil.getPortalAuthenticatedUser();
|
||||
|
||||
if (currentUser == null) {
|
||||
return "redirect:/login";
|
||||
}
|
||||
|
||||
// 사용자 이메일 주소를 모델에 추가
|
||||
model.addAttribute("email", currentUser.getUsername());
|
||||
model.addAttribute("userId", currentUser.getId());
|
||||
|
||||
return "apps/mypage/verificationEmail";
|
||||
} catch (Exception e) {
|
||||
logger.error("이메일 인증 페이지 로드 실패", e);
|
||||
return "redirect:/";
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/mypage/send-verification-code")
|
||||
public ResponseEntity<ValidationResponse> sendVerificationCode(
|
||||
@org.springframework.web.bind.annotation.RequestBody java.util.Map<String, String> request,
|
||||
HttpSession session) {
|
||||
try {
|
||||
String email = request.get("email");
|
||||
|
||||
// 현재 로그인한 사용자의 이메일과 일치하는지 확인
|
||||
PortalAuthenticatedUser currentUser = SecurityUtil.getPortalAuthenticatedUser();
|
||||
if (currentUser == null || !currentUser.getUsername().equals(email)) {
|
||||
ValidationResponse response = new ValidationResponse();
|
||||
response.setValid(false);
|
||||
response.setMessage("유효하지 않은 요청입니다.");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
// 이전 세션 데이터 정리
|
||||
session.removeAttribute("emailVerified");
|
||||
|
||||
// 이메일 인증 코드 발송
|
||||
ValidationResponse response = authFacade.requestAuth(email, "EMAIL");
|
||||
|
||||
if (response.isValid()) {
|
||||
session.setAttribute("verificationEmail", email);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("이메일 인증 코드 발송 실패", e);
|
||||
ValidationResponse response = new ValidationResponse();
|
||||
response.setValid(false);
|
||||
response.setMessage("인증 코드 발송에 실패했습니다.");
|
||||
return ResponseEntity.status(500).body(response);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/mypage/verify-email-code")
|
||||
public ResponseEntity<ValidationResponse> verifyEmailCode(
|
||||
@org.springframework.web.bind.annotation.RequestBody java.util.Map<String, String> request,
|
||||
HttpSession session) {
|
||||
try {
|
||||
String email = request.get("email");
|
||||
String code = request.get("code");
|
||||
|
||||
// 현재 로그인한 사용자의 이메일과 일치하는지 확인
|
||||
PortalAuthenticatedUser currentUser = SecurityUtil.getPortalAuthenticatedUser();
|
||||
if (currentUser == null || !currentUser.getUsername().equals(email)) {
|
||||
ValidationResponse response = new ValidationResponse();
|
||||
response.setValid(false);
|
||||
response.setMessage("유효하지 않은 요청입니다.");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
// 세션에 저장된 이메일과 일치하는지 확인
|
||||
String sessionEmail = (String) session.getAttribute("verificationEmail");
|
||||
if (sessionEmail == null || !sessionEmail.equals(email)) {
|
||||
ValidationResponse response = new ValidationResponse();
|
||||
response.setValid(false);
|
||||
response.setMessage("인증 요청된 이메일과 일치하지 않습니다.");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
// 인증 코드 확인
|
||||
ValidationResponse response = authFacade.verifyAuthNumber(email, code);
|
||||
|
||||
if (response.isValid()) {
|
||||
session.setAttribute("emailVerified", true);
|
||||
|
||||
// 사용자 상태를 ACTIVE로 변경
|
||||
userFacade.activateUserByEmail(email);
|
||||
|
||||
// 이메일 인증 관련 세션 정보 제거
|
||||
session.removeAttribute("emailVerificationRequired");
|
||||
session.removeAttribute("redirectUrl");
|
||||
|
||||
logger.info("이메일 인증 완료: {}", email);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("이메일 인증 코드 확인 실패", e);
|
||||
ValidationResponse response = new ValidationResponse();
|
||||
response.setValid(false);
|
||||
response.setMessage("인증 코드 확인에 실패했습니다.");
|
||||
return ResponseEntity.status(500).body(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@ package com.eactive.apim.portal.apps.user.dto;
|
||||
import com.eactive.apim.portal.common.validator.AuthNumberMatch;
|
||||
import com.eactive.apim.portal.common.validator.CellPhone;
|
||||
import com.eactive.apim.portal.common.validator.PasswordMatch;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRule;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKbank;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKjbank;
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Length;
|
||||
import org.hibernate.validator.constraints.NotEmpty;
|
||||
@@ -13,7 +12,7 @@ import org.hibernate.validator.constraints.NotEmpty;
|
||||
@AuthNumberMatch(recipient = "loginId", authField = "authNumber")
|
||||
@PasswordMatch(input = "password", confirm = "password2")
|
||||
@Data
|
||||
@PasswordRuleForKbank(password = "password", loginId = "loginId", mobile = "mobileNumber")
|
||||
@PasswordRuleForKjbank(password = "password", loginId = "loginId", mobile = "mobileNumber")
|
||||
public class PortalUserRegistrationDTO {
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package com.eactive.apim.portal.apps.user.dto;
|
||||
|
||||
import com.eactive.apim.portal.common.validator.PasswordMatch;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRule;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKbank;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKjbank;
|
||||
import com.eactive.apim.portal.common.validator.UniqueId;
|
||||
import com.eactive.apim.portal.portaluser.entity.UserStatus;
|
||||
import lombok.Data;
|
||||
@@ -14,7 +13,7 @@ import java.io.Serializable;
|
||||
|
||||
@PasswordMatch(input = "password", confirm = "password2")
|
||||
@Data
|
||||
@PasswordRuleForKbank(loginId = "userId", password = "password", mobile = "mobilePhone")
|
||||
@PasswordRuleForKjbank(loginId = "userId", password = "password", mobile = "mobilePhone")
|
||||
public class UserRegisterDTO implements Serializable {
|
||||
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ import com.eactive.apim.portal.file.service.FileTypeContext;
|
||||
import com.eactive.apim.portal.portalorg.entity.PortalOrg;
|
||||
import com.eactive.apim.portal.portaluser.entity.PortalUser;
|
||||
import com.eactive.apim.portal.portaluser.entity.PortalUserEnums;
|
||||
import com.eactive.apim.portal.portaluser.event.UserVerificationEmailEvent;
|
||||
import com.eactive.apim.portal.portaluser.repository.PortalUserRepository;
|
||||
import com.eactive.apim.portal.template.entity.MessageCode;
|
||||
import com.eactive.apim.portal.template.service.MessageHandlerService;
|
||||
import com.eactive.apim.portal.template.service.MessageRecipient;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -206,7 +206,7 @@ public class OrgRegisterFacadeImpl implements OrgRegisterFacade {
|
||||
try {
|
||||
String encToken = encryptionUtil.encrypt(tokenValue);
|
||||
params.put("token", Base64.encode(encToken.getBytes(StandardCharsets.UTF_8)));
|
||||
messageHandlerService.publishEvent(UserVerificationEmailEvent.KEY, recipient, params);
|
||||
messageHandlerService.publishEvent(MessageCode.USER_VERIFICATION_EMAIL, recipient, params);
|
||||
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
|
||||
throw new SystemException("암호화 모듈 오류");
|
||||
}
|
||||
|
||||
@@ -15,4 +15,6 @@ public interface UserFacade {
|
||||
void updateCorporateManager(PortalUserDTO portalUserDTO);
|
||||
|
||||
void withdrawUser(String userId);
|
||||
|
||||
void activateUserByEmail(String email);
|
||||
}
|
||||
@@ -198,4 +198,23 @@ public class UserFacadeImpl implements UserFacade {
|
||||
throw new IllegalArgumentException("새 비밀번호와 확인 비밀번호가 일치하지 않습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void activateUserByEmail(String email) {
|
||||
PortalUser user = portalUserService.findByEmailAddr(email);
|
||||
|
||||
if (user == null) {
|
||||
throw new IllegalArgumentException("사용자를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
if (user.getUserStatus() == PortalUserEnums.UserStatus.ACTIVE) {
|
||||
throw new IllegalArgumentException("이미 활성화된 계정입니다.");
|
||||
}
|
||||
|
||||
user.setUserStatus(PortalUserEnums.UserStatus.ACTIVE);
|
||||
portalUserService.save(user);
|
||||
|
||||
log.info("사용자 이메일 인증 완료 - 활성화: {}", email);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.eactive.apim.portal.common.util.SecurityUtil;
|
||||
import com.eactive.apim.portal.common.util.StringMaskingUtil;
|
||||
import com.eactive.apim.portal.invitation.entity.UserInvitation;
|
||||
import com.eactive.apim.portal.invitation.entity.UserInvitationEnums.InvitationStatus;
|
||||
import com.eactive.apim.portal.invitation.event.UserInvitationCancelEvent;
|
||||
import com.eactive.apim.portal.invitation.event.UserInvitationEvent;
|
||||
import com.eactive.apim.portal.portaluser.event.UserManagerAssignedEvent;
|
||||
import com.eactive.apim.portal.invitation.repository.UserInvitationRepository;
|
||||
@@ -183,7 +184,29 @@ public class UserManFacade {
|
||||
throw new IllegalStateException("Invitation is not in a cancelable state");
|
||||
}
|
||||
|
||||
// invitationId 로 사용자 이름 조회, 실패시 id 를 이름으로 대체
|
||||
String name = portalUserRepository.findById(invitation.getInvitationEmail())
|
||||
.map(PortalUser::getUserName)
|
||||
.orElse(invitation.getInvitationEmail());
|
||||
|
||||
// name 이 이메일 일 경우 @ 앞부분 만 사용 (안하면 암호화 해야함...)
|
||||
if (name.contains("@")) {
|
||||
name = name.substring(0, name.indexOf("@"));
|
||||
}
|
||||
|
||||
invitation.setStatus(InvitationStatus.CANCELED);
|
||||
|
||||
messageHandlerService.publishEvent(UserInvitationCancelEvent.KEY,
|
||||
MessageRecipient.builder()
|
||||
.username(name)
|
||||
.userId(invitationId)
|
||||
.build(),
|
||||
new HashMap<String, Object>() {{
|
||||
put("corpName", user.getPortalOrg().getOrgName());
|
||||
put("managerName", user.getUserName());
|
||||
}}
|
||||
);
|
||||
|
||||
userInvitationRepository.save(invitation);
|
||||
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ import com.eactive.apim.portal.invitation.entity.UserInvitation;
|
||||
import com.eactive.apim.portal.invitation.entity.UserInvitationEnums;
|
||||
import com.eactive.apim.portal.invitation.repository.UserInvitationRepository;
|
||||
import com.eactive.apim.portal.portaluser.entity.PortalUser;
|
||||
import com.eactive.apim.portal.portaluser.event.UserVerificationEmailEvent;
|
||||
import com.eactive.apim.portal.portaluser.repository.PortalUserRepository;
|
||||
import com.eactive.apim.portal.template.entity.MessageCode;
|
||||
import com.eactive.apim.portal.template.service.MessageHandlerService;
|
||||
import com.eactive.apim.portal.template.service.MessageRecipient;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -146,7 +146,8 @@ public class UserRegisterFacadeImpl implements UserRegisterFacade {
|
||||
}
|
||||
|
||||
agreementsFacade.saveUserAgreements(newUser.getId(), AgreementType.PRIVACY_COLLECT_IND);
|
||||
sendEmailActivation(newUser);
|
||||
// 11.13 - 회원 가입단계가 아닌 로그인 단계로 이메일 인증 이동
|
||||
// sendEmailActivation(newUser);
|
||||
return new ValidationResponse(true,"회원가입이 완료되었습니다.");
|
||||
}
|
||||
|
||||
@@ -219,7 +220,7 @@ public class UserRegisterFacadeImpl implements UserRegisterFacade {
|
||||
String tokenValue = String.valueOf(authNumberGenerator.generateAuthNumber());
|
||||
// String tokenValue = registeredUser.getCreatedDate().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + ":" + registeredUser.getId();
|
||||
params.put("token", tokenValue);
|
||||
messageHandlerService.publishEvent(UserVerificationEmailEvent.KEY, recipient, params);
|
||||
messageHandlerService.publishEvent(MessageCode.USER_VERIFICATION_EMAIL, recipient, params);
|
||||
|
||||
// try {
|
||||
// String encToken = encryptionUtil.encrypt(tokenValue);
|
||||
|
||||
@@ -96,9 +96,10 @@ public class PortalUserAuthService implements UserDetailsService {
|
||||
|
||||
public void initializePassword(String loginId, String userName, String mobileNumber) {
|
||||
|
||||
PortalUser portalUser = portalUserRepository.findByLoginIdAndUserNameAndMobileNumber(loginId, userName, mobileNumber).orElseThrow(() -> new UserNotFoundException("일치하는 사용자 정보를 찾을 수 없습니다."));
|
||||
PortalUser portalUser = portalUserRepository.findByLoginIdAndUserNameAndMobileNumber(loginId, userName, mobileNumber)
|
||||
.orElseThrow(() -> new UserNotFoundException("일치하는 사용자 정보를 찾을 수 없습니다."));
|
||||
|
||||
String tempPassword = EncryptionUtil.generateNewPassword();
|
||||
String tempPassword = EncryptionUtil.generateNewPasswordForKjbank(loginId);
|
||||
portalUser.setPasswordHash(passwordEncoder.encode(tempPassword));
|
||||
|
||||
portalUserRepository.save(portalUser);
|
||||
|
||||
@@ -49,6 +49,15 @@ public class PortalUserService {
|
||||
return portalUserRepository.findByLoginId(loginId);
|
||||
}
|
||||
|
||||
public PortalUser findByEmailAddr(String emailAddr) {
|
||||
return portalUserRepository.findPortalUserByEmailAddr(emailAddr)
|
||||
.orElseThrow(() -> new IllegalArgumentException("해당 이메일 주소의 사용자를 찾을 수 없습니다."));
|
||||
}
|
||||
|
||||
public PortalUser save(PortalUser user) {
|
||||
return portalUserRepository.save(user);
|
||||
}
|
||||
|
||||
public boolean existsByLoginId(String loginId) {
|
||||
return portalUserRepository.existsByLoginId(loginId);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.eactive.apim.portal.apps.user.validator;
|
||||
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKbankValidator;
|
||||
import com.eactive.apim.portal.common.validator.PasswordRuleForKjbankValidator;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@@ -16,7 +17,7 @@ public class PasswordValidator {
|
||||
}
|
||||
|
||||
public boolean isValidPassword(String password, String loginId, String mobileNumber) {
|
||||
PasswordRuleForKbankValidator validator = new PasswordRuleForKbankValidator();
|
||||
PasswordRuleForKjbankValidator validator = new PasswordRuleForKjbankValidator();
|
||||
return validator.isValid(password, loginId, mobileNumber);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public class PortalAuthenticatedUser extends PortalUser implements UserDetails {
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
return !"Y".equalsIgnoreCase(this.getAccountLockYn());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -30,7 +30,30 @@ public class EncryptionUtil {
|
||||
return newpassword.toString();
|
||||
}
|
||||
|
||||
@Value("${encryption.key:kbank_portal_application_1357902}")
|
||||
/**
|
||||
* 광주은행용 임시패스워드 생성
|
||||
* - @ + 이메일 주소 앞 5자리 + 랜덤숫자 3자리 + !
|
||||
* @return
|
||||
*/
|
||||
public static String generateNewPasswordForKjbank(String loginId) {
|
||||
StringBuilder newpassword = new StringBuilder();
|
||||
newpassword.append("@");
|
||||
|
||||
if (loginId.length() <= 5) {
|
||||
newpassword.append(loginId);
|
||||
} else {
|
||||
newpassword.append(loginId.substring(0, 5));
|
||||
}
|
||||
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
newpassword.append(RandomUtil.getRandomNum(0, 9));
|
||||
}
|
||||
newpassword.append("!");
|
||||
|
||||
return newpassword.toString();
|
||||
}
|
||||
|
||||
@Value("${encryption.key:kjbank_portal_application_1357902}")
|
||||
private String secretKey; // Should be 16, 24, or 32 bytes long for AES-128, AES-192, or AES-256
|
||||
|
||||
private static final String ALGORITHM = "AES";
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.eactive.apim.portal.common.validator;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Constraint(validatedBy = PasswordRuleForKjbankValidator.class)
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface PasswordRuleForKjbank {
|
||||
String message() default "비밀 번호 규칙에 부합하지 않습니다.(영문/숫자/특수문자 포함 8~20자, 아이디, 휴대전화, 3자리 이상 연속,반복 문자 불가)";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
String password();
|
||||
|
||||
String loginId();
|
||||
|
||||
String mobile();
|
||||
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.eactive.apim.portal.common.validator;
|
||||
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Created by Sungpil Hyun
|
||||
*/
|
||||
public class PasswordRuleForKjbankValidator implements ConstraintValidator<PasswordRuleForKjbank, Object> {
|
||||
|
||||
// 최소 8자, 최대 20자 상수 선언
|
||||
private static final int MIN = 8;
|
||||
private static final int MAX = 20;
|
||||
|
||||
private String password;
|
||||
private String loginId;
|
||||
private String mobileNumber;
|
||||
|
||||
// 3자리 연속 문자 정규식
|
||||
private static final String SAMEPT = "(\\w)\\1\\1";
|
||||
// 공백 문자 정규식
|
||||
private static final String BLANKPT = "(\\s)";
|
||||
|
||||
@Override
|
||||
public void initialize(PasswordRuleForKjbank constraintAnnotation) {
|
||||
this.password = constraintAnnotation.password();
|
||||
this.loginId = constraintAnnotation.loginId();
|
||||
this.mobileNumber = constraintAnnotation.mobile();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
|
||||
|
||||
String passwordValue = null;
|
||||
String loginIdValue = null;
|
||||
String mobileNumberValue = null;
|
||||
|
||||
try {
|
||||
passwordValue = (String) PropertyUtils.getProperty(value, this.password);
|
||||
loginIdValue = (String) PropertyUtils.getProperty(value, this.loginId);
|
||||
mobileNumberValue = (String) PropertyUtils.getProperty(value, this.mobileNumber);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isValid(passwordValue, loginIdValue, mobileNumberValue);
|
||||
}
|
||||
|
||||
public boolean isValid(String password, String loginId, String mobileNumber) {
|
||||
// 영어, 숫자, 특수문자 포함한 MIN to MAX 글자 정규식
|
||||
String REGEX = "^((?=.*\\d)(?=.*[a-zA-Z])(?=.*[\\W]).{" + MIN + "," + MAX + "})$";
|
||||
|
||||
// 정규식 검사객체
|
||||
Matcher matcher;
|
||||
|
||||
// 공백 체크
|
||||
if (password == null || "".equals(password)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ASCII 문자 비교를 위한 UpperCase
|
||||
String tmpPw = password.toUpperCase();
|
||||
// 문자열 길이
|
||||
int strLen = tmpPw.length();
|
||||
|
||||
// 글자 길이 체크
|
||||
if (strLen > 20 || strLen < 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (loginId != null && !loginId.isEmpty()) {
|
||||
String[] loginParts = loginId.split("@");
|
||||
if (loginParts.length > 0) {
|
||||
String username = loginParts[0].toUpperCase();
|
||||
if (tmpPw.contains(username)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile number validation
|
||||
if (mobileNumber != null && !mobileNumber.isEmpty()) {
|
||||
String[] mobileParts = mobileNumber.split("-");
|
||||
for (String part : mobileParts) {
|
||||
if (!part.isEmpty() && tmpPw.contains(part)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 공백 체크
|
||||
matcher = Pattern.compile(BLANKPT).matcher(tmpPw);
|
||||
if (matcher.find()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 비밀번호 정규식 체크
|
||||
matcher = Pattern.compile(REGEX).matcher(tmpPw);
|
||||
if (!matcher.find()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 동일한 문자 3개 이상 체크
|
||||
matcher = Pattern.compile(SAMEPT).matcher(tmpPw);
|
||||
if (matcher.find()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 연속된 문자 / 숫자 3개 이상 체크
|
||||
// ASCII Char를 담을 배열 선언
|
||||
int[] tmpArray = new int[strLen];
|
||||
|
||||
// Make Array
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
tmpArray[i] = tmpPw.charAt(i);
|
||||
}
|
||||
|
||||
// Validation Array
|
||||
for (int i = 0; i < strLen - 2; i++) {
|
||||
if (isContinuous(tmpArray[i], tmpArray[i + 2]) && isContinuous(tmpArray[i], tmpArray[i + 1], tmpArray[i + 2])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Validation Complete
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
static boolean isContinuous(int first, int third) {
|
||||
// 첫 글자 A-Z / 0-9
|
||||
return (first > 47 && third < 58) || (first > 64 && third < 91);
|
||||
}
|
||||
|
||||
static boolean isContinuous(int first, int second, int third) {
|
||||
// 배열의 연속된 수 검사
|
||||
// 3번째 글자 - 2번째 글자 = 1, 3번째 글자 - 1번째 글자 = 2
|
||||
return Math.abs(third - second) == 1 && Math.abs(third - first) == 2;
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,7 @@ public class BaseDatasourceConfiguration {
|
||||
properties.put("hibernate.default_schema", prop.getSchema());
|
||||
properties.put("javax.persistence.validation.mode", "none");
|
||||
properties.put("javax.persistence.transactionType", "JTA");
|
||||
properties.put("hibernate.format_sql", "true");
|
||||
|
||||
if (prop instanceof EmsDatasourceProperty) {
|
||||
persistenceUnit = "portal";
|
||||
@@ -95,7 +96,7 @@ public class BaseDatasourceConfiguration {
|
||||
}
|
||||
|
||||
// 개발 환경용
|
||||
if (env.matchesProfiles("dev", "local")) {
|
||||
if (env.matchesProfiles("local")) {
|
||||
properties.put("hibernate.hbm2ddl.auto", "validate");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.eactive.apim.portal.config;
|
||||
|
||||
import com.eactive.eai.data.jpa.BaseRepositoryImpl;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -9,20 +8,14 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jndi.JndiObjectFactoryBean;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Configuration
|
||||
@EntityScan(basePackages = {"com.eactive.apim.gateway"})
|
||||
@@ -78,28 +71,6 @@ public class GatewayDatasourceConfiguration extends BaseDatasourceConfiguration
|
||||
return createDataSource(gatewayProp);
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public DataSource portalDataSource(EmsDatasourceProperty emsProp) {
|
||||
// JNDI 이용
|
||||
if (StringUtils.isNotEmpty(emsProp.getJndiName())) {
|
||||
try {
|
||||
return this.jndiLookup(emsProp.getJndiName());
|
||||
} catch (NamingException e) {
|
||||
log.warn("JNDI lookup failed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("개발환경을 위해 JNDI 대신 직접 DB 접속 시도");
|
||||
|
||||
// JNDI 실패시 직접 접속 이용
|
||||
if (StringUtils.isEmpty(emsProp.getJdbcUrl())) {
|
||||
throw new IllegalArgumentException("DB 접속을 위한 JNDI 또는 서버 접속 정보가 설정되어 있지 않음");
|
||||
}
|
||||
|
||||
return createDataSource(emsProp);
|
||||
}
|
||||
|
||||
@Bean(name = "gatewayEntityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean gatewayEntityManagerFactory(
|
||||
EntityManagerFactoryBuilder builder,
|
||||
@@ -107,18 +78,4 @@ public class GatewayDatasourceConfiguration extends BaseDatasourceConfiguration
|
||||
GatewayDataSourceProperty gatewayProp) {
|
||||
return createEntityManagerFactory(builder, dataSource, gatewayProp);
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean(name = "entityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
|
||||
EntityManagerFactoryBuilder builder,
|
||||
@Qualifier("gatewayDataSource") DataSource dataSource,
|
||||
EmsDatasourceProperty emsProp) {
|
||||
return createEntityManagerFactory(builder, dataSource, emsProp);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuditorAware<String> auditorProvider() {
|
||||
return new AuditorAwareImpl();
|
||||
}
|
||||
}
|
||||
|
||||
+24
-6
@@ -5,11 +5,10 @@ import com.eactive.apim.portal.apps.user.service.PortalUserLogService;
|
||||
import com.eactive.apim.portal.common.exception.UserNotFoundException;
|
||||
import com.eactive.apim.portal.portaluser.entity.PortalUser;
|
||||
import com.eactive.apim.portal.portaluser.repository.PortalUserRepository;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.eactive.apim.portal.template.entity.MessageCode;
|
||||
import com.eactive.apim.portal.template.service.MessageHandlerService;
|
||||
import com.eactive.apim.portal.template.service.MessageRecipient;
|
||||
import org.apache.groovy.util.Maps;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
@@ -20,6 +19,11 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Created by Sungpil Hyun
|
||||
*/
|
||||
@@ -30,10 +34,15 @@ public class PortalAuthenticationFailureHandler implements AuthenticationFailure
|
||||
private static final Logger logger = LoggerFactory.getLogger(PortalAuthenticationFailureHandler.class);
|
||||
private final PortalUserRepository portalUserRepository;
|
||||
private final PortalUserLogService userLogService;
|
||||
private final MessageHandlerService messageHandlerService;
|
||||
|
||||
public PortalAuthenticationFailureHandler(PortalUserRepository portalUserRepository, PortalUserLogService userLogService) {
|
||||
|
||||
public PortalAuthenticationFailureHandler(PortalUserRepository portalUserRepository,
|
||||
PortalUserLogService userLogService,
|
||||
MessageHandlerService messageHandlerService) {
|
||||
this.portalUserRepository = portalUserRepository;
|
||||
this.userLogService = userLogService;
|
||||
this.messageHandlerService = messageHandlerService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -53,8 +62,17 @@ public class PortalAuthenticationFailureHandler implements AuthenticationFailure
|
||||
user.setLoginFailureCount(user.getLoginFailureCount() + 1);
|
||||
if (user.getLoginFailureCount() >= 5) {
|
||||
user.setAccountLockYn("Y");
|
||||
|
||||
// 계정 잠금 알림
|
||||
messageHandlerService.publishEvent(
|
||||
MessageCode.USER_ACCOUNT_LOCKED,
|
||||
MessageRecipient.of(user),
|
||||
Maps.of("reason", "5회 이상 로그인 실패로 인한 계정 잠금")) ;;
|
||||
}
|
||||
portalUserRepository.save(user);
|
||||
|
||||
|
||||
|
||||
} catch (UserNotFoundException e) {
|
||||
logger.error("{} login try {}", username, e.getMessage());
|
||||
}
|
||||
|
||||
@@ -5,8 +5,12 @@ import com.eactive.apim.portal.apps.user.service.PortalUserAuthService;
|
||||
import com.eactive.apim.portal.common.user.PortalAuthenticatedUser;
|
||||
import com.eactive.apim.portal.portalorg.entity.PortalOrgEnums;
|
||||
import com.eactive.apim.portal.portaluser.entity.PortalUserEnums;
|
||||
import com.eactive.apim.portal.template.entity.MessageCode;
|
||||
import com.eactive.apim.portal.template.service.MessageHandlerService;
|
||||
import com.eactive.apim.portal.template.service.MessageRecipient;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.groovy.util.Maps;
|
||||
import org.springframework.security.authentication.*;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
@@ -25,6 +29,7 @@ public class PortalAuthenticationManager implements AuthenticationManager {
|
||||
|
||||
private final PortalUserAuthService portalUserAuthService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final MessageHandlerService messageHandlerService;
|
||||
|
||||
private String decodePassword(String encodedPassword) {
|
||||
try {
|
||||
@@ -46,9 +51,22 @@ public class PortalAuthenticationManager implements AuthenticationManager {
|
||||
|
||||
PortalAuthenticatedUser user = (PortalAuthenticatedUser) portalUserAuthService.loadUserByUsername(username);
|
||||
|
||||
|
||||
if (!user.isAccountNonLocked()) {
|
||||
if (user.getLoginFailureCount() >= 5) {
|
||||
throw new LockedException("계정이 잠겼습니다. 비밀번호 초기화 또는 관리자에게 문의하세요.");
|
||||
}
|
||||
|
||||
throw new LockedException("로그인 할 수 없습니다. 비밀번호 초기화 또는 관리자에게 문의하세요.");
|
||||
}
|
||||
|
||||
|
||||
// 비밀번호 검증
|
||||
if (!passwordEncoder.matches(decodedPassword, user.getPassword())) {
|
||||
throw new BadCredentialsException("아이디 또는 비밀번호가 일치하지 않습니다.");
|
||||
// 암호화가 되어 있지 않을 수도 있어 그대로 비교 검증
|
||||
if (!user.getPassword().equals(decodedPassword)) {
|
||||
throw new BadCredentialsException("아이디 또는 비밀번호가 일치하지 않습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
// DORMANT 상태 체크
|
||||
@@ -64,9 +82,10 @@ public class PortalAuthenticationManager implements AuthenticationManager {
|
||||
throw new DisabledException("사용자 승인 대기중입니다. ");
|
||||
}
|
||||
|
||||
if (user.getUserStatus().equals(PortalUserEnums.UserStatus.READY)) {
|
||||
throw new DisabledException("이메일 인증이 완료되지 않았습니다. 인증 메일을 확인해주세요.");
|
||||
}
|
||||
// 25.11.13 - 이메일 인증 로그인은 허용
|
||||
// if (user.getUserStatus().equals(PortalUserEnums.UserStatus.READY)) {
|
||||
// throw new DisabledException("이메일 인증이 완료되지 않았습니다. 인증 메일을 확인해주세요.");
|
||||
// }
|
||||
|
||||
if (user.getUserStatus().equals(PortalUserEnums.UserStatus.ADMINBLOCK)) {
|
||||
throw new DisabledException("법인 관리자에 의해 비활성화된 계정입니다. 법인 관리자에게 문의하시기 바랍니다.");
|
||||
@@ -79,9 +98,7 @@ public class PortalAuthenticationManager implements AuthenticationManager {
|
||||
}
|
||||
}
|
||||
|
||||
if (!user.isAccountNonLocked()) {
|
||||
throw new LockedException("로그인할 수 없습니다. 관리자에게 문의하세요.");
|
||||
}
|
||||
|
||||
|
||||
UsernamePasswordAuthenticationToken authorityToken =
|
||||
new UsernamePasswordAuthenticationToken(user, decodedPassword, user.getAuthorities());
|
||||
|
||||
+9
-1
@@ -55,7 +55,11 @@ public class PortalAuthenticationSuccessHandler implements AuthenticationSuccess
|
||||
HttpSession session = request.getSession();
|
||||
|
||||
// 세션에 상태 저장
|
||||
if (isDormantAccount(user)) {
|
||||
if (isEmailVerificationRequired(user)) {
|
||||
session.setAttribute("success", "이메일 인증이 완료되지 않았습니다. 이메일을 확인하여 인증을 완료해주세요.");
|
||||
session.setAttribute("emailVerificationRequired", true);
|
||||
session.setAttribute("redirectUrl", contextPath + "/mypage/verification-email");
|
||||
} else if (isDormantAccount(user)) {
|
||||
session.setAttribute("success", "90일 이상 미접속하여 계정이 잠금 처리되었습니다. 본인인증 후 이용해주세요.");
|
||||
session.setAttribute("dormantAccount", true);
|
||||
session.setAttribute("dormantLoginId", username);
|
||||
@@ -114,4 +118,8 @@ public class PortalAuthenticationSuccessHandler implements AuthenticationSuccess
|
||||
return PortalUserEnums.UserStatus.DORMANT.equals(user.getUserStatus());
|
||||
}
|
||||
|
||||
private boolean isEmailVerificationRequired(PortalUser user) {
|
||||
return PortalUserEnums.UserStatus.READY.equals(user.getUserStatus());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.eactive.apim.portal.config;
|
||||
|
||||
import com.eactive.apim.portal.spring.DatabaseSessionVerifier;
|
||||
import com.eactive.eai.data.jpa.BaseRepositoryImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -57,23 +58,39 @@ public class PortalDatasourceConfiguration extends BaseDatasourceConfiguration {
|
||||
@Primary
|
||||
@Bean
|
||||
public DataSource portalDataSource(EmsDatasourceProperty emsProp) {
|
||||
DataSource dataSource = null;
|
||||
|
||||
log.debug("Portal datasource initialize.");
|
||||
|
||||
// JNDI 이용
|
||||
if (StringUtils.isNotEmpty(emsProp.getJndiName())) {
|
||||
try {
|
||||
return this.jndiLookup(emsProp.getJndiName());
|
||||
log.debug("Try get JNDI datasource : {}", emsProp.getJndiName());
|
||||
dataSource = this.jndiLookup(emsProp.getJndiName());
|
||||
} catch (NamingException e) {
|
||||
log.warn("JNDI lookup failed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("개발환경을 위해 JNDI 대신 직접 DB 접속 시도");
|
||||
if (dataSource == null) {
|
||||
log.info("개발환경을 위해 JNDI 대신 직접 DB 접속 시도");
|
||||
|
||||
// JNDI 실패시 직접 접속 이용
|
||||
if (StringUtils.isEmpty(emsProp.getJdbcUrl())) {
|
||||
throw new IllegalArgumentException("DB 접속을 위한 JNDI 또는 서버 접속 정보가 설정되어 있지 않음");
|
||||
// JNDI 실패시 직접 접속 이용
|
||||
if (StringUtils.isEmpty(emsProp.getJdbcUrl())) {
|
||||
throw new IllegalArgumentException("DB 접속을 위한 JNDI 또는 서버 접속 정보가 설정되어 있지 않음");
|
||||
}
|
||||
|
||||
dataSource = createDataSource(emsProp);
|
||||
}
|
||||
|
||||
return createDataSource(emsProp);
|
||||
if (dataSource != null && env.matchesProfiles("db_check")) {
|
||||
log.debug("Activated 'db_check' profile.");
|
||||
DatabaseSessionVerifier verifier = new DatabaseSessionVerifier(dataSource);
|
||||
verifier.afterSingletonsInstantiated();
|
||||
}
|
||||
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Primary
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.eactive.apim.portal.spring;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
//@Configuration
|
||||
//@Profile("db_check")
|
||||
@Slf4j
|
||||
public class DatabaseSessionVerifier implements SmartInitializingSingleton {
|
||||
private final DataSource emsDataSource;
|
||||
|
||||
|
||||
public DatabaseSessionVerifier(DataSource emsDataSource) {
|
||||
this.emsDataSource = emsDataSource;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
log.info("DB 검증 작업 시작 - {}", now());
|
||||
log.info("---------------------------------------------------");
|
||||
|
||||
log.info("1. 커넥션 확인");
|
||||
try (Connection conn = emsDataSource.getConnection()) {
|
||||
try (PreparedStatement statement = conn.prepareStatement("select 1 from dual")) {
|
||||
ResultSet rs = statement.executeQuery();
|
||||
if (rs.next()) {
|
||||
log.info("DB 커넥션 확인됨");
|
||||
}
|
||||
}
|
||||
|
||||
log.info("\n2. Table 권한 확인 - {}", now());
|
||||
Map<String, Set<String>> grantTables = this.printTablePrivileges(conn);
|
||||
|
||||
|
||||
log.info("\n3. PTL_PROPERTY 테이블 확인 - {}", now());
|
||||
if (!grantTables.containsKey("PTL_PROPERTY")) {
|
||||
log.info("PTL_PROPERTY 테이블 확인 안됨. ROLE 재로딩 시도");
|
||||
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("SET ROLE_RL_EMS_ALL");
|
||||
}
|
||||
|
||||
this.printTablePrivileges(conn);
|
||||
|
||||
throw new InterruptedException("DB 검증 실패로 강제 종료");
|
||||
} else {
|
||||
log.info("PTL_PROPERTY 테이블 확인 됨.");
|
||||
}
|
||||
|
||||
log.info("검증 작업 종료 - {}", now());
|
||||
} catch (Exception e) {
|
||||
log.error("DB 세션 검증 실패", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
throw new RuntimeException("db_check profile end.");
|
||||
}
|
||||
|
||||
|
||||
private LinkedHashMap<String, Set<String>> printTablePrivileges(Connection conn) throws SQLException {
|
||||
LinkedHashMap<String, Set<String>> tables = new LinkedHashMap<>();
|
||||
|
||||
try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM ROLE_TAB_PRIVS WHERE role = ? ORDER BY table_name ASC")) {
|
||||
stmt.setString(1, "RL_EMS_ALL");
|
||||
ResultSet rs = stmt.executeQuery();
|
||||
while(rs.next()) {
|
||||
Set<String> privileges;
|
||||
if (tables.containsKey(rs.getString("table_name"))) {
|
||||
privileges = tables.get(rs.getString("table_name"));
|
||||
} else {
|
||||
privileges = new LinkedHashSet<>();
|
||||
tables.put(rs.getString("table_name").toUpperCase(), privileges);
|
||||
}
|
||||
|
||||
privileges.add(rs.getString("privilege"));
|
||||
}
|
||||
|
||||
log.info("| Table | Privileges |");
|
||||
log.info("|---|---|");
|
||||
tables.forEach((key, value) -> log.info(String.format("| %-20s | %-36s |", key, value)));
|
||||
}
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
|
||||
private String now() {
|
||||
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.eactive.apim.portal.tools;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@Component
|
||||
@Aspect
|
||||
@Slf4j
|
||||
public class JpaErrorLoggingAspect {
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
@AfterThrowing(pointcut = "@annotation(org.springframework.transaction.annotation.Transactional)", throwing = "ex")
|
||||
public void onError(SQLException ex) {
|
||||
try {
|
||||
String user = (String) em.createNativeQuery("select user from dual").getSingleResult();
|
||||
log.error("DB USER = {}, SQL ERROR = {}", user, ex.getMessage() );
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to fetch DB User", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user