+package de.juplo.yourshouter;
+
+
+import java.util.Collections;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.social.connect.UsersConnectionRepository;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+
+/**
+ * Intercepts all requests to handle the user-cookie.
+ *
+ * @author Kai Moritz
+ */
+public final class UserCookieInterceptor extends HandlerInterceptorAdapter
+{
+ private final static Logger LOG =
+ LoggerFactory.getLogger(UserCookieInterceptor.class);
+
+
+ private final UsersConnectionRepository repository;
+
+
+ /**
+ * Creates an instance of this class, that uses the given instance of
+ * {@link UsersConnectionRepository}.
+ *
+ * @param repository
+ * The instance of {@link UsersConnectionRepository} to use.
+ */
+ public UserCookieInterceptor(UsersConnectionRepository repository)
+ {
+ this.repository = repository;
+ }
+
+
+ /**
+ * Before a request is handled, the current user is loaded from the cookie,
+ * if the cookie is present and the user is known. If the user is not known,
+ * the cookie is removed.
+ *
+ * @param request
+ * The {@link HttpServletRequest} that is intercepted.
+ * @param response
+ * The {@link HttpServletResponse} that is intercepted.
+ * @param handler
+ * The handler, that handles the intercepted request.
+ * @return
+ * Always <code>true</code>, to indicate, that the intercepted request
+ * should be handled normally.
+ */
+ @Override
+ public boolean preHandle(
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler
+ )
+ {
+ String user = UserCookieGenerator.INSTANCE.readCookieValue(request);
+ if (user != null)
+ {
+ if (!repository
+ .findUserIdsConnectedTo("facebook", Collections.singleton(user))
+ .isEmpty()
+ )
+ {
+ LOG.info("loading user {} from cookie", user);
+ SecurityContext.setCurrentUser(user);
+ return true;
+ }
+ else
+ {
+ LOG.warn("user {} is not known!", user);
+ UserCookieGenerator.INSTANCE.removeCookie(response);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * After a request, the user is removed from the security-context.
+ *
+ * @param request
+ * The {@link HttpServletRequest} that is intercepted.
+ * @param response
+ * The {@link HttpServletResponse} that is intercepted.
+ * @param handler
+ * The handler, that handles the intercepted request.
+ * @param exception
+ * If an exception was thrown during the handling of this request, it is
+ * handed in through this parameter.
+ */
+ @Override
+ public void afterCompletion(
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception exception
+ )
+ {
+ SecurityContext.remove();
+ }
+}