rave-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mpie...@apache.org
Subject svn commit: r1160472 - in /incubator/rave/sandbox/science-gateways/rave-gateway-extensions: ./ src/main/java/org/apache/rave/portal/service/impl/ src/main/java/org/apache/rave/portal/web/ src/main/java/org/apache/rave/portal/web/api/ src/main/java/org/...
Date Mon, 22 Aug 2011 22:23:37 GMT
Author: mpierce
Date: Mon Aug 22 22:23:37 2011
New Revision: 1160472

URL: http://svn.apache.org/viewvc?rev=1160472&view=rev
Log:
(RAVE-207) Adding initial gateway REST service for credentials implementation

Added:
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/UserInfoRest.java
Modified:
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/pom.xml
    incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/service/impl/CommunityUserService.java

Modified: incubator/rave/sandbox/science-gateways/rave-gateway-extensions/pom.xml
URL: http://svn.apache.org/viewvc/incubator/rave/sandbox/science-gateways/rave-gateway-extensions/pom.xml?rev=1160472&r1=1160471&r2=1160472&view=diff
==============================================================================
--- incubator/rave/sandbox/science-gateways/rave-gateway-extensions/pom.xml (original)
+++ incubator/rave/sandbox/science-gateways/rave-gateway-extensions/pom.xml Mon Aug 22 22:23:37
2011
@@ -90,6 +90,13 @@
 		<scope>provided</scope>
 	 </dependency>
 
+	 <!-- JSON Dependencies -->
+    <dependency>
+      <groupId>org.json</groupId>
+      <artifactId>json</artifactId>
+      <version>20070829</version>
+    </dependency>
+
 	 <!-- Gridshib dependencies -->
 	 <dependency>
 		<groupId>edu.ncsa</groupId>

Modified: incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/service/impl/CommunityUserService.java
URL: http://svn.apache.org/viewvc/incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/service/impl/CommunityUserService.java?rev=1160472&r1=1160471&r2=1160472&view=diff
==============================================================================
--- incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/service/impl/CommunityUserService.java
(original)
+++ incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/service/impl/CommunityUserService.java
Mon Aug 22 22:23:37 2011
@@ -72,14 +72,15 @@ import xportlets.proxymanager.ProxyStora
  * myproxy-logon or similar.
  */
 @Service(value = "communityUserService")
-public class CommunityUserService extends DefaultUserService {
+//public class CommunityUserService extends DefaultUserService {
+public class CommunityUserService implements UserService {
 	 private static final String COMMUNITY_CREDENTIAL_LOCATION="community.credential.location";
     private static int defaultPort = 7512;
     private static int defaultLifeTime = 60*24*100;
 	 private static String defaultServer="myproxy.teragrid.org";
 
     protected static final Logger logger = LoggerFactory.getLogger(CommunityUserService.class);
-    private UserRepository userRepository;
+    protected UserRepository userRepository;
 
     // public static String trustedCertsFile = "trustedCAs";
     private String trustedCertsFile;
@@ -94,8 +95,7 @@ public class CommunityUserService extend
 
     @Autowired
     public CommunityUserService(UserRepository userRepository) {
-		  super(userRepository);
-		  //        this.userRepository = userRepository;
+		  this.userRepository = userRepository;
 		  myproxyHostname=defaultServer;
 		  myproxyLifeTime=defaultLifeTime;
 		  myproxyPortNumber=defaultPort;
@@ -105,7 +105,7 @@ public class CommunityUserService extend
 
     @Override
 	 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
DataAccessException {
-        log.debug("loadUserByUsername called with: " + username);
+        logger.debug("loadUserByUsername called with: " + username);
 		  logger.info("Running GSI login");
         final User user = userRepository.getByUsername(username);
         if(user == null) {
@@ -181,4 +181,76 @@ public class CommunityUserService extend
 				ex3.printStackTrace();
 		  }		  
 	 }
+    @Override
+    public User getAuthenticatedUser() {
+        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+        
+        if (authentication != null && authentication.getPrincipal() instanceof User)
{
+            return (User) authentication.getPrincipal();
+        } else {
+            throw new SecurityException("Could not get the authenticated user!");
+        }
+    }
+
+    @Override
+    public void setAuthenticatedUser(long userId) {
+        final User user = userRepository.get(userId);
+        if(user == null) {
+            throw new UsernameNotFoundException("User with id '" + userId + "' was not found!");
+        }
+        SecurityContext securityContext = createContext(user);
+        SecurityContextHolder.setContext(securityContext);
+    }
+
+    @Override
+    public void clearAuthenticatedUser() {
+        SecurityContextHolder.clearContext();
+    }
+
+    private SecurityContext createContext(final User user) {
+        SecurityContext securityContext = new SecurityContextImpl();
+        securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities())
{
+            @Override
+            public Object getCredentials() {
+                return "N/A";
+            }
+
+            @Override
+            public Object getPrincipal() {
+                return user;
+            }
+
+            @Override
+            public boolean isAuthenticated() {
+                return true;
+            }
+        });
+        return securityContext;
+    }
+
+	 @Override
+	 @Transactional
+	 public void registerNewUser(User user) {
+		  userRepository.save(user);
+	 }
+	 
+	 @Override
+	 public User getUserById(Long id) {
+		  return userRepository.get(id);
+	 }
+
+	 @Override
+	 public User getUserByUsername(String userName){
+		  return userRepository.getByUsername(userName);
+	 }
+
+	 @Override
+	 public User getUserByEmail(String userEmail){
+		  return userRepository.getByUserEmail(userEmail);
+	 }
+
+	 @Override
+	 public void updateUserProfile(User user) {
+		  System.out.println("Updating user profile");
+	 }
 }
\ No newline at end of file

Added: incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/UserInfoRest.java
URL: http://svn.apache.org/viewvc/incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/UserInfoRest.java?rev=1160472&view=auto
==============================================================================
--- incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/UserInfoRest.java
(added)
+++ incubator/rave/sandbox/science-gateways/rave-gateway-extensions/src/main/java/org/apache/rave/portal/web/api/rest/UserInfoRest.java
Mon Aug 22 22:23:37 2011
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rave.portal.web.api.rest;
+
+import java.io.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.rave.portal.service.UserService;
+import org.apache.rave.portal.model.User;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Controller;
+import org.springframework.util.ClassUtils;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import org.globus.gsi.GlobusCredential;
+import org.globus.gsi.gssapi.GlobusGSSCredentialImpl;
+import org.ietf.jgss.GSSCredential;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+//ProxyManager imports
+import xportlets.proxymanager.ProxyManager;
+import xportlets.proxymanager.ProxyStorageException;
+
+
+/**
+ * Handler for all services exposed under the /api/rest/callbacks path.
+ */
+@Controller(value="verify")
+@RequestMapping("/api/rest/callback/*")
+public class UserInfoRest {
+    private static Logger logger = LoggerFactory.getLogger(UserInfoRest.class);
+	 private UserService userService;
+	 
+    @Autowired
+    public UserInfoRest(UserService userService) {
+        this.userService = userService;
+    }       
+	 
+    @RequestMapping(value = "{email}", method = RequestMethod.POST)    
+    public String getUserInfo(@PathVariable String email, @RequestBody String postBody,HttpServletResponse
response) {
+		  logger.debug("POST received for /api/rest/callback/" + email);
+		  String jsonResponse="";
+		  try {
+				jsonResponse=processRequest(email,postBody);							 
+        }
+        catch(JSONException ex) {
+				logger.error("Invalid request:"+ex.getMessage());
+		  }
+		  return jsonResponse;
+    }    
+    
+    // TODO - when we implement security we can implement different exception
+    //        handlers for different errors (unauthorized, resource not found, etc)
+    @ExceptionHandler(Exception.class)
+    public String handleException(Exception ex, HttpServletRequest request, HttpServletResponse
response) {
+        logger.error("Error occured while accessing " + request.getRequestURL(), ex);   
    
+        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
+        return ClassUtils.getShortName(ex.getClass());
+    }
+
+	 /**
+	  * Process the incoming JSON request.  For backward compatiblity with the 
+	  * OGCE Gadget Container, we keep "userid" in the JSON message format, but this
+	  * is the username, not userid, in Rave.
+	  */
+	 private String processRequest(String userEmail, String postBody) throws JSONException {
+		  User user=userService.getUserByEmail(userEmail);
+		  JSONObject resultObj = new JSONObject();
+		  
+		  //Convert the incoming post body to a JSON array.  This could include
+		  //multiple requests.
+		  JSONArray array = new JSONArray(postBody);
+		  JSONArray result = new JSONArray();
+		  
+		  //Convert each entry into a JSON object and extract information.
+		  for(int i = 0; i < array.length(); ++i) {
+				JSONObject obj = array.getJSONObject(i);
+				String username = obj.optString("userid");
+				String email = obj.getString("email");
+				JSONObject aresultObj = new JSONObject();
+				if (username != null) {
+					 aresultObj.put("userid", username);
+				}
+				aresultObj.put("email", email);
+				if (user != null) {
+					 aresultObj.put("valid", true);
+					 username = user.getUsername();
+					 aresultObj.put("userid", username);
+					 
+					 String certStr = getCertStr(username);
+					 if (certStr != null) {
+						  aresultObj.put("cert", certStr);
+					 }
+					 else {
+								aresultObj.put("cert", "");
+					 }
+				} else
+					 aresultObj.put("valid", false);
+				
+				result.put(aresultObj);
+		  }
+        
+		  resultObj.put("result", result);
+		  resultObj.put("status", "succ");
+		  return resultObj.toString();	  
+    }    
+
+    /**
+     * Get serialized certificate.
+     */
+    private String getCertStr (String username) {
+		  if (username == null || username.equals("")) return null;
+		  String returnProxyStr=null;
+		  GSSCredential proxy = null;
+		  try {
+				proxy = ProxyManager.getDefaultProxy(username);
+				if (proxy == null) return null;
+				
+				if (proxy instanceof GlobusGSSCredentialImpl) {
+					 GlobusCredential globusCred = ((GlobusGSSCredentialImpl)
+															  proxy).getGlobusCredential();
+					 ByteArrayOutputStream baos = new ByteArrayOutputStream();
+					 globusCred.save(baos);
+					 returnProxyStr = baos.toString("UTF-8");
+					 baos.close();
+					 return returnProxyStr;
+				} else {
+					 logger.error("retrieved proxy is not an instance of GlobusGSSCredentialImpl.");
+					 return null;
+				}
+		  }
+		  catch(Exception ex) {
+				logger.error("Could not set the proxy string: "+ex.getMessage());
+		  }
+		  //If we get here, we are returning null.
+		  logger.error("Couldn't set the proxy string correctly: "+returnProxyStr);
+		  return returnProxyStr;
+	 }
+}
\ No newline at end of file



Mime
View raw message