[Yanel-commits] rev 21412 - in public/yanel/trunk/src/core/java/org/wyona/yanel: cmdl core core/map servlet

michi at wyona.com michi at wyona.com
Thu Jan 4 12:46:29 CET 2007


Author: michi
Date: 2007-01-04 12:46:28 +0100 (Thu, 04 Jan 2007)
New Revision: 21412

Modified:
   public/yanel/trunk/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java
   public/yanel/trunk/src/core/java/org/wyona/yanel/core/Yanel.java
   public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/Realm.java
   public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/RealmConfiguration.java
   public/yanel/trunk/src/core/java/org/wyona/yanel/servlet/YanelServlet.java
Log:
realm configuration simplified

Modified: public/yanel/trunk/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java
===================================================================
--- public/yanel/trunk/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java	2007-01-04 11:43:41 UTC (rev 21411)
+++ public/yanel/trunk/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java	2007-01-04 11:46:28 UTC (rev 21412)
@@ -71,10 +71,8 @@
 
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
-        Path path = null;
-        if (args.length == 1 && args[0].length() > 0) {
-            path = new Path(args[0]);
-        } else {
+        String url = null;
+        if (args.length != 1 || args[0].length() == 0) {
             System.out.println("\nPlease enter a path (e.g. /index.html):");
             try {
                 String value = br.readLine();
@@ -83,25 +81,29 @@
                    return;
                 }
                 System.out.println("The following value has been entered: " + value);
-                path = new Path(value);
+                url = value;
             } catch (Exception e) {
                 System.err.println(e);
             }
         }
 
       
-        PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
+        Realm realm = map.getRealm(url);
+        Path path = map.getPath(realm, url);
+        //PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
+        PolicyManager pm = realm.getPolicyManager();
     
 
         String[] groupnames = {"admin", "accounting"};
-        if (pm.authorize(new org.wyona.commons.io.Path(path.toString()), new Identity("lenya", groupnames), new Role("view"))) {
+        if (pm.authorize(path, new Identity("lenya", groupnames), new Role("view"))) {
             System.out.println("Access granted: " + path);
         } else {
             // TODO: Deny access resp. start login process!
             System.out.println("Access denied: " + path);
         }
 
-        String rti = map.getResourceTypeIdentifier(path);
+        String rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path).getUniversalName();
+        //String rti = map.getResourceTypeIdentifier(path);
         System.out.println("Resource Type Identifier: " + rti);
 
         if (rti == null) {
@@ -121,7 +123,7 @@
 
 
         Resource res = null;
-        CommandLineRequest request = new CommandLineRequest(path.toString());
+        CommandLineRequest request = new CommandLineRequest(url);
         CommandLineResponse response = new CommandLineResponse();
         try {
             res = rtr.newResource(rti);
@@ -145,7 +147,7 @@
             System.out.println("View Descriptors: " + ((ViewableV1) res).getViewDescriptors());
             String viewId = null;
             try {
-                View view = ((ViewableV1) res).getView(path, viewId);
+                View view = ((ViewableV1) res).getView(new Path(url), viewId);
                 System.out.println("mime-type: " + view.getMimeType());
 
                 BufferedReader bReader = new BufferedReader(new java.io.InputStreamReader(view.getInputStream()));
@@ -164,7 +166,7 @@
 
         if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) {
             try {
-                java.io.Reader reader = ((ModifiableV1) res).getReader(path);
+                java.io.Reader reader = ((ModifiableV1) res).getReader(new Path(url));
             } catch (Exception e) {
                 System.err.println(e.getMessage());
             }

Modified: public/yanel/trunk/src/core/java/org/wyona/yanel/core/Yanel.java
===================================================================
--- public/yanel/trunk/src/core/java/org/wyona/yanel/core/Yanel.java	2007-01-04 11:43:41 UTC (rev 21411)
+++ public/yanel/trunk/src/core/java/org/wyona/yanel/core/Yanel.java	2007-01-04 11:46:28 UTC (rev 21412)
@@ -16,9 +16,12 @@
 
 package org.wyona.yanel.core;
 
+import org.wyona.security.core.api.IdentityManager;
+import org.wyona.security.core.api.PolicyManager;
 import org.wyona.yanel.core.map.Map;
 import org.wyona.yanel.core.map.Realm;
 import org.wyona.yanel.core.map.RealmConfiguration;
+import org.wyona.yarep.core.Repository;
 import org.wyona.yarep.core.RepositoryFactory;
 import org.springframework.beans.factory.BeanFactory;
 import org.springframework.context.ApplicationContext;
@@ -34,6 +37,7 @@
     private ApplicationContext applicationContext;
     private RealmConfiguration realmConfig;
     private ResourceManager resourceManager;
+    private boolean isInitialized = false;
     
     private static final String SPRING_CONFIG_FILE = "spring-*-config.xml"; 
 
@@ -47,6 +51,12 @@
    } 
    
    public void init() throws Exception {
+       if (isInitialized) {
+           return;
+       } else {
+           isInitialized = true;
+       }
+       
        map = (Map) applicationContext.getBean("map");
        realmConfig = new RealmConfiguration();
        map.setRealmConfiguration(realmConfig);
@@ -54,6 +64,18 @@
        rtr = new ResourceTypeRegistry();
        resourceManager = new ResourceManager();
        resourceManager.setResourceTypeRegistry(rtr);
+       
+       /*PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
+       IdentityManager im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager");
+       
+       Realm[] realms = realmConfig.getRealms();
+       for (int i=0; i<realms.length; i++) {
+           pm.addPoliciesRepository(realms[i].getPoliciesRepository());
+           im.addIdentitiesRepository(realms[i].getIdentitiesRepository());
+       }
+
+       im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager");*/
+
     }
    
     public static Yanel getInstance() throws Exception {

Modified: public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/Realm.java
===================================================================
--- public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/Realm.java	2007-01-04 11:43:41 UTC (rev 21411)
+++ public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/Realm.java	2007-01-04 11:46:28 UTC (rev 21412)
@@ -17,6 +17,8 @@
 package org.wyona.yanel.core.map;
 
 import org.wyona.commons.io.Path;
+import org.wyona.security.core.api.IdentityManager;
+import org.wyona.security.core.api.PolicyManager;
 import org.wyona.yarep.core.Repository;
 
 /**
@@ -29,6 +31,8 @@
     private Path mountPoint;
     private Repository repository;
     private Repository rtiRepository;
+    private PolicyManager policyManager;
+    private IdentityManager identityManager;
 
     private String proxyHostName;
     private String proxyPort;
@@ -133,5 +137,20 @@
         this.rtiRepository = repository;
     }
 
+    public IdentityManager getIdentityManager() {
+        return identityManager;
+    }
 
+    public void setIdentityManager(IdentityManager identityManager) {
+        this.identityManager = identityManager;
+    }
+
+    public PolicyManager getPolicyManager() {
+        return policyManager;
+    }
+
+    public void setPolicyManager(PolicyManager policyManager) {
+        this.policyManager = policyManager;
+    }
+
 }

Modified: public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/RealmConfiguration.java
===================================================================
--- public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/RealmConfiguration.java	2007-01-04 11:43:41 UTC (rev 21411)
+++ public/yanel/trunk/src/core/java/org/wyona/yanel/core/map/RealmConfiguration.java	2007-01-04 11:46:28 UTC (rev 21412)
@@ -17,6 +17,7 @@
 package org.wyona.yanel.core.map;
 
 import java.io.File;
+import java.io.IOException;
 import java.lang.ClassNotFoundException;
 import java.lang.IllegalAccessException;
 import java.lang.InstantiationException;
@@ -30,7 +31,13 @@
 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
 
 import org.wyona.commons.io.FileUtil;
+import org.wyona.security.core.IdentityManagerFactory;
+import org.wyona.security.core.PolicyManagerFactory;
+import org.wyona.security.core.api.IdentityManager;
+import org.wyona.security.core.api.PolicyManager;
+import org.wyona.yanel.core.ConfigurationException;
 import org.wyona.yanel.core.Yanel;
+import org.wyona.yarep.core.Repository;
 import org.wyona.yarep.core.RepositoryFactory;
 
 /**
@@ -53,14 +60,14 @@
     /**
      *
      */
-    public RealmConfiguration() {
+    public RealmConfiguration() throws ConfigurationException {
         this(DEFAULT_CONFIGURATION_FILE);
     }
 
     /**
      *
      */
-    public RealmConfiguration(String configurationFile) {
+    public RealmConfiguration(String configurationFile) throws ConfigurationException {
         CONFIGURATION_FILE = configurationFile;
 
         propertiesURL = RealmConfiguration.class.getClassLoader().getResource(CONFIGURATION_FILE);
@@ -80,9 +87,10 @@
             }
             log.debug("Realms Configuration: " + realmsConfigFile);
             readRealms();
-            assignRepositories();
-        } catch (Exception e) {
-            log.error(e);
+            //assignRepositories();
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+            throw new ConfigurationException("Could not load realms configuration file: " + propertiesURL);
         }
     }
 
@@ -96,13 +104,21 @@
     /**
      *
      */
-    public void readRealms() {
+    public void readRealms() throws ConfigurationException {
         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
         Configuration config;
 
         try {
+            Yanel yanel = Yanel.getInstance();
+            PolicyManagerFactory pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory");
+            IdentityManagerFactory imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory");
+
+            RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory");
+            RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory");
+            RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory");
+            RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory");
             config = builder.buildFromFile(realmsConfigFile);
-
+            
             Configuration[] realmElements = config.getChildren("realm");
             for (int i = 0;i < realmElements.length; i++) {
                 String mountPoint = realmElements[i].getAttribute("mount-point", null);
@@ -114,7 +130,42 @@
                 if (proxy != null) {
                     realm.setProxy(proxy.getChild("host-name").getValue(), proxy.getChild("port").getValue(""), proxy.getChild("prefix").getValue());
                 }
-                log.debug("Realm: " + realm);
+                Configuration configElement = realmElements[i].getChild("config", false);
+                if (configElement == null) {
+                    throw new ConfigurationException("Missing <config src=\"...\"/> child element for realm " + realmId);
+                }
+                String configSrc = configElement.getAttribute("src", null);
+                
+                File realmConfigFile = resolveFile(new File(configSrc), realmsConfigFile);
+                log.debug("Reading realm config file for [" + realmId + "]: " + realmConfigFile);
+                Configuration realmConfig = builder.buildFromFile(realmConfigFile);
+                
+                String repoConfigSrc = realmConfig.getChild("data", false).getValue();
+                File repoConfig = resolveFile(new File(repoConfigSrc), realmConfigFile);
+                realm.setRepository(repoFactory.newRepository(realmId, repoConfig));
+                
+                repoConfigSrc = realmConfig.getChild("rti", false).getValue();
+                repoConfig = resolveFile(new File(repoConfigSrc), realmConfigFile);
+                realm.setRTIRepository(rtiRepoFactory.newRepository(realmId, repoConfig));
+                
+                Configuration repoConfigElement = realmConfig.getChild("ac-policies", false);
+                if (repoConfigElement != null) {
+                    repoConfig = resolveFile(new File(repoConfigElement.getValue()), realmConfigFile);
+                    Repository policiesRepo = policiesRepoFactory.newRepository(realmId, repoConfig);
+                    PolicyManager policyManager = pmFactory.newPolicyManager(policiesRepo);
+                    realm.setPolicyManager(policyManager);
+                }
+                
+                repoConfigElement = realmConfig.getChild("ac-identities", false);
+                if (repoConfigElement != null) {
+                    repoConfig = resolveFile(new File(repoConfigElement.getValue()), realmConfigFile);
+                    Repository identitiesRepo = identitiesRepoFactory.newRepository(realmId, repoConfig);
+                    IdentityManager identityManager = imFactory.newIdentityManager(identitiesRepo);
+                    realm.setIdentityManager(identityManager);
+                }
+                
+                log.info("Realm: " + realm);
+                
                 hm.put(realmId, realm);
                 if (rootFlag.equals("true")) {
                     log.debug("Root realm found: " + realm.getID());
@@ -127,10 +178,30 @@
                 }
             }
         } catch (Exception e) {
-            log.error(e);
+            log.error(e.getMessage(), e);
+            throw new ConfigurationException("Error reading realm configuration from file " + 
+                    realmsConfigFile + ": " + e.getMessage(), e);
         }
         inheritRootRealmProperties();
     }
+    
+    /**
+     * If the given file has a relative path, resolve it relative to the given dir.
+     * If dir is in fact a file, the resolving will use the parent dir of that file.  
+     * @param file
+     * @param dir
+     * @return
+     */
+    protected File resolveFile(File file, File dir) {
+        if (!file.isAbsolute()) {
+            if (dir.isDirectory()) {
+                file = FileUtil.file(dir.getAbsolutePath(), file.toString());
+            } else {
+                file = FileUtil.file(dir.getParentFile().getAbsolutePath(), file.toString());
+            }
+        }
+        return file;
+    }
 
     /**
      *
@@ -173,26 +244,13 @@
                 realm.setProxy(rootRealm.getProxyHostName(), rootRealm.getProxyPort(), rootRealm.getProxyPrefix());
                 log.debug("Inherit root realm properties to realm: " + key);
             }
+            if (realm.getIdentityManager() == null) {
+                realm.setIdentityManager(rootRealm.getIdentityManager());
+            }
+            if (realm.getPolicyManager() == null) {
+                realm.setPolicyManager(rootRealm.getPolicyManager());
+            }
         }
     }
     
-    /**
-     * Assigns the repositories to the realms.
-     * Each realm has a default data repository and a rti repository.
-     * The id of the realm matches the id of the repository.
-     */
-    private void assignRepositories() throws Exception {
-        RepositoryFactory defaultRepoFactory = Yanel.getInstance().getRepositoryFactory("DefaultRepositoryFactory");
-        RepositoryFactory rtiRepoFactory = Yanel.getInstance().getRepositoryFactory("RTIRepositoryFactory");
-        
-        java.util.Iterator keyIterator = hm.keySet().iterator();
-        while(keyIterator.hasNext()) {
-            String key = (String)keyIterator.next();
-            Realm realm = (Realm)hm.get(key);
-            
-            realm.setRepository(defaultRepoFactory.newRepository(realm.getID()));
-            realm.setRTIRepository(rtiRepoFactory.newRepository(realm.getID()));
-        }
-        
-    }
 }

Modified: public/yanel/trunk/src/core/java/org/wyona/yanel/servlet/YanelServlet.java
===================================================================
--- public/yanel/trunk/src/core/java/org/wyona/yanel/servlet/YanelServlet.java	2007-01-04 11:43:41 UTC (rev 21411)
+++ public/yanel/trunk/src/core/java/org/wyona/yanel/servlet/YanelServlet.java	2007-01-04 11:46:28 UTC (rev 21412)
@@ -41,6 +41,7 @@
 import org.wyona.yanel.servlet.communication.HttpResponse;
 import org.wyona.yanel.util.ResourceAttributeHelper;
 
+import org.wyona.security.core.AuthenticationException;
 import org.wyona.security.core.api.Identity;
 import org.wyona.security.core.api.IdentityManager;
 import org.wyona.security.core.api.PolicyManager;
@@ -65,8 +66,8 @@
 
     ResourceTypeRegistry rtr;
 
-    PolicyManager pm;
-    IdentityManager im;
+    //PolicyManager pm;
+    //IdentityManager im;
     Map map;
     Yanel yanel;
 
@@ -97,9 +98,9 @@
             
             rtr = yanel.getResourceTypeRegistry();
 
-            pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
+            //pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
 
-            im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager");
+            //im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager");
           
             map = (Map) yanel.getBeanFactory().getBean("map");
 
@@ -756,8 +757,17 @@
         }
 
         boolean authorized = false;
-        Realm realm = map.getRealm(new Path(request.getServletPath()));
+        Realm realm;
+        Path path;
+        try {
+            realm = map.getRealm(request.getServletPath());
+            path = map.getPath(realm, request.getServletPath());
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            throw new ServletException(e.getMessage(), e);
+        }
 
+
         // HTTP BASIC Authorization (For clients such as for instance Sunbird, OpenOffice or cadaver)
         // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling
         String authorization = request.getHeader("Authorization");
@@ -775,8 +785,9 @@
                 String username = up[0];
                 String password = up[1];
                 log.debug("username: " + username + ", password: " + password);
-                if (im.authenticate(username, password, realm.getID())) {
-                    authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), new Identity(username, null), new Role("view"));
+                try {
+                if (realm.getIdentityManager().authenticate(username, password)) {
+                    authorized = realm.getPolicyManager().authorize(path, new Identity(username, null), new Role("view"));
                     if(authorized) {
                         return null;
                     } else {
@@ -795,6 +806,10 @@
                     writer.print("BASIC Authentication Failed!");
                     return response;
                 }
+                } catch (Exception e) {
+                    log.error(e.getMessage(), e);
+                    throw new ServletException(e.getMessage(), e);
+                }
             } else if (authorization.toUpperCase().startsWith("DIGEST")) {
                 log.error("DIGEST is not implemented");
                 authorized = false;
@@ -819,8 +834,20 @@
             log.debug("Identity is WORLD");
             identity = new Identity();
         }
-        authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role);
+        
+        
+        //authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role);
+        
+        try {
+            log.error("authorize: realm: " + realm + ", path: " + path + ", identity: " + identity.getUsername() + ", role: " + role.getName());
+            authorized = realm.getPolicyManager().authorize(path, identity, role);
+            log.error("authorize result: " + authorized);
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            throw new ServletException(e.getMessage(), e);
+        }
 
+
         if(!authorized) {
             log.warn("Access denied: " + getRequestURLQS(request, null, false));
 
@@ -852,6 +879,7 @@
             StringBuffer sb = new StringBuffer("");
             String neutronVersions = request.getHeader("Neutron");
             String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
+            
             if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
                 log.debug("Neutron Versions supported by client: " + neutronVersions);
                 log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
@@ -897,17 +925,19 @@
      *
      */
     private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) {
-        Realm realm = map.getRealm(new Path(request.getServletPath()));
-        // TODO: Handle this exception more gracefully!
-        if (realm == null) log.error("No realm found for path " + new Path(request.getServletPath()));
-        String proxyHostName = realm.getProxyHostName();
-        String proxyPort = realm.getProxyPort();
-        String proxyPrefix = realm.getProxyPrefix();
-
-        URL url = null;
+        //Realm realm = map.getRealm(new Path(request.getServletPath()));
+        try {
+            Realm realm = map.getRealm(request.getServletPath());
     
-        try {
-        url = new URL(request.getRequestURL().toString());
+            // TODO: Handle this exception more gracefully!
+            if (realm == null) log.error("No realm found for path " + new Path(request.getServletPath()));
+            String proxyHostName = realm.getProxyHostName();
+            String proxyPort = realm.getProxyPort();
+            String proxyPrefix = realm.getProxyPrefix();
+    
+            URL url = null;
+        
+            url = new URL(request.getRequestURL().toString());
 
             if (proxyHostName != null) {
                 url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
@@ -928,23 +958,24 @@
             if(proxyHostName != null || proxyPort != null || proxyPrefix != null) {
                 log.debug("Proxy enabled request: " + url);
             }
+
+            String urlQS = url.toString();
+            if (request.getQueryString() != null) {
+                urlQS = urlQS + "?" + request.getQueryString();
+                if (addQS != null) urlQS = urlQS + "&" + addQS;
+            } else {
+                if (addQS != null) urlQS = urlQS + "?" + addQS;
+            }
+    
+            if (xml) urlQS = urlQS.replaceAll("&", "&amp;");
+    
+            log.debug("Request: " + urlQS);
+
+            return urlQS;
         } catch (Exception e) {
             log.error(e);
+            return null;
         }
-
-        String urlQS = url.toString();
-        if (request.getQueryString() != null) {
-            urlQS = urlQS + "?" + request.getQueryString();
-            if (addQS != null) urlQS = urlQS + "&" + addQS;
-        } else {
-            if (addQS != null) urlQS = urlQS + "?" + addQS;
-        }
-
-        if (xml) urlQS = urlQS.replaceAll("&", "&amp;");
-
-        log.debug("Request: " + urlQS);
-
-        return urlQS;
     }
 
     /**
@@ -1009,13 +1040,16 @@
      */
     public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
-        Realm realm = map.getRealm(new Path(request.getServletPath()));
+        try {
+            Realm realm = map.getRealm(request.getServletPath());
+            Path path = map.getPath(realm, request.getServletPath());
+            //Realm realm = map.getRealm(new Path(request.getServletPath()));
 
         // HTML Form based authentication
         String loginUsername = request.getParameter("yanel.login.username");
         if(loginUsername != null) {
             HttpSession session = request.getSession(true);
-            if (im.authenticate(loginUsername, request.getParameter("yanel.login.password"), realm.getID())) {
+            if (realm.getIdentityManager().authenticate(loginUsername, request.getParameter("yanel.login.password"))) {
                 log.debug("Realm: " + realm);
                 session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null));
                 return null;
@@ -1026,62 +1060,100 @@
             }
         }
 
-        // Neutron-Auth based authentication
-        String yanelUsecase = request.getParameter("yanel.usecase");
-        if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
-            log.debug("Neutron Authentication ...");
+            // Neutron-Auth based authentication
+            String yanelUsecase = request.getParameter("yanel.usecase");
+            if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
+                log.debug("Neutron Authentication ...");
 
-            String username = null;
-            String password = null;
-            String originalRequest = null;
-            DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
-            try {
-                Configuration config = builder.build(request.getInputStream());
+                String username = null;
+                String password = null;
+                String originalRequest = null;
+                DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
+                try {
+                    Configuration config = builder.build(request.getInputStream());
 
-                Configuration originalRequestConfig = config.getChild("original-request");
-                originalRequest = originalRequestConfig.getAttribute("url", null);
+                    Configuration originalRequestConfig = config.getChild("original-request");
+                    originalRequest = originalRequestConfig.getAttribute("url", null);
 
-                Configuration[] paramConfig = config.getChildren("param");
-                for (int i = 0; i < paramConfig.length; i++) {
-                    String paramName = paramConfig[i].getAttribute("name", null);
-                    if (paramName != null) {
-                        if (paramName.equals("username")) {
-                            username = paramConfig[i].getValue();
-                        } else if (paramName.equals("password")) {
-                            password = paramConfig[i].getValue();
+                    Configuration[] paramConfig = config.getChildren("param");
+                    for (int i = 0; i < paramConfig.length; i++) {
+                        String paramName = paramConfig[i].getAttribute("name", null);
+                        if (paramName != null) {
+                            if (paramName.equals("username")) {
+                                username = paramConfig[i].getValue();
+                            } else if (paramName.equals("password")) {
+                                password = paramConfig[i].getValue();
+                            }
                         }
                     }
+                } catch(Exception e) {
+                    log.warn(e);
                 }
-            } catch(Exception e) {
-                log.warn(e);
-            }
 
-            log.debug("Username: " + username);
+                log.debug("Username: " + username);
 
-            if (username != null) {
-                HttpSession session = request.getSession(true);
-                log.debug("Realm ID: " + realm.getID());
-                if (im.authenticate(username, password, realm.getID())) {
-                    log.info("Authentication successful: " + username);
-                    session.setAttribute(IDENTITY_KEY, new Identity(username, null));
+                if (username != null) {
+                    HttpSession session = request.getSession(true);
+                    log.debug("Realm ID: " + realm.getID());
+                    if (realm.getIdentityManager().authenticate(username, password)) {
+                        log.info("Authentication successful: " + username);
+                        session.setAttribute(IDENTITY_KEY, new Identity(username, null));
 
-                    // TODO: send some XML content, e.g. <authentication-successful/>
-                    response.setContentType("text/plain");
-                    response.setStatus(response.SC_OK);
+                        // TODO: send some XML content, e.g. <authentication-successful/>
+                        response.setContentType("text/plain");
+                        response.setStatus(response.SC_OK);
 
-                    PrintWriter writer = response.getWriter();
-                    writer.print("Neutron Authentication Successful!");
-                    return response;
+                        PrintWriter writer = response.getWriter();
+                        writer.print("Neutron Authentication Successful!");
+                        return response;
+                    } else {
+                        log.warn("Neutron Authentication failed: " + username);
+
+                        // TODO: Refactor this code with the one from doAuthenticate ...
+                        log.debug("Original Request: " + originalRequest);
+
+                        StringBuffer sb = new StringBuffer("");
+                        sb.append("<?xml version=\"1.0\"?>");
+                        sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
+                        sb.append("<message>Authentication failed!</message>");
+                        sb.append("<authentication>");
+                        // TODO: ...
+                        sb.append("<original-request url=\"" + originalRequest + "\"/>");
+                        //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
+                        //TODO: Also support https ...
+                        // TODO: ...
+                        sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">");
+                        //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
+                        sb.append("<form>");
+                        sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
+                        sb.append("<param description=\"Username\" name=\"username\"/>");
+                        sb.append("<param description=\"Password\" name=\"password\"/>");
+                        sb.append("</form>");
+                        sb.append("</login>");
+                        // NOTE: Needs to be a full URL, because user might switch the server ...
+                        // TODO: ...
+                        sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
+                        sb.append("</authentication>");
+                        sb.append("</exception>");
+
+                        log.debug("Neutron-Auth response: " + sb);
+
+                        response.setContentType("application/xml");
+                        response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
+                        response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
+
+                        PrintWriter w = response.getWriter();
+                        w.print(sb);
+                        return response;
+                    }
                 } else {
-                    log.warn("Neutron Authentication failed: " + username);
+                    // TODO: Refactor resp. reuse response from above ...
+                    log.warn("Neutron Authentication failed because username is NULL!");
 
-                    // TODO: Refactor this code with the one from doAuthenticate ...
-                    log.debug("Original Request: " + originalRequest);
-
                     StringBuffer sb = new StringBuffer("");
                     sb.append("<?xml version=\"1.0\"?>");
                     sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
-                    sb.append("<message>Authentication failed!</message>");
+                    sb.append("<message>Authentication failed because no username was sent!</message>");
                     sb.append("<authentication>");
                     // TODO: ...
                     sb.append("<original-request url=\"" + originalRequest + "\"/>");
@@ -1102,55 +1174,21 @@
                     sb.append("</authentication>");
                     sb.append("</exception>");
 
-                    log.debug("Neutron-Auth response: " + sb);
-
                     response.setContentType("application/xml");
                     response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
                     response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
 
-                    PrintWriter w = response.getWriter();
-                    w.print(sb);
+                    PrintWriter writer = response.getWriter();
+                    writer.print(sb);
                     return response;
                 }
             } else {
-                // TODO: Refactor resp. reuse response from above ...
-                log.warn("Neutron Authentication failed because username is NULL!");
-
-                StringBuffer sb = new StringBuffer("");
-                sb.append("<?xml version=\"1.0\"?>");
-                sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
-                sb.append("<message>Authentication failed because no username was sent!</message>");
-                sb.append("<authentication>");
-                // TODO: ...
-                sb.append("<original-request url=\"" + originalRequest + "\"/>");
-                //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
-                //TODO: Also support https ...
-                // TODO: ...
-                sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">");
-                //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
-                sb.append("<form>");
-                sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
-                sb.append("<param description=\"Username\" name=\"username\"/>");
-                sb.append("<param description=\"Password\" name=\"password\"/>");
-                sb.append("</form>");
-                sb.append("</login>");
-                // NOTE: Needs to be a full URL, because user might switch the server ...
-                // TODO: ...
-                sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
-                sb.append("</authentication>");
-                sb.append("</exception>");
-
-                response.setContentType("application/xml");
-                response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
-                response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
-
-                PrintWriter writer = response.getWriter();
-                writer.print(sb);
-                return response;
+                log.debug("Neutron Authentication successful.");
+                return null;
             }
-        } else {
-            log.debug("Neutron Authentication successful.");
-            return null;
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            throw new ServletException(e.getMessage(), e);
         }
     }
 




More information about the Yanel-commits mailing list