1 package de.juplo.yourshouter;
4 import java.io.IOException;
5 import java.util.Collections;
6 import java.util.regex.Pattern;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
12 import org.springframework.social.connect.UsersConnectionRepository;
13 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
17 * Intercepts all requests to handle the user-cookie.
21 public final class UserCookieInterceptor extends HandlerInterceptorAdapter
23 private final static Logger LOG =
24 LoggerFactory.getLogger(UserCookieInterceptor.class);
25 private final static Pattern PATTERN = Pattern.compile("^/signin|canvas");
28 private final UsersConnectionRepository repository;
32 * Creates an instance of this class, that uses the given instance of
33 * {@link UsersConnectionRepository}.
36 * The instance of {@link UsersConnectionRepository} to use.
38 public UserCookieInterceptor(UsersConnectionRepository repository)
40 this.repository = repository;
45 * Before a request is handled, the current user is loaded from the cookie,
46 * if the cookie is present and the user is known. If the user is not known,
47 * the cookie is removed.
50 * The {@link HttpServletRequest} that is intercepted.
52 * The {@link HttpServletResponse} that is intercepted.
54 * The handler, that handles the intercepted request.
56 * Always <code>true</code>, to indicate, that the intercepted request
57 * should be handled normally.
58 * @throws java.io.IOException
59 * if something wents wrong, while sending the redirect to the
63 public boolean preHandle(
64 HttpServletRequest request,
65 HttpServletResponse response,
71 if (PATTERN.matcher(request.getServletPath()).find())
74 String user = UserCookieGenerator.INSTANCE.readCookieValue(request);
78 .findUserIdsConnectedTo("facebook", Collections.singleton(user))
82 LOG.info("loading user {} from cookie", user);
83 SecurityContext.setCurrentUser(user);
88 LOG.warn("user {} is not known!", user);
89 UserCookieGenerator.INSTANCE.removeCookie(response);
93 response.sendRedirect("/signin.html");
98 * After a request, the user is removed from the security-context.
101 * The {@link HttpServletRequest} that is intercepted.
103 * The {@link HttpServletResponse} that is intercepted.
105 * The handler, that handles the intercepted request.
107 * If an exception was thrown during the handling of this request, it is
108 * handed in through this parameter.
111 public void afterCompletion(
112 HttpServletRequest request,
113 HttpServletResponse response,
118 SecurityContext.remove();