카테고리 없음

TiL 코드스니펫이나 참고 한번이라도 한 내용

creator7087 2025. 4. 2. 20:49

아래 코드들을 안보고 칠때까지 노력해본다.

@PostMapping("/login")
//HttpServletRequest httpServletRequest 구조 외우기
public ResponseEntity<LoginResponseDto> authorLogin(@Valid @RequestBody LoginRequestDto loginRequestDto, HttpServletRequest httpServletRequest) {

    LoginResponseDto loginResponseDto=loginService.authorLogin(loginRequestDto);

    HttpSession session=httpServletRequest.getSession();

    session.setAttribute(Const.LOGIN_USER,loginResponseDto.getId());


    return new ResponseEntity<>(loginResponseDto,HttpStatus.OK);
}
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class) // JPA Auditing 활성화
public abstract class BaseEntity {
    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @Setter
    @LastModifiedDate  // 수정 시간 자동 업데이트
    private LocalDateTime updatedAt;
}
//@ExceptionHandler 이름 외우기
//MethodArgumentNotValidException 랑 ConstraintViolationException 기억하자
@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();

    for (FieldError error : ex.getBindingResult().getFieldErrors()) {
        errors.put(error.getField(), error.getDefaultMessage());
    }

    return new ResponseEntity<>(errors,HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<ErrorDto> handleConstraintViolation(ConstraintViolationException ex) {
    ErrorDto errorDto=new ErrorDto(ex.getMessage());
    return new ResponseEntity<>(errorDto,HttpStatus.BAD_REQUEST);
}
public class LoginFilter implements Filter {
    private static final String[] whiteList={"/home/login","/home/logout","/authors"};


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        String requestURL=httpServletRequest.getRequestURI();

        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;

        HttpSession httpSession=httpServletRequest.getSession(false);

        if (!IsWhiteList(requestURL)) {
            if (httpSession == null || httpSession.getAttribute(Const.LOGIN_USER) == null) {
                throw (new IOException("하기싫어요"));
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
    private boolean IsWhiteList(String requestURL ){

        //보고 하자
        return PatternMatchUtils.simpleMatch(whiteList,requestURL);
    }



}
import at.favre.lib.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;

@Component
public class PasswordEncoder {

    public String encode(String rawPassword) {
        return BCrypt.withDefaults().hashToString(BCrypt.MIN_COST, rawPassword.toCharArray());
    }

    public boolean matches(String rawPassword, String encodedPassword) {
        BCrypt.Result result = BCrypt.verifyer().verify(rawPassword.toCharArray(), encodedPassword);
        return result.verified;
    }
}
//암기&구조 확인필수
@Configuration
public class WebConfig {
    @Bean
    public FilterRegistrationBean loginFilter(){
        FilterRegistrationBean<Filter> filterRegistrationBean= new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new LoginFilter());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
}
@Repository
@Transactional
@RequiredArgsConstructor
public class LoginCheckedRepositoryImpl implements LoginCheckedRepository {
    // 이 부분 블로그 참고(암기필수)
    @Autowired
    private final EntityManager entityManager;
    @Autowired
    private final PasswordEncoder passwordEncoder;

    @Override
    public LoginResponseDto checkPassword(String email, String password) {
        //sqpl문 공부
        String storedAuthorPassword =entityManager.createQuery("SELECT A.password FROM Author A where A.email=:email", String.class)
                .setParameter("email",email)
                .getSingleResult();


        if (!passwordEncoder.matches(password,storedAuthorPassword)){
            throw new CustomException(ErrorCode.Password, new String[]{"home/login", "잘못된 입력입니다"});
        }else {
            Long storedAuthorId = entityManager.createQuery("SELECT A.id FROM Author A where A.email=:email", Long.class)
                    .setParameter("email",email)
                    .getSingleResult();
            LoginResponseDto loginResponseDto =new LoginResponseDto("로그인에 성공했습니다.",storedAuthorId,true);

        return loginResponseDto;
        }


    }
    //혹시몰라서 캡슐화 적용
    private static class UserInfo {
        String storedPassword;
        Long storedId;

    }
}