|
| 1 | +package clap.server.adapter.inbound.security; |
| 2 | + |
| 3 | +import clap.server.application.service.auth.LoginAttemptService; |
| 4 | +import clap.server.exception.AuthException; |
| 5 | +import clap.server.exception.code.CommonErrorCode; |
| 6 | +import jakarta.servlet.FilterChain; |
| 7 | +import jakarta.servlet.ServletException; |
| 8 | +import jakarta.servlet.http.HttpServletRequest; |
| 9 | +import jakarta.servlet.http.HttpServletResponse; |
| 10 | +import lombok.RequiredArgsConstructor; |
| 11 | +import lombok.extern.slf4j.Slf4j; |
| 12 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 13 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 14 | +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; |
| 15 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.util.ArrayList; |
| 19 | + |
| 20 | +import static clap.server.common.constants.AuthConstants.SESSION_ID; |
| 21 | + |
| 22 | + |
| 23 | +@RequiredArgsConstructor |
| 24 | +@Slf4j |
| 25 | +public class LoginAttemptFilter extends OncePerRequestFilter { |
| 26 | + |
| 27 | + private static final String LOGIN_ENDPOINT = "/api/auths/login"; |
| 28 | + private final LoginAttemptService loginAttemptService; |
| 29 | + |
| 30 | + @Override |
| 31 | + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) |
| 32 | + throws ServletException, IOException { |
| 33 | + |
| 34 | + String sessionId = request.getHeader(SESSION_ID.getValue().toLowerCase()); |
| 35 | + |
| 36 | + if (request.getRequestURI().equals(LOGIN_ENDPOINT)) { |
| 37 | + if (sessionId == null) { |
| 38 | + throw new AuthException(CommonErrorCode.BAD_REQUEST); |
| 39 | + } |
| 40 | + loginAttemptService.checkAccountIsLocked(sessionId); |
| 41 | + } |
| 42 | + |
| 43 | + UsernamePasswordAuthenticationToken authenticationToken = |
| 44 | + new UsernamePasswordAuthenticationToken("user", null, new ArrayList<>()); |
| 45 | + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); |
| 46 | + SecurityContextHolder.getContext().setAuthentication(authenticationToken); |
| 47 | + |
| 48 | + filterChain.doFilter(request, response); |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments