Implemented a simple UserIdSource, that stores the user in a cookie
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / SecurityContext.java
diff --git a/src/main/java/de/juplo/yourshouter/SecurityContext.java b/src/main/java/de/juplo/yourshouter/SecurityContext.java
new file mode 100644 (file)
index 0000000..37ca54c
--- /dev/null
@@ -0,0 +1,66 @@
+package de.juplo.yourshouter;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Simple SecurityContext that stores the currently signed-in connection in a
+ * thread local.
+ *
+ * @author Kai Moritz
+ */
+public final class SecurityContext
+{
+  private final static Logger LOG = LoggerFactory.getLogger(SecurityContext.class);
+  private final static ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
+
+
+  /**
+   * Fetches the ID of the current user from the thread-local.
+   *
+   * @return
+   *     The ID of the current user, or <code>null</code> if no user is known.
+   */
+  public static String getCurrentUser()
+  {
+    String user = CURRENT_USER.get();
+    LOG.debug("current user: {}", user);
+    return user;
+  }
+
+  /**
+   * Stores the given ID as the ID of the current user in the thread-local.
+   *
+   * @param user
+   *     The ID to store as the ID of the current user.
+   */
+  public static void setCurrentUser(String user)
+  {
+    LOG.debug("setting current user: {}", user);
+    CURRENT_USER.set(user);
+  }
+
+  /**
+   * Checks, if a user is signed in. That is, if the ID of a user is stored in
+   * the thread-local.
+   *
+   * @return
+   *   <code>true</code>, if a user is signed in, <code>false</code> otherwise.
+   */
+  public static boolean userSignedIn()
+  {
+    boolean signedIn = CURRENT_USER.get() != null;
+    LOG.debug("user signed in: {}", signedIn);
+    return signedIn;
+  }
+
+  /**
+   * Removes the ID of the current user from the thread-local.
+   */
+  public static void remove()
+  {
+    LOG.debug("removing current user");
+    CURRENT_USER.remove();
+  }
+}