1 package de.juplo.yourshouter;
4 import java.io.IOException;
5 import java.util.Collections;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
11 import org.springframework.social.connect.UsersConnectionRepository;
12 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
16 * Intercepts all requests to handle the user-cookie.
20 public final class UserCookieInterceptor extends HandlerInterceptorAdapter
22 private final static Logger LOG =
23 LoggerFactory.getLogger(UserCookieInterceptor.class);
26 private final UsersConnectionRepository repository;
30 * Creates an instance of this class, that uses the given instance of
31 * {@link UsersConnectionRepository}.
34 * The instance of {@link UsersConnectionRepository} to use.
36 public UserCookieInterceptor(UsersConnectionRepository repository)
38 this.repository = repository;
43 * Before a request is handled, the current user is loaded from the cookie,
44 * if the cookie is present and the user is known. If the user is not known,
45 * the cookie is removed.
48 * The {@link HttpServletRequest} that is intercepted.
50 * The {@link HttpServletResponse} that is intercepted.
52 * The handler, that handles the intercepted request.
54 * Always <code>true</code>, to indicate, that the intercepted request
55 * should be handled normally.
56 * @throws java.io.IOException
57 * if something wents wrong, while sending the redirect to the
61 public boolean preHandle(
62 HttpServletRequest request,
63 HttpServletResponse response,
69 if (request.getServletPath().startsWith("/signin"))
72 String user = UserCookieGenerator.INSTANCE.readCookieValue(request);
76 .findUserIdsConnectedTo("facebook", Collections.singleton(user))
80 LOG.info("loading user {} from cookie", user);
81 SecurityContext.setCurrentUser(user);
86 LOG.warn("user {} is not known!", user);
87 UserCookieGenerator.INSTANCE.removeCookie(response);
91 response.sendRedirect("/signin.html");
96 * After a request, the user is removed from the security-context.
99 * The {@link HttpServletRequest} that is intercepted.
101 * The {@link HttpServletResponse} that is intercepted.
103 * The handler, that handles the intercepted request.
105 * If an exception was thrown during the handling of this request, it is
106 * handed in through this parameter.
109 public void afterCompletion(
110 HttpServletRequest request,
111 HttpServletResponse response,
116 SecurityContext.remove();