[jboss-cvs] Picketlink SVN: r965 - in social/trunk: facebook and 8 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Fri May 20 00:16:44 EDT 2011


Author: anil.saldhana at jboss.com
Date: 2011-05-20 00:16:43 -0400 (Fri, 20 May 2011)
New Revision: 965

Added:
   social/trunk/facebook/
   social/trunk/facebook/.project
   social/trunk/facebook/pom.xml
   social/trunk/facebook/src/
   social/trunk/facebook/src/main/
   social/trunk/facebook/src/main/java/
   social/trunk/facebook/src/main/java/org/
   social/trunk/facebook/src/main/java/org/picketlink/
   social/trunk/facebook/src/main/java/org/picketlink/social/
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java
   social/trunk/facebook/src/main/resources/
   social/trunk/facebook/src/test/
   social/trunk/facebook/src/test/java/
   social/trunk/facebook/src/test/resources/
Log:
facebook module

Added: social/trunk/facebook/.project
===================================================================
--- social/trunk/facebook/.project	                        (rev 0)
+++ social/trunk/facebook/.project	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,17 @@
+<projectDescription>
+  <name>picketlink-facebook</name>
+  <comment>PicketLink Social - Facebook Adaptor</comment>
+  <projects/>
+  <buildSpec>
+    <buildCommand>
+      <name>org.eclipse.jdt.core.javabuilder</name>
+    </buildCommand>
+    <buildCommand>
+      <name>org.maven.ide.eclipse.maven2Builder</name>
+    </buildCommand>
+  </buildSpec>
+  <natures>
+    <nature>org.maven.ide.eclipse.maven2Nature</nature>
+    <nature>org.eclipse.jdt.core.javanature</nature>
+  </natures>
+</projectDescription>
\ No newline at end of file

Added: social/trunk/facebook/pom.xml
===================================================================
--- social/trunk/facebook/pom.xml	                        (rev 0)
+++ social/trunk/facebook/pom.xml	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,127 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.picketlink</groupId>
+      <artifactId>picketlink-fed-parent</artifactId>
+      <version>2.0.0-SNAPSHOT</version>
+      <relativePath>../parent</relativePath>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <artifactId>picketlink-facebook</artifactId>
+   <packaging>jar</packaging>
+   <name>PicketLink Social - Facebook Adaptor</name>
+   <url>http://labs.jboss.org/portal/picketlink/</url>
+   <description>PicketLink Social - Facebook Adaptor</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+
+   <build>
+     <plugins>
+       <plugin>
+          <artifactId>maven-surefire-plugin</artifactId>
+          <version>2.7.1</version>
+          <configuration>
+            <additionalClasspathElements>
+              <additionalClasspathElement>${basedir}/src/test/resources/endorsed/xercesImpl.jar</additionalClasspathElement>
+            </additionalClasspathElements>
+            <printSummary>true</printSummary>
+            <disableXmlReport>false</disableXmlReport>
+            <testFailureIgnore>false</testFailureIgnore>
+            <includes>
+              <include>**/**TestCase.java</include>
+            </includes>
+            <forkMode>pertest</forkMode>
+            <argLine>-Djava.endorsed.dirs=${basedir}/src/test/resources/endorsed</argLine>
+            <useFile>false</useFile>
+            <trimStackTrace>false</trimStackTrace>
+          </configuration>
+        </plugin>
+     </plugins>
+  </build>
+
+   <dependencies>
+      <dependency>
+         <groupId>org.json</groupId>
+         <artifactId>json</artifactId>
+         <version>20090211</version>
+      </dependency>
+     <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jboss-security-spi</artifactId>
+         <version>2.0.4</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jbosssx</artifactId>
+         <version>2.0.4</version>
+         <scope>compile</scope>
+      </dependency>
+     <dependency>
+         <groupId>org.apache.tomcat</groupId>
+         <artifactId>catalina</artifactId>
+         <version>6.0.18</version>
+         <optional>true</optional>
+      </dependency>
+      <dependency>
+         <groupId>javax.servlet</groupId>
+         <artifactId>servlet-api</artifactId>
+         <version>2.5</version>
+         <optional>true</optional>
+      </dependency>
+      <dependency>
+         <groupId>apache-log4j</groupId>
+         <artifactId>log4j</artifactId>
+         <version>1.2.14</version>
+         <optional>true</optional>
+      </dependency>
+      <dependency>
+         <groupId>commons-httpclient</groupId>
+         <artifactId>commons-httpclient</artifactId>
+         <version>3.1</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <scope>test</scope>
+      </dependency>
+   </dependencies>
+   
+   <reporting>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-javadoc-plugin</artifactId>
+        <configuration>
+          <doclet>org.jboss.apiviz.APIviz</doclet>
+          <docletArtifact>
+            <groupId>org.jboss.apiviz</groupId>
+            <artifactId>apiviz</artifactId>
+            <version>1.2.5.GA</version>
+          </docletArtifact>
+          <additionalparam>
+            -charset UTF-8
+            -docencoding UTF-8
+            -version
+            -author
+            -breakiterator
+            -windowtitle "${project.name} ${project.version} API Reference"
+            -doctitle "${project.name} ${project.version} API Reference"
+            -bottom "Copyright © ${project.inceptionYear}-Present ${project.organization.name}. All Rights Reserved."
+            -link http://java.sun.com/javase/6/docs/api/
+            -sourceclasspath ${project.build.outputDirectory}
+          </additionalparam>
+          <encoding>UTF-8</encoding>
+        </configuration>
+      </plugin>
+    </plugins>
+  </reporting>
+</project>


Property changes on: social/trunk/facebook/pom.xml
___________________________________________________________________
Added: svn:executable
   + *

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,411 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.social.facebook;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.authenticator.Constants;
+import org.apache.catalina.authenticator.FormAuthenticator;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.apache.catalina.deploy.LoginConfig;
+import org.apache.catalina.realm.GenericPrincipal;
+import org.apache.log4j.Logger;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Component for sending login requests to Facebook.
+ * 
+ * @author Anil Saldhana
+ * @author Marcel Kolsteren
+ * @since May 8, 2011
+ */
+public class FacebookAuthenticator extends FormAuthenticator 
+{ 
+   protected static Logger log = Logger.getLogger(FacebookAuthenticator.class);
+   protected boolean trace = log.isTraceEnabled();
+   
+   public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
+   
+   public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
+   
+   protected  FacebookUtil util = new FacebookUtil(FacebookConstants.SERVICE_URL);
+   protected String returnURL;
+   protected String clientID;
+   protected String clientSecret;
+   protected String scope;
+   
+   protected List<String> roles = new ArrayList<String>();
+   
+   //Whether the authenticator has to to save and restore request
+   protected boolean saveRestoreRequest = true;
+   
+   public static String EMPTY_PASSWORD = "EMPTY";
+
+   
+   public enum STATES { AUTH, AUTHZ, FINISH};
+   
+   
+   public void setReturnURL(String returnURL)
+   {
+      this.returnURL = returnURL;
+   }
+
+   public void setClientID(String clientID)
+   {
+      this.clientID = clientID;
+   }
+
+   public void setScope(String scope)
+   {
+      this.scope = scope;
+   }
+
+   public void setClientSecret(String clientSecret)
+   {
+      this.clientSecret = clientSecret;
+   }
+   
+   public void setRoleString(String roleStr)
+   {
+      if(roleStr == null)
+         throw new RuntimeException("Role String is null in configuration");
+      StringTokenizer st = new StringTokenizer(roleStr, ",");
+      while(st.hasMoreElements())
+      {
+         roles.add(st.nextToken());
+      }
+   }
+   
+   public void setSaveRestoreRequest(boolean saveRestoreRequest)
+   {
+      this.saveRestoreRequest = saveRestoreRequest;
+   }
+
+   
+   @Override
+   public void start() throws LifecycleException
+   {
+      //Validate the input values
+      if(clientID == null)
+         throw new LifecycleException("clientID is not provided");
+      if(clientSecret == null)
+         throw new LifecycleException("clientSecret is not provided");
+      if(returnURL == null)
+         throw new LifecycleException("returnURL is not provided");
+      super.start();
+   }
+
+   @Override
+   public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
+   {  
+      if(trace) log.trace("authenticate");
+      
+      HttpSession session = request.getSession();
+      String state = (String) session.getAttribute("STATE");
+      
+      if(trace) log.trace("state="+ state);
+      
+      if( STATES.FINISH.name().equals(state))
+         return true;
+      
+      if( state == null || state.isEmpty())
+      {
+         Map<String, String> params = new HashMap<String, String>();
+         params.put(OAuthConstants.REDIRECT_URI_PARAMETER, this.returnURL);
+         params.put(OAuthConstants.CLIENT_ID_PARAMETER, this.clientID); 
+         if (scope != null)
+         {
+            params.put(OAuthConstants.SCOPE_PARAMETER, scope);
+         }
+         String location = new StringBuilder(FacebookConstants.SERVICE_URL).append("?").append(
+               util.createQueryString(params)).toString();
+         try
+         { 
+            session.setAttribute("STATE", STATES.AUTH.name());
+            if(trace) log.trace("Redirect:"+location);
+            response.sendRedirect(location);
+            return false;
+         }
+         catch (IOException e)
+         {
+            throw new RuntimeException(e);
+         } 
+      }
+      //We have sent an auth request
+      if( state.equals(STATES.AUTH.name()))
+      {
+         return handleAuthStage(request, response);
+         
+      }
+      
+      Principal facebookPrincipal = null;
+      if( state.equals(STATES.AUTHZ.name()))
+      {
+         Principal principal = null;
+         facebookPrincipal = handleAuthenticationResponse(request, response);
+
+         cachedPrincipal.set(facebookPrincipal);
+         
+         if(isJBossEnv())
+         {
+            cachedRoles.set(roles);
+            principal = context.getRealm().authenticate(facebookPrincipal.getName(), EMPTY_PASSWORD); 
+         }
+         else
+         { 
+            //Create a Tomcat Generic Principal
+            principal = new GenericPrincipal(getContainer().getRealm(), facebookPrincipal.getName(), null, roles, facebookPrincipal);
+         }
+         
+         request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, facebookPrincipal.getName());
+         request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
+         request.setUserPrincipal(principal);
+
+         if (saveRestoreRequest)
+         {
+            this.restoreRequest(request, request.getSessionInternal());
+         }
+         register(request, response, principal, Constants.FORM_METHOD, facebookPrincipal.getName(), "");
+         request.getSession().setAttribute("STATE", STATES.FINISH.name());
+
+         return true;
+      }
+      return false;
+   }
+   
+   protected void sendAuthorizeRequest(String returnUrl, HttpServletResponse response)
+   { 
+      //String returnUri = util.getReturnUri(returnUrl);
+      String returnUri = returnUrl;
+      
+      Map<String, String> params = new HashMap<String, String>();
+      params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
+      params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
+      if (scope != null)
+      {
+         params.put(OAuthConstants.SCOPE_PARAMETER, scope);
+      }
+      String location = new StringBuilder(FacebookConstants.AUTHENTICATION_ENDPOINT_URL).append("?").append(
+            util.createQueryString(params)).toString();
+      try
+      {
+         response.sendRedirect(location);
+      }
+      catch (IOException e)
+      {
+         throw new RuntimeException(e);
+      }
+   }
+   
+   protected URLConnection sendAccessTokenRequest(String returnUrl, String authorizationCode, HttpServletResponse response)
+   { 
+      String returnUri = returnURL;
+
+      Map<String, String> params = new HashMap<String, String>();
+      params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
+      params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
+      params.put(OAuthConstants.CLIENT_SECRET_PARAMETER, clientSecret);
+      params.put(OAuthConstants.CODE_PARAMETER, authorizationCode);
+      
+      String location = new StringBuilder(FacebookConstants.ACCESS_TOKEN_ENDPOINT_URL).append("?").append(
+            util.createQueryString(params)).toString();
+
+      try
+      {
+         if(trace) log.trace("AccessToken Request="+location);
+         URL url = new URL(location);
+         URLConnection connection = url.openConnection();
+         return connection;
+      }
+      catch (IOException e)
+      {
+         throw new RuntimeException(e);
+      }
+   }
+   
+   
+   
+   protected Principal handleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response)
+   {
+      String error = request.getParameter(OAuthConstants.ERROR_PARAMETER);
+      if (error != null)
+      {
+         throw new RuntimeException("error:" + error);
+      }
+      else
+      {
+         String returnUrl = returnURL;
+         String authorizationCode = request.getParameter(OAuthConstants.CODE_PARAMETER);
+         if (authorizationCode == null)
+         {
+            throw new RuntimeException("Authorization code parameter not found");
+         }
+
+         URLConnection connection = sendAccessTokenRequest(returnUrl, authorizationCode, response);
+
+         Map<String, String> params = formUrlDecode(readUrlContent(connection));
+         String accessToken = params.get(OAuthConstants.ACCESS_TOKEN_PARAMETER);
+         String expires = params.get(FacebookConstants.EXPIRES);
+         
+         if(trace) log.trace("Access Token=" + accessToken + " :: Expires=" + expires);
+         
+         if (accessToken == null)
+         {
+            throw new RuntimeException("No access token found");
+         } 
+         
+         return readInIdentity(request, response, accessToken, returnUrl);
+      } 
+   }
+   
+   private boolean handleAuthStage(HttpServletRequest request, HttpServletResponse response)
+   {
+      request.getSession().setAttribute("STATE",STATES.AUTHZ.name());
+      sendAuthorizeRequest(this.returnURL, response);
+      return false;
+   }
+   
+   
+   private boolean isJBossEnv()
+   {
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      Class<?> clazz = null;
+      try
+      {
+         clazz = tcl.loadClass("org.jboss.system.Service");
+      }
+      catch (ClassNotFoundException e)
+      { 
+      }
+      if( clazz != null )
+         return true;
+      return false;
+   }
+   
+   private Principal readInIdentity(HttpServletRequest request, HttpServletResponse response, String accessToken, String returnUrl)
+   {
+      FacebookPrincipal facebookPrincipal = null;
+      try
+      {
+         String urlString = new StringBuilder(FacebookConstants.PROFILE_ENDPOINT_URL).append("?access_token=").append(
+               URLEncoder.encode(accessToken, "UTF-8")).toString();
+         if(trace) log.trace("Profile read:"+urlString);
+         
+         URL profileUrl = new URL(urlString);
+         String profileContent = readUrlContent(profileUrl.openConnection());
+         JSONObject jsonObject = new JSONObject(profileContent);
+
+         facebookPrincipal = new FacebookPrincipal();
+         facebookPrincipal.setAccessToken(accessToken);
+         facebookPrincipal.setId(jsonObject.getString("id"));
+         facebookPrincipal.setName(jsonObject.getString("name"));
+         facebookPrincipal.setFirstName(jsonObject.getString("first_name"));
+         facebookPrincipal.setLastName(jsonObject.getString("last_name"));
+         facebookPrincipal.setGender(jsonObject.getString("gender"));
+         facebookPrincipal.setTimezone(jsonObject.getString("timezone"));
+         facebookPrincipal.setLocale(jsonObject.getString("locale"));
+         if (jsonObject.getString("email") != null)
+         {
+            facebookPrincipal.setEmail(jsonObject.getString("email"));
+         }
+      }
+      catch (JSONException e)
+      {
+         throw new RuntimeException(e);
+      }
+      catch (IOException e)
+      {
+         throw new RuntimeException(e);
+      }
+      
+      return facebookPrincipal;
+   }
+   
+   private String readUrlContent(URLConnection connection)
+   {
+      StringBuilder result = new StringBuilder();
+      try
+      {
+         Reader reader = new InputStreamReader(connection.getInputStream());
+         char[] buffer = new char[50];
+         int nrOfChars;
+         while ((nrOfChars = reader.read(buffer)) != -1)
+         {
+            result.append(buffer, 0, nrOfChars);
+         }
+      }
+      catch (IOException e)
+      {
+         throw new RuntimeException(e);
+      }
+      return result.toString();
+   }
+   
+   private Map<String, String> formUrlDecode(String encodedData)
+   {
+      Map<String, String> params = new HashMap<String, String>();
+      String[] elements = encodedData.split("&");
+      for (String element : elements)
+      {
+         String[] pair = element.split("=");
+         if (pair.length == 2)
+         {
+            String paramName = pair[0];
+            String paramValue;
+            try
+            {
+               paramValue = URLDecoder.decode(pair[1], "UTF-8");
+            }
+            catch (UnsupportedEncodingException e)
+            {
+               throw new RuntimeException(e);
+            }
+            params.put(paramName, paramValue);
+         }
+         else
+         {
+            throw new RuntimeException("Unexpected name-value pair in response: " + element);
+         }
+      }
+      return params;
+   }
+}
\ No newline at end of file

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,47 @@
+/*
+* JBoss, Home of Professional Open Source.
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* as indicated by the @author tags. See the copyright.txt file in the
+* distribution for a full listing of individual contributors. 
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.picketlink.social.facebook;
+
+/**
+ * Constants for facebook
+* @author Marcel Kolsteren
+* @author anil saldhana
+* @since Sep 26, 2010
+*/
+public class FacebookConstants
+{
+   public static final String AUTHENTICATION_ENDPOINT_URL = "https://graph.facebook.com/oauth/authorize";
+
+   public static final String ACCESS_TOKEN_ENDPOINT_URL = "https://graph.facebook.com/oauth/access_token";
+
+   public static final String PROFILE_ENDPOINT_URL = "https://graph.facebook.com/me";
+   
+   public static final String RETURN_URL_PARAMETER = "returnUrl";
+   
+   public static final String SERVICE_URL = "https://www.facebook.com/dialog/oauth";
+   
+   public static final String TYPE = "type";
+   
+   public static final String WEB_SERVER = "web_server";
+   
+   public static final String EXPIRES = "expires";
+}

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,70 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.social.facebook;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.List;
+
+import javax.security.auth.login.LoginException;
+import javax.security.auth.spi.LoginModule;
+
+import org.jboss.security.SimpleGroup;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
+
+/**
+ * A {@link LoginModule} for JBoss environment
+ * @author Anil Saldhana
+ * @since May 19, 2011
+ */
+public class FacebookLoginModule extends UsernamePasswordLoginModule
+{ 
+   @Override
+   protected Principal getIdentity()
+   {
+      return new SimplePrincipal(FacebookAuthenticator.cachedPrincipal.get().getName());
+   }
+
+   @Override
+   protected String getUsersPassword() throws LoginException
+   {
+      return FacebookAuthenticator.EMPTY_PASSWORD;
+   }
+
+   @Override
+   protected Group[] getRoleSets() throws LoginException
+   {   
+      Group group = new SimpleGroup("Roles"); 
+
+      List<String> roles = FacebookAuthenticator.cachedRoles.get();
+
+      if(roles != null)
+      {
+         for(String role: roles)
+         {
+            group.addMember(new SimplePrincipal(role));
+         }
+      }
+      return new Group[] {group};
+   }
+}
\ No newline at end of file

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,143 @@
+/*
+* JBoss, Home of Professional Open Source.
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* as indicated by the @author tags. See the copyright.txt file in the
+* distribution for a full listing of individual contributors. 
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.picketlink.social.facebook;
+
+import java.io.Serializable;
+import java.security.Principal;
+
+/**
+ * An instance of {@link Principal} representing a facebook user
+* @author Marcel Kolsteren
+* @since Sep 26, 2010
+*/
+public class FacebookPrincipal implements Principal, Serializable
+{ 
+   private static final long serialVersionUID = 8086364702249670998L;
+
+   private String accessToken;
+
+   private String id;
+
+   private String name;
+
+   private String firstName;
+
+   private String lastName;
+
+   private String gender;
+
+   private String timezone;
+
+   private String locale;
+
+   private String email;
+
+   public String getAccessToken()
+   {
+      return accessToken;
+   }
+
+   public void setAccessToken(String accessToken)
+   {
+      this.accessToken = accessToken;
+   }
+
+   public String getId()
+   {
+      return id;
+   }
+
+   public void setId(String id)
+   {
+      this.id = id;
+   }
+
+   public String getFirstName()
+   {
+      return firstName;
+   }
+
+   public void setFirstName(String firstName)
+   {
+      this.firstName = firstName;
+   }
+
+   public String getLastName()
+   {
+      return lastName;
+   }
+
+   public void setLastName(String lastName)
+   {
+      this.lastName = lastName;
+   }
+
+   public String getGender()
+   {
+      return gender;
+   }
+
+   public void setGender(String gender)
+   {
+      this.gender = gender;
+   }
+
+   public String getTimezone()
+   {
+      return timezone;
+   }
+
+   public void setTimezone(String timezone)
+   {
+      this.timezone = timezone;
+   }
+
+   public String getLocale()
+   {
+      return locale;
+   }
+
+   public void setLocale(String locale)
+   {
+      this.locale = locale;
+   }
+
+   public void setName(String name)
+   {
+      this.name = name;
+   }
+
+   public String getName()
+   {
+      return name;
+   }
+
+   public String getEmail()
+   {
+      return email;
+   }
+
+   public void setEmail(String email)
+   {
+      this.email = email;
+   }
+}

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,79 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.social.facebook;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Map;
+
+/**
+ * Utility for facebook
+ * @author Anil Saldhana
+ * @since May 8, 2011
+ */
+public class FacebookUtil
+{
+   protected String serviceURL = null;
+   
+   public FacebookUtil(String url)
+   {
+      this.serviceURL = url;
+   }
+   
+   /**
+    * Given a {@link Map} of params, construct a query string
+    * @param params
+    * @return
+    */
+   public String createQueryString(Map<String, String> params)
+   {
+      StringBuilder queryString = new StringBuilder();
+      boolean first = true;
+      for (Map.Entry<String, String> entry : params.entrySet())
+      {
+         String paramName = entry.getKey();
+         String paramValue = entry.getValue();
+         if (first)
+         {
+            first = false;
+         }
+         else
+         {
+            queryString.append("&");
+         }
+         queryString.append(paramName).append("=");
+         String encodedParamValue;
+         try
+         {
+            if(paramValue == null)
+               throw new RuntimeException("paramValue is null");
+            encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
+         }
+         catch (UnsupportedEncodingException e)
+         {
+            throw new RuntimeException(e);
+         }
+         queryString.append(encodedParamValue);
+      }
+      return queryString.toString();
+   }
+}
\ No newline at end of file

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,44 @@
+/*
+* JBoss, Home of Professional Open Source.
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* as indicated by the @author tags. See the copyright.txt file in the
+* distribution for a full listing of individual contributors. 
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.picketlink.social.facebook;
+
+/**
+ * Constants defined by the OAuth spec
+ * @author Marcel Kolsteren
+ * @since Sep 26, 2010
+ */
+public class OAuthConstants
+{
+   public static final String CODE_PARAMETER = "code";
+
+   public static final String CLIENT_ID_PARAMETER = "client_id";
+
+   public static final String CLIENT_SECRET_PARAMETER = "client_secret";
+
+   public static final String SCOPE_PARAMETER = "scope";
+
+   public static final String REDIRECT_URI_PARAMETER = "redirect_uri";
+
+   public static final String ACCESS_TOKEN_PARAMETER = "access_token";
+
+   public static final String ERROR_PARAMETER = "error";
+}

Added: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java	                        (rev 0)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java	2011-05-20 04:16:43 UTC (rev 965)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.social.facebook;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextAssociation;
+import org.jboss.security.SecurityContextFactory;
+
+/**
+ * Privileged Blocks
+ * @author Anil Saldhana
+ * @since May 19, 2011
+ */
+class SecurityActions
+{
+   static SecurityContext createSecurityContext( final String name)
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
+      {
+         public SecurityContext run()
+         { 
+            try
+            {
+               return SecurityContextFactory.createSecurityContext(name);
+            }
+            catch (Exception e)
+            {
+               throw new RuntimeException(e);
+            }
+         }
+      });
+   }
+   
+   static void setSecurityContext( final SecurityContext sc)
+   {
+      AccessController.doPrivileged(new PrivilegedAction<Void>()
+      {
+
+         public Void run()
+         { 
+            SecurityContextAssociation.setSecurityContext(sc);
+            return null;
+         }
+      });
+   }
+   
+   static SecurityContext getSecurityContext()
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
+      {
+
+         public SecurityContext run()
+         { 
+            return SecurityContextAssociation.getSecurityContext();
+         }
+      });
+   }
+   
+   static ClassLoader getContextClassLoader()
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+      {
+
+         public ClassLoader run()
+         { 
+            return Thread.currentThread().getContextClassLoader();
+         }
+      });
+   }
+
+}
\ No newline at end of file



More information about the jboss-cvs-commits mailing list