|
| 1 | +package org.launchcode.codingevents; |
| 2 | + |
| 3 | +import jakarta.servlet.http.HttpServletRequest; |
| 4 | +import jakarta.servlet.http.HttpServletResponse; |
| 5 | +import jakarta.servlet.http.HttpSession; |
| 6 | +import org.launchcode.codingevents.controllers.AuthenticationController; |
| 7 | +import org.launchcode.codingevents.data.UserRepository; |
| 8 | +import org.launchcode.codingevents.models.User; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.web.servlet.HandlerInterceptor; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.util.Arrays; |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +public class AuthenticationFilter implements HandlerInterceptor { |
| 17 | + |
| 18 | + @Autowired |
| 19 | + UserRepository userRepository; |
| 20 | + |
| 21 | + @Autowired |
| 22 | + AuthenticationController authenticationController; |
| 23 | + |
| 24 | + private static final List<String> whitelist = Arrays.asList("/login", "/register", "/logout", "/css"); |
| 25 | + |
| 26 | + private static boolean isWhitelisted(String path) { |
| 27 | + for (String pathRoot : whitelist) { |
| 28 | + if (path.startsWith(pathRoot)) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + } |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public boolean preHandle(HttpServletRequest request, |
| 37 | + HttpServletResponse response, |
| 38 | + Object handler) throws IOException { |
| 39 | + |
| 40 | + // Don't require sign-in for whitelisted pages |
| 41 | + if (isWhitelisted(request.getRequestURI())) { |
| 42 | + // returning true indicates that the request may proceed |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + HttpSession session = request.getSession(); |
| 47 | + User user = authenticationController.getUserFromSession(session); |
| 48 | + |
| 49 | + // The user is logged in |
| 50 | + if (user != null) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + // The user is NOT logged in |
| 55 | + response.sendRedirect("/login"); |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments