Sign in users via Facebook and sign up new users automatically
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / UserCookieSignInAdapter.java
1 package de.juplo.yourshouter;
2
3 import javax.servlet.http.HttpServletResponse;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.social.connect.Connection;
7 import org.springframework.social.connect.web.SignInAdapter;
8 import org.springframework.web.context.request.NativeWebRequest;
9
10
11 /**
12  * Simple implementation of {@link SignInAdapter}.
13  *
14  * We configured Spring-Social to call this implementation, to sign in the
15  * user, after he was authenticated by Facebook.
16  *
17  * @author Kai Moritz
18  */
19 public class UserCookieSignInAdapter implements SignInAdapter
20 {
21   private final static Logger LOG =
22       LoggerFactory.getLogger(UserCookieSignInAdapter.class);
23
24
25   /**
26    * Stores the user in the security-context to sign him in.
27    * Also remembers the user for subsequent calls by storing the ID in the
28    * cookie.
29    *
30    * @param user
31    *     The user-ID. We configured Spring-Social to call
32    *     {@link UserCookieSignInAdapter} to extract a user-ID from the
33    *     connection.
34    * @param connection
35    *     The connection. In our case a connection to Facebook.
36    * @param request
37    *     The actual request. We need it, to store the cookie.
38    * @return
39    *     We return <code>null</code>, to indicate, that the user should be
40    *     redirected to the default-post-sign-in-URL (configured in
41    *     {@link ProviderSinInController}) after a successfull authentication.
42    *
43    * @see {@link UserCookieSignInAdapter}
44    * @see {@link ProviderSignInController#postSignInUrl}
45    */
46   @Override
47   public String signIn(
48       String user,
49       Connection<?> connection,
50       NativeWebRequest request
51       )
52   {
53     LOG.info(
54         "signing in user {} (connected via {})",
55         user,
56         connection.getKey().getProviderId()
57         );
58     SecurityContext.setCurrentUser(user);
59     UserCookieGenerator
60         .INSTANCE
61         .addCookie(user, request.getNativeResponse(HttpServletResponse.class));
62
63     // We return null to trigger a redirect to "/".
64     return null;
65   }
66 }