You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by bh...@apache.org on 2014/08/12 12:34:52 UTC

[01/28] git commit: updated refs/heads/master to ae207be

Repository: cloudstack
Updated Branches:
  refs/heads/master bc92bfd82 -> ae207bea9


CLOUDSTACK-7083: Add SAML2 SSO plugin skeleton and stub

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c4f20026
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c4f20026
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c4f20026

Branch: refs/heads/master
Commit: c4f200265bf87b11e9e2091724bf2b330fd6924a
Parents: bc92bfd
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 5 17:03:44 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:28 2014 +0200

----------------------------------------------------------------------
 plugins/pom.xml                                 |  1 +
 .../saml2/findbugsExcludeFilter.xml             | 25 +++++++++++
 plugins/user-authenticators/saml2/pom.xml       | 29 ++++++++++++
 .../META-INF/cloudstack/saml2/module.properties | 18 ++++++++
 .../cloudstack/saml2/spring-saml2-context.xml   | 32 ++++++++++++++
 .../cloudstack/SAML2UserAuthenticator.java      | 46 ++++++++++++++++++++
 .../cloudstack/SAML2UserAuthenticatorTest.java  | 39 +++++++++++++++++
 7 files changed, 190 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/pom.xml b/plugins/pom.xml
index b3890c0..0b1b62d 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -72,6 +72,7 @@
     <module>user-authenticators/ldap</module>
     <module>user-authenticators/md5</module>
     <module>user-authenticators/plain-text</module>
+    <module>user-authenticators/saml2</module>
     <module>user-authenticators/sha256salted</module>
     <module>network-elements/dns-notifier</module>
     <module>storage/image/s3</module>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/findbugsExcludeFilter.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/findbugsExcludeFilter.xml b/plugins/user-authenticators/saml2/findbugsExcludeFilter.xml
new file mode 100644
index 0000000..d372850
--- /dev/null
+++ b/plugins/user-authenticators/saml2/findbugsExcludeFilter.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+
+-->
+<FindBugsFilter>
+
+
+</FindBugsFilter>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/pom.xml b/plugins/user-authenticators/saml2/pom.xml
new file mode 100644
index 0000000..bfe5eb7
--- /dev/null
+++ b/plugins/user-authenticators/saml2/pom.xml
@@ -0,0 +1,29 @@
+<!--
+  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.
+-->
+<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/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>cloud-plugin-user-authenticator-saml2</artifactId>
+  <name>Apache CloudStack Plugin - User Authenticator SAML2</name>
+  <parent>
+    <groupId>org.apache.cloudstack</groupId>
+    <artifactId>cloudstack-plugins</artifactId>
+    <version>4.5.0-SNAPSHOT</version>
+    <relativePath>../../pom.xml</relativePath>
+  </parent>
+</project>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/module.properties
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/module.properties b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/module.properties
new file mode 100644
index 0000000..0da9d5b
--- /dev/null
+++ b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/module.properties
@@ -0,0 +1,18 @@
+# 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.
+name=saml2
+parent=api

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
new file mode 100644
index 0000000..f244292
--- /dev/null
+++ b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
@@ -0,0 +1,32 @@
+<!--
+  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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+    xmlns:aop="http://www.springframework.org/schema/aop"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+                      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+                      http://www.springframework.org/schema/context
+                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+    <bean id="SAML2UserAuthenticator" class="org.apache.cloudstack.SAML2UserAuthenticator">
+        <property name="name" value="SAML2"/>
+    </bean>
+
+</beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/src/org/apache/cloudstack/SAML2UserAuthenticator.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/SAML2UserAuthenticator.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/SAML2UserAuthenticator.java
new file mode 100644
index 0000000..4e1e795
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/SAML2UserAuthenticator.java
@@ -0,0 +1,46 @@
+//  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.cloudstack;
+
+import com.cloud.server.auth.DefaultUserAuthenticator;
+import com.cloud.server.auth.UserAuthenticator;
+import com.cloud.utils.Pair;
+import org.apache.log4j.Logger;
+
+import javax.ejb.Local;
+import java.util.Map;
+
+@Local(value = {UserAuthenticator.class})
+public class SAML2UserAuthenticator extends DefaultUserAuthenticator {
+    public static final Logger s_logger = Logger.getLogger(SAML2UserAuthenticator.class);
+
+    @Override
+    public Pair<Boolean, ActionOnFailedAuthentication> authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters) {
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Trying SAML2 auth for user: " + username);
+        }
+
+        // TODO: implement core logic, HTTP GET redirections etc.
+
+        return new Pair<Boolean, ActionOnFailedAuthentication>(true, null);
+    }
+
+    @Override
+    public String encode(final String password) {
+        // TODO: Complete method
+        StringBuilder sb = new StringBuilder(32);
+        return sb.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c4f20026/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
new file mode 100644
index 0000000..8298c6c
--- /dev/null
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.cloudstack;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class SAML2UserAuthenticatorTest {
+
+    @Test
+    public void encode() {
+
+    }
+
+    @Test
+    public void authenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+
+    }
+}


[06/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
client: add saml2 plugin dependency on client artifact

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f7f8f07f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f7f8f07f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f7f8f07f

Branch: refs/heads/master
Commit: f7f8f07f4755e4538a283ce37a02278a31114df3
Parents: c4f2002
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Wed Aug 6 00:19:21 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 client/pom.xml            | 5 +++++
 tools/eclipse/eclipse.epf | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f7f8f07f/client/pom.xml
----------------------------------------------------------------------
diff --git a/client/pom.xml b/client/pom.xml
index fcd8317..d87fc45 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -82,6 +82,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.cloudstack</groupId>
+      <artifactId>cloud-plugin-user-authenticator-saml2</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.cloudstack</groupId>
       <artifactId>cloud-plugin-user-authenticator-sha256salted</artifactId>
       <version>${project.version}</version>
     </dependency>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f7f8f07f/tools/eclipse/eclipse.epf
----------------------------------------------------------------------
diff --git a/tools/eclipse/eclipse.epf b/tools/eclipse/eclipse.epf
index 0fd88ac..d7795aa 100644
--- a/tools/eclipse/eclipse.epf
+++ b/tools/eclipse/eclipse.epf
@@ -428,7 +428,7 @@
 /instance/org.eclipse.jdt.core/org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
 /instance/org.eclipse.jdt.core/org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
 /instance/org.eclipse.jdt.core/org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
-/instance/org.eclipse.wst.sse.core/task-tag-projects-already-scanned=cloud-agent,cloud-api,cloud-apidoc,cloud-awsapi,cloud-cli,cloud-client-ui,cloud-console-proxy,cloud-core,cloud-devcloud,cloud-devcloud-kvm,cloud-developer,cloud-engine,cloud-engine-api,cloud-engine-components-api,cloud-engine-compute,cloud-engine-network,cloud-engine-orchestration,cloud-engine-schema,cloud-engine-service,cloud-engine-storage,cloud-engine-storage-backup,cloud-engine-storage-image,cloud-engine-storage-imagemotion,cloud-engine-storage-integration-test,cloud-engine-storage-snapshot,cloud-engine-storage-volume,cloud-framework-events,cloud-framework-ipc,cloud-framework-rest,cloud-marvin,cloud-mom-rabbitmq,cloud-patches,cloud-plugin-acl-static-role-based,cloud-plugin-api-discovery,cloud-plugin-api-limit-account-based,cloud-plugin-console-proxy,cloud-plugin-example-dns-notifier,cloud-plugin-host-allocator-random,cloud-plugin-hypervisor-baremetal,cloud-plugin-hypervisor-kvm,cloud-plugin-hypervisor-ovm,cloud
 -plugin-hypervisor-simulator,cloud-plugin-hypervisor-ucs,cloud-plugin-hypervisor-vmware,cloud-plugin-hypervisor-xen,cloud-plugin-netapp,cloud-plugin-network-elb,cloud-plugin-network-f5,cloud-plugin-network-netscaler,cloud-plugin-network-nvp,cloud-plugin-network-ovs,cloud-plugin-network-srx,cloud-plugin-network-vns,cloud-plugin-planner-user-concentrated-pod,cloud-plugin-planner-user-dispersing,cloud-plugin-snmp-alerts,cloud-plugin-storage-allocator-random,cloud-plugin-storage-image-s3,cloud-plugin-storage-volume-default,cloud-plugin-storage-volume-solidfire,cloud-plugin-syslog-alerts,cloud-plugin-user-authenticator-ldap,cloud-plugin-user-authenticator-md5,cloud-plugin-user-authenticator-plaintext,cloud-plugin-user-authenticator-sha256salted,cloud-server,cloud-testclient,cloud-tools,cloud-usage,cloud-utils,cloud-vmware-base,cloudstack,cloudstack-framework,cloudstack-plugins,xapi,cloud-framework-jobs,cloud-plugin-host-anti-affinity,cloud-plugin-network-cisco-vnmc,cloud-plugin-network-m
 idonet,cloud-secondary-storage,cloudstack-services,cloud-plugin-network-internallb,cloud-plugin-planner-implicit-dedication,cloudstack-service-console-proxy
+/instance/org.eclipse.wst.sse.core/task-tag-projects-already-scanned=cloud-agent,cloud-api,cloud-apidoc,cloud-awsapi,cloud-cli,cloud-client-ui,cloud-console-proxy,cloud-core,cloud-devcloud,cloud-devcloud-kvm,cloud-developer,cloud-engine,cloud-engine-api,cloud-engine-components-api,cloud-engine-compute,cloud-engine-network,cloud-engine-orchestration,cloud-engine-schema,cloud-engine-service,cloud-engine-storage,cloud-engine-storage-backup,cloud-engine-storage-image,cloud-engine-storage-imagemotion,cloud-engine-storage-integration-test,cloud-engine-storage-snapshot,cloud-engine-storage-volume,cloud-framework-events,cloud-framework-ipc,cloud-framework-rest,cloud-marvin,cloud-mom-rabbitmq,cloud-patches,cloud-plugin-acl-static-role-based,cloud-plugin-api-discovery,cloud-plugin-api-limit-account-based,cloud-plugin-console-proxy,cloud-plugin-example-dns-notifier,cloud-plugin-host-allocator-random,cloud-plugin-hypervisor-baremetal,cloud-plugin-hypervisor-kvm,cloud-plugin-hypervisor-ovm,cloud
 -plugin-hypervisor-simulator,cloud-plugin-hypervisor-ucs,cloud-plugin-hypervisor-vmware,cloud-plugin-hypervisor-xen,cloud-plugin-netapp,cloud-plugin-network-elb,cloud-plugin-network-f5,cloud-plugin-network-netscaler,cloud-plugin-network-nvp,cloud-plugin-network-ovs,cloud-plugin-network-srx,cloud-plugin-network-vns,cloud-plugin-planner-user-concentrated-pod,cloud-plugin-planner-user-dispersing,cloud-plugin-snmp-alerts,cloud-plugin-storage-allocator-random,cloud-plugin-storage-image-s3,cloud-plugin-storage-volume-default,cloud-plugin-storage-volume-solidfire,cloud-plugin-syslog-alerts,cloud-plugin-user-authenticator-ldap,cloud-plugin-user-authenticator-md5,cloud-plugin-user-authenticator-plaintext,cloud-plugin-user-authenticator-saml2,cloud-plugin-user-authenticator-sha256salted,cloud-server,cloud-testclient,cloud-tools,cloud-usage,cloud-utils,cloud-vmware-base,cloudstack,cloudstack-framework,cloudstack-plugins,xapi,cloud-framework-jobs,cloud-plugin-host-anti-affinity,cloud-plugin-net
 work-cisco-vnmc,cloud-plugin-network-midonet,cloud-secondary-storage,cloudstack-services,cloud-plugin-network-internallb,cloud-plugin-planner-implicit-dedication,cloudstack-service-console-proxy
 /instance/org.eclipse.jdt.debug.ui/org.eclipse.debug.ui.ExpressionView.org.eclipse.jdt.debug.ui.show_null_entries=true
 /instance/org.eclipse.jdt.ui/sp_cleanup.correct_indentation=false
 /instance/org.eclipse.jdt.core/org.eclipse.jdt.core.formatter.comment.format_source_code=true


[02/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
APIAuthenticator: Add interface definition for the auth mechanisms

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/31722c26
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/31722c26
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/31722c26

Branch: refs/heads/master
Commit: 31722c26745a8a741c53f0aaaba25b0f1d576d12
Parents: a6a63dd
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:26:32 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 .../com/cloud/api/auth/APIAuthenticator.java    | 40 ++++++++++++++++++++
 1 file changed, 40 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/31722c26/server/src/com/cloud/api/auth/APIAuthenticator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/APIAuthenticator.java b/server/src/com/cloud/api/auth/APIAuthenticator.java
new file mode 100644
index 0000000..a0f669e
--- /dev/null
+++ b/server/src/com/cloud/api/auth/APIAuthenticator.java
@@ -0,0 +1,40 @@
+// 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 com.cloud.api.auth;
+
+import org.apache.cloudstack.api.ServerApiException;
+
+import javax.servlet.http.HttpSession;
+import java.util.Map;
+
+/*
+* APIAuthenticator is an interface that defines method that
+* a class should implement that help with Authentication and accepts
+* a command string and an array of parameters. This should be used only
+* in the Servlet that is doing authentication.
+*
+* @param command The API command name such as login, logout etc
+* @param params An array of HTTP parameters
+* @param session HttpSession object
+* */
+public interface APIAuthenticator {
+    public String authenticate(String command, Map<String, Object[]> params,
+                               HttpSession session, String remoteAddress, String responseType,
+                               StringBuilder auditTrailSb) throws ServerApiException;
+    public APIAuthenticationType getAPIType();
+
+}


[20/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiXmlDocWriter: get rid of hardcoded login/logout docs

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/7434f1bd
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/7434f1bd
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/7434f1bd

Branch: refs/heads/master
Commit: 7434f1bd33624f75af212f708123f178f76eefe9
Parents: ee57f47
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:37:36 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 .../src/com/cloud/api/doc/ApiXmlDocWriter.java  | 22 ++++++--------------
 1 file changed, 6 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7434f1bd/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
index 11ea57a..ee8a4bb 100644
--- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
+++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
@@ -241,24 +241,14 @@ public class ApiXmlDocWriter {
             while (it.hasNext()) {
                 String key = (String)it.next();
 
-                if (key.equals("login")) {
-                    writeLoginCommand(rootAdminSorted);
-                    writeLoginCommand(outDomainAdminSorted);
-                    writeLoginCommand(regularUserSorted);
-                } else if (key.equals("logout")) {
-                    writeLogoutCommand(rootAdminSorted);
-                    writeLogoutCommand(outDomainAdminSorted);
-                    writeLogoutCommand(regularUserSorted);
-                } else {
-                    writeCommand(rootAdminSorted, key);
+                writeCommand(rootAdminSorted, key);
 
-                    if (s_domainAdminApiCommands.containsKey(key)) {
-                        writeCommand(outDomainAdminSorted, key);
-                    }
+                if (s_domainAdminApiCommands.containsKey(key)) {
+                    writeCommand(outDomainAdminSorted, key);
+                }
 
-                    if (s_regularUserApiCommands.containsKey(key)) {
-                        writeCommand(regularUserSorted, key);
-                    }
+                if (s_regularUserApiCommands.containsKey(key)) {
+                    writeCommand(regularUserSorted, key);
                 }
             }
 


[19/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiXmlDocWriter: remove hardcoded login and logout apis

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/2e5bbc9a
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/2e5bbc9a
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/2e5bbc9a

Branch: refs/heads/master
Commit: 2e5bbc9a0d4d04211996d30d41ae88a41561e975
Parents: b587291
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:33:40 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 .../src/com/cloud/api/doc/ApiXmlDocWriter.java  | 186 ++++---------------
 1 file changed, 39 insertions(+), 147 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e5bbc9a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
index 6824185..11ea57a 100644
--- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
+++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java
@@ -16,6 +16,29 @@
 // under the License.
 package com.cloud.api.doc;
 
+import com.cloud.alert.AlertManager;
+import com.cloud.serializer.Param;
+import com.cloud.utils.IteratorUtil;
+import com.cloud.utils.ReflectUtil;
+import com.google.gson.annotations.SerializedName;
+import com.thoughtworks.xstream.XStream;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.BaseAsyncCreateCmd;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.BaseResponse;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.response.AsyncJobResponse;
+import org.apache.cloudstack.api.response.HostResponse;
+import org.apache.cloudstack.api.response.IPAddressResponse;
+import org.apache.cloudstack.api.response.SecurityGroupResponse;
+import org.apache.cloudstack.api.response.SnapshotResponse;
+import org.apache.cloudstack.api.response.StoragePoolResponse;
+import org.apache.cloudstack.api.response.TemplateResponse;
+import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.cloudstack.api.response.VolumeResponse;
+import org.apache.log4j.Logger;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -41,32 +64,6 @@ import java.util.TreeMap;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
-import org.apache.log4j.Logger;
-
-import com.google.gson.annotations.SerializedName;
-import com.thoughtworks.xstream.XStream;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.BaseAsyncCmd;
-import org.apache.cloudstack.api.BaseAsyncCreateCmd;
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.BaseResponse;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.response.AsyncJobResponse;
-import org.apache.cloudstack.api.response.HostResponse;
-import org.apache.cloudstack.api.response.IPAddressResponse;
-import org.apache.cloudstack.api.response.SecurityGroupResponse;
-import org.apache.cloudstack.api.response.SnapshotResponse;
-import org.apache.cloudstack.api.response.StoragePoolResponse;
-import org.apache.cloudstack.api.response.TemplateResponse;
-import org.apache.cloudstack.api.response.UserVmResponse;
-import org.apache.cloudstack.api.response.VolumeResponse;
-
-import com.cloud.alert.AlertManager;
-import com.cloud.serializer.Param;
-import com.cloud.utils.IteratorUtil;
-import com.cloud.utils.ReflectUtil;
-
 public class ApiXmlDocWriter {
     public static final Logger s_logger = Logger.getLogger(ApiXmlDocWriter.class.getName());
 
@@ -183,15 +180,6 @@ public class ApiXmlDocWriter {
             }
         }
 
-        // Login and logout commands are hardcoded
-        s_allApiCommands.put("login", "login");
-        s_domainAdminApiCommands.put("login", "login");
-        s_regularUserApiCommands.put("login", "login");
-
-        s_allApiCommands.put("logout", "logout");
-        s_domainAdminApiCommands.put("logout", "logout");
-        s_regularUserApiCommands.put("logout", "logout");
-
         s_allApiCommandsSorted.putAll(s_allApiCommands);
         s_domainAdminApiCommandsSorted.putAll(s_domainAdminApiCommands);
         s_regularUserApiCommandsSorted.putAll(s_regularUserApiCommands);
@@ -223,66 +211,28 @@ public class ApiXmlDocWriter {
                 String key = (String)it.next();
 
                 // Write admin commands
-                if (key.equals("login")) {
-                    writeLoginCommand(out);
-                    writeLoginCommand(rootAdmin);
-                    writeLoginCommand(domainAdmin);
-                    writeLoginCommand(regularUser);
-
-                    ObjectOutputStream singleRootAdminCommandOs = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "login" + ".xml"), "command");
-                    writeLoginCommand(singleRootAdminCommandOs);
-                    singleRootAdminCommandOs.close();
+                writeCommand(out, key);
+                writeCommand(rootAdmin, key);
 
-                    ObjectOutputStream singleDomainAdminCommandOs = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + "login" + ".xml"), "command");
-                    writeLoginCommand(singleDomainAdminCommandOs);
-                    singleDomainAdminCommandOs.close();
-
-                    ObjectOutputStream singleRegularUserCommandOs = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/" + "login" + ".xml"), "command");
-                    writeLoginCommand(singleRegularUserCommandOs);
-                    singleRegularUserCommandOs.close();
-
-                } else if (key.equals("logout")) {
-                    writeLogoutCommand(out);
-                    writeLogoutCommand(rootAdmin);
-                    writeLogoutCommand(domainAdmin);
-                    writeLogoutCommand(regularUser);
-
-                    ObjectOutputStream singleRootAdminCommandOs = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "logout" + ".xml"), "command");
-                    writeLogoutCommand(singleRootAdminCommandOs);
+                // Write single commands to separate xml files
+                if (!key.equals("login")) {
+                    ObjectOutputStream singleRootAdminCommandOs = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + key + ".xml"), "command");
+                    writeCommand(singleRootAdminCommandOs, key);
                     singleRootAdminCommandOs.close();
+                }
 
-                    ObjectOutputStream singleDomainAdminCommandOs = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + "logout" + ".xml"), "command");
-                    writeLogoutCommand(singleDomainAdminCommandOs);
+                if (s_domainAdminApiCommands.containsKey(key)) {
+                    writeCommand(domainAdmin, key);
+                    ObjectOutputStream singleDomainAdminCommandOs = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + key + ".xml"), "command");
+                    writeCommand(singleDomainAdminCommandOs, key);
                     singleDomainAdminCommandOs.close();
+                }
 
-                    ObjectOutputStream singleRegularUserCommandOs = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/" + "logout" + ".xml"), "command");
-                    writeLogoutCommand(singleRegularUserCommandOs);
+                if (s_regularUserApiCommands.containsKey(key)) {
+                    writeCommand(regularUser, key);
+                    ObjectOutputStream singleRegularUserCommandOs = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/" + key + ".xml"), "command");
+                    writeCommand(singleRegularUserCommandOs, key);
                     singleRegularUserCommandOs.close();
-
-                } else {
-                    writeCommand(out, key);
-                    writeCommand(rootAdmin, key);
-
-                    // Write single commands to separate xml files
-                    if (!key.equals("login")) {
-                        ObjectOutputStream singleRootAdminCommandOs = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + key + ".xml"), "command");
-                        writeCommand(singleRootAdminCommandOs, key);
-                        singleRootAdminCommandOs.close();
-                    }
-
-                    if (s_domainAdminApiCommands.containsKey(key)) {
-                        writeCommand(domainAdmin, key);
-                        ObjectOutputStream singleDomainAdminCommandOs = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + key + ".xml"), "command");
-                        writeCommand(singleDomainAdminCommandOs, key);
-                        singleDomainAdminCommandOs.close();
-                    }
-
-                    if (s_regularUserApiCommands.containsKey(key)) {
-                        writeCommand(regularUser, key);
-                        ObjectOutputStream singleRegularUserCommandOs = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/" + key + ".xml"), "command");
-                        writeCommand(singleRegularUserCommandOs, key);
-                        singleRegularUserCommandOs.close();
-                    }
                 }
             }
 
@@ -393,64 +343,6 @@ public class ApiXmlDocWriter {
         }
     }
 
-    private static void writeLoginCommand(ObjectOutputStream out) throws ClassNotFoundException, IOException {
-        ArrayList<Argument> request = new ArrayList<Argument>();
-        ArrayList<Argument> response = new ArrayList<Argument>();
-
-        // Create a new command, set name and description
-        Command apiCommand = new Command();
-        apiCommand.setName("login");
-        apiCommand.setDescription("Logs a user into the CloudStack. A successful login attempt will generate a JSESSIONID cookie value that can be passed in subsequent Query command calls until the \"logout\" command has been issued or the session has expired.");
-
-        // Generate request
-        request.add(new Argument("username", "Username", true));
-        request.add(new Argument(
-            "password",
-            "Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.",
-            true));
-        request.add(new Argument("domain",
-            "path of the domain that the user belongs to. Example: domain=/com/cloud/internal.  If no domain is passed in, the ROOT domain is assumed.", false));
-        request.add(new Argument("domainId",
-            "id of the domain that the user belongs to. If both domain and domainId are passed in, \"domainId\" parameter takes precendence", false));
-        apiCommand.setRequest(request);
-
-        // Generate response
-        response.add(new Argument("username", "Username"));
-        response.add(new Argument("userid", "User id"));
-        response.add(new Argument("password", "Password"));
-        response.add(new Argument("domainid", "domain ID that the user belongs to"));
-        response.add(new Argument("timeout", "the time period before the session has expired"));
-        response.add(new Argument("account", "the account name the user belongs to"));
-        response.add(new Argument("firstname", "first name of the user"));
-        response.add(new Argument("lastname", "last name of the user"));
-        response.add(new Argument("type", "the account type (admin, domain-admin, read-only-admin, user)"));
-        response.add(new Argument("timezone", "user time zone"));
-        response.add(new Argument("timezoneoffset", "user time zone offset from UTC 00:00"));
-        response.add(new Argument("sessionkey", "Session key that can be passed in subsequent Query command calls"));
-        apiCommand.setResponse(response);
-
-        out.writeObject(apiCommand);
-    }
-
-    private static void writeLogoutCommand(ObjectOutputStream out) throws ClassNotFoundException, IOException {
-        ArrayList<Argument> request = new ArrayList<Argument>();
-        ArrayList<Argument> response = new ArrayList<Argument>();
-
-        // Create a new command, set name and description
-        Command apiCommand = new Command();
-        apiCommand.setName("logout");
-        apiCommand.setDescription("Logs out the user");
-
-        // Generate request - no request parameters
-        apiCommand.setRequest(request);
-
-        // Generate response
-        response.add(new Argument("description", "success if the logout action succeeded"));
-        apiCommand.setResponse(response);
-
-        out.writeObject(apiCommand);
-    }
-
     private static ArrayList<Argument> setRequestFields(Set<Field> fields) {
         ArrayList<Argument> arguments = new ArrayList<Argument>();
         Set<Argument> requiredArguments = new HashSet<Argument>();


[07/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
saml2: add opensaml as dependency

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/a6a63dd2
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/a6a63dd2
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/a6a63dd2

Branch: refs/heads/master
Commit: a6a63dd2d3505e015550e658b253060b4ea5e0b7
Parents: 6016613
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:25:41 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 plugins/user-authenticators/saml2/pom.xml | 5 +++++
 1 file changed, 5 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a6a63dd2/plugins/user-authenticators/saml2/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/pom.xml b/plugins/user-authenticators/saml2/pom.xml
index 00b3ff0..a220dcf 100644
--- a/plugins/user-authenticators/saml2/pom.xml
+++ b/plugins/user-authenticators/saml2/pom.xml
@@ -32,5 +32,10 @@
       <artifactId>spring-security-saml2-core</artifactId>
       <version>1.0.0.RELEASE</version>
     </dependency>
+    <dependency>
+      <groupId>org.opensaml</groupId>
+      <artifactId>opensaml</artifactId>
+      <version>2.6.1</version>
+    </dependency>
   </dependencies>
 </project>


[17/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
utils: refactor HTTP transport stuff to HttpUtils

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/315feb06
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/315feb06
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/315feb06

Branch: refs/heads/master
Commit: 315feb06839bbe74f4f8068a1ad634be352b49fc
Parents: f11dcf8
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:04:01 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 utils/src/com/cloud/utils/HttpUtils.java | 56 +++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/315feb06/utils/src/com/cloud/utils/HttpUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/HttpUtils.java b/utils/src/com/cloud/utils/HttpUtils.java
new file mode 100644
index 0000000..f608b86
--- /dev/null
+++ b/utils/src/com/cloud/utils/HttpUtils.java
@@ -0,0 +1,56 @@
+// 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 com.cloud.utils;
+
+import org.apache.log4j.Logger;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class HttpUtils {
+
+    public static final Logger s_logger = Logger.getLogger(HttpUtils.class);
+
+    public static final String UTF_8 = "UTF-8";
+    public static final String RESPONSE_TYPE_JSON = "json";
+    public static final String RESPONSE_TYPE_XML = "xml";
+    public static final String JSON_CONTENT_TYPE = "text/javascript; charset=UTF-8";
+    public static final String XML_CONTENT_TYPE = "text/xml; charset=UTF-8";
+
+    public static void writeHttpResponse(final HttpServletResponse resp, final String response,
+                                         final Integer responseCode, final String responseType) {
+        try {
+            if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+                resp.setContentType(JSON_CONTENT_TYPE);
+            } else if (RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)){
+                resp.setContentType(XML_CONTENT_TYPE);
+            }
+            if (responseCode != null) {
+                resp.setStatus(responseCode);
+            }
+            resp.getWriter().print(response);
+        } catch (final IOException ioex) {
+            if (s_logger.isTraceEnabled()) {
+                s_logger.trace("Exception writing http response: " + ioex);
+            }
+        } catch (final Exception ex) {
+            if (!(ex instanceof IllegalStateException)) {
+                s_logger.error("Unknown exception writing http response", ex);
+            }
+        }
+    }
+}


[16/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiServlet: use the new and refactored authentication mechanism

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/ee57f47e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/ee57f47e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/ee57f47e

Branch: refs/heads/master
Commit: ee57f47e2932ff018b354c2ccc47f9943e6af3eb
Parents: 2e5bbc9
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:34:35 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/ApiServlet.java | 251 +++++++-------------------
 1 file changed, 62 insertions(+), 189 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ee57f47e/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
old mode 100755
new mode 100644
index e78bf38..5a8cf94
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -16,12 +16,22 @@
 // under the License.
 package com.cloud.api;
 
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
+import com.cloud.api.auth.APIAuthenticationManager;
+import com.cloud.api.auth.APIAuthenticationType;
+import com.cloud.api.auth.APIAuthenticator;
+import com.cloud.user.Account;
+import com.cloud.user.AccountService;
+import com.cloud.user.User;
+import com.cloud.utils.StringUtils;
+import com.cloud.utils.db.EntityManager;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.managed.context.ManagedContext;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.support.SpringBeanAutowiringSupport;
 
 import javax.inject.Inject;
 import javax.servlet.ServletConfig;
@@ -30,24 +40,11 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
-
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-import org.springframework.web.context.support.SpringBeanAutowiringSupport;
-
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.ApiErrorCode;
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.ServerApiException;
-import org.apache.cloudstack.context.CallContext;
-import org.apache.cloudstack.managed.context.ManagedContext;
-
-import com.cloud.exception.CloudAuthenticationException;
-import com.cloud.user.Account;
-import com.cloud.user.AccountService;
-import com.cloud.user.User;
-import com.cloud.utils.StringUtils;
-import com.cloud.utils.db.EntityManager;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.Map;
 
 @Component("apiServlet")
 @SuppressWarnings("serial")
@@ -63,6 +60,8 @@ public class ApiServlet extends HttpServlet {
     EntityManager _entityMgr;
     @Inject
     ManagedContext _managedContext;
+    @Inject
+    APIAuthenticationManager _authManager;
 
     public ApiServlet() {
     }
@@ -121,8 +120,9 @@ public class ApiServlet extends HttpServlet {
     }
 
     void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) {
+        final String remoteAddress = req.getRemoteAddr();
         final StringBuilder auditTrailSb = new StringBuilder(128);
-        auditTrailSb.append(" ").append(req.getRemoteAddr());
+        auditTrailSb.append(" ").append(remoteAddress);
         auditTrailSb.append(" -- ").append(req.getMethod()).append(' ');
         // get the response format since we'll need it in a couple of places
         String responseType = BaseCmd.RESPONSE_TYPE_XML;
@@ -151,107 +151,56 @@ public class ApiServlet extends HttpServlet {
 
             final Object[] commandObj = params.get(ApiConstants.COMMAND);
             if (commandObj != null) {
-                final String command = (String)commandObj[0];
-                if ("logout".equalsIgnoreCase(command)) {
-                    // if this is just a logout, invalidate the session and return
-                    if (session != null) {
-                        final Long userId = (Long)session.getAttribute("userid");
-                        final Account account = (Account)session.getAttribute("accountobj");
-                        Long accountId = null;
-                        if (account != null) {
-                            accountId = account.getId();
-                        }
-                        auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
-                        if (userId != null) {
-                            _apiServer.logoutUser(userId);
-                        }
-                        try {
-                            session.invalidate();
-                        } catch (final IllegalStateException ise) {
-                        }
-                    }
-                    auditTrailSb.append("command=logout");
-                    auditTrailSb.append(" ").append(HttpServletResponse.SC_OK);
-                    writeResponse(resp, getLogoutSuccessResponse(responseType), HttpServletResponse.SC_OK, responseType);
-                    return;
-                } else if ("login".equalsIgnoreCase(command)) {
-                    auditTrailSb.append("command=login");
-                    // if this is a login, authenticate the user and return
-                    if (session != null) {
-                        try {
-                            session.invalidate();
-                        } catch (final IllegalStateException ise) {
-                        }
-                    }
-                    session = req.getSession(true);
-                    final String[] username = (String[])params.get(ApiConstants.USERNAME);
-                    final String[] password = (String[])params.get(ApiConstants.PASSWORD);
-                    String[] domainIdArr = (String[])params.get(ApiConstants.DOMAIN_ID);
+                final String command = (String) commandObj[0];
 
-                    if (domainIdArr == null) {
-                        domainIdArr = (String[])params.get(ApiConstants.DOMAIN__ID);
-                    }
-                    final String[] domainName = (String[])params.get(ApiConstants.DOMAIN);
-                    Long domainId = null;
-                    if ((domainIdArr != null) && (domainIdArr.length > 0)) {
-                        try {
-                            //check if UUID is passed in for domain
-                            domainId = _apiServer.fetchDomainId(domainIdArr[0]);
-                            if (domainId == null) {
-                                domainId = Long.parseLong(domainIdArr[0]);
+                APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command);
+                if (apiAuthenticator != null) {
+                    auditTrailSb.append("command=");
+                    auditTrailSb.append(command);
+
+                    int httpResponseCode = HttpServletResponse.SC_OK;
+                    String responseString = null;
+
+                    if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) {
+                        if (session != null) {
+                            try {
+                                session.invalidate();
+                            } catch (final IllegalStateException ise) {
                             }
-                            auditTrailSb.append(" domainid=" + domainId);// building the params for POST call
-                        } catch (final NumberFormatException e) {
-                            s_logger.warn("Invalid domain id entered by user");
-                            auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
-                            final String serializedResponse =
-                                _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
-                                    responseType);
-                            writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                         }
+                        session = req.getSession(true);
+                    }
+
+                    try {
+                        responseString = apiAuthenticator.authenticate(command, params, session, remoteAddress, responseType, auditTrailSb);
+                    } catch (ServerApiException e) {
+                        httpResponseCode = e.getErrorCode().getHttpCode();
+                        responseString = e.getMessage();
+                        s_logger.debug("Authentication failure: " + e.getMessage());
                     }
-                    String domain = null;
-                    if (domainName != null) {
-                        domain = domainName[0];
-                        auditTrailSb.append(" domain=" + domain);
-                        if (domain != null) {
-                            // ensure domain starts with '/' and ends with '/'
-                            if (!domain.endsWith("/")) {
-                                domain += '/';
+                    if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) {
+                        if (session != null) {
+                            final Long userId = (Long) session.getAttribute("userid");
+                            final Account account = (Account) session.getAttribute("accountobj");
+                            Long accountId = null;
+                            if (account != null) {
+                                accountId = account.getId();
                             }
-                            if (!domain.startsWith("/")) {
-                                domain = "/" + domain;
+                            auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
+                            if (userId != null) {
+                                _apiServer.logoutUser(userId);
                             }
-                        }
-                    }
-
-                    if (username != null) {
-                        final String pwd = ((password == null) ? null : password[0]);
-                        try {
-                            _apiServer.loginUser(session, username[0], pwd, domainId, domain, req.getRemoteAddr(), params);
-                            auditTrailSb.insert(0, "(userId=" + session.getAttribute("userid") + " accountId=" + ((Account)session.getAttribute("accountobj")).getId() +
-                                " sessionId=" + session.getId() + ")");
-                            final String loginResponse = getLoginSuccessResponse(session, responseType);
-                            writeResponse(resp, loginResponse, HttpServletResponse.SC_OK, responseType);
-                            return;
-                        } catch (final CloudAuthenticationException ex) {
-                            // TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
                             try {
                                 session.invalidate();
-                            } catch (final IllegalStateException ise) {
+                            } catch (final IllegalStateException ignored) {
                             }
-
-                            auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage()
-                                : "failed to authenticate user, check if username/password are correct");
-                            final String serializedResponse =
-                                _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage()
-                                    : "failed to authenticate user, check if username/password are correct", params, responseType);
-                            writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), responseType);
-                            return;
                         }
                     }
+                    writeResponse(resp, responseString, httpResponseCode, responseType);
+                    return;
                 }
             }
+
             auditTrailSb.append(req.getQueryString());
             final boolean isNew = ((session == null) ? true : session.isNew());
 
@@ -371,80 +320,4 @@ public class ApiServlet extends HttpServlet {
         }
     }
 
-    @SuppressWarnings("rawtypes")
-    String getLoginSuccessResponse(final HttpSession session, final String responseType) {
-        final StringBuilder sb = new StringBuilder();
-        final int inactiveInterval = session.getMaxInactiveInterval();
-
-        final String user_UUID = (String)session.getAttribute("user_UUID");
-        session.removeAttribute("user_UUID");
-
-        final String domain_UUID = (String)session.getAttribute("domain_UUID");
-        session.removeAttribute("domain_UUID");
-
-        if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
-            sb.append("{ \"loginresponse\" : { ");
-            final Enumeration attrNames = session.getAttributeNames();
-            if (attrNames != null) {
-                sb.append("\"timeout\" : \"").append(inactiveInterval).append("\"");
-                while (attrNames.hasMoreElements()) {
-                    final String attrName = (String)attrNames.nextElement();
-                    if ("userid".equalsIgnoreCase(attrName)) {
-                        sb.append(", \"" + attrName + "\" : \"" + user_UUID + "\"");
-                    } else if ("domainid".equalsIgnoreCase(attrName)) {
-                        sb.append(", \"" + attrName + "\" : \"" + domain_UUID + "\"");
-                    } else {
-                        final Object attrObj = session.getAttribute(attrName);
-                        if ((attrObj instanceof String) || (attrObj instanceof Long)) {
-                            sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\"");
-                        }
-                    }
-                }
-            }
-            sb.append(" } }");
-        } else {
-            sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
-            sb.append("<loginresponse cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">");
-            sb.append("<timeout>").append(inactiveInterval).append("</timeout>");
-            final Enumeration attrNames = session.getAttributeNames();
-            if (attrNames != null) {
-                while (attrNames.hasMoreElements()) {
-                    final String attrName = (String)attrNames.nextElement();
-                    if (ApiConstants.USER_ID.equalsIgnoreCase(attrName)) {
-                        sb.append("<").append(attrName).append(">")
-                                .append(user_UUID).append("</")
-                                .append(attrName).append(">");
-                    } else if ("domainid".equalsIgnoreCase(attrName)) {
-                        sb.append("<").append(attrName).append(">")
-                                .append(domain_UUID).append("</")
-                                .append(attrName).append(">");
-                    } else {
-                        final Object attrObj = session.getAttribute(attrName);
-                        if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) {
-                            sb.append("<").append(attrName).append(">")
-                                    .append(attrObj.toString()).append("</")
-                                    .append(attrName).append(">");
-                        }
-                    }
-                }
-            }
-
-            sb.append("</loginresponse>");
-        }
-        return sb.toString();
-    }
-
-    private String getLogoutSuccessResponse(final String responseType) {
-        final StringBuilder sb = new StringBuilder();
-        if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
-            sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }");
-        } else {
-            sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
-            sb.append("<logoutresponse cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">");
-            sb.append("<description>success</description>");
-            sb.append("</logoutresponse>");
-        }
-        return sb.toString();
-    }
-
 }


[03/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiErrorCode: Add API error code 401, 405

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/e6d2b239
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/e6d2b239
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/e6d2b239

Branch: refs/heads/master
Commit: e6d2b2391bf4d4fffbbb2be1c4adfb9737b78915
Parents: accd574
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:24:42 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 api/src/org/apache/cloudstack/api/ApiErrorCode.java | 2 ++
 1 file changed, 2 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e6d2b239/api/src/org/apache/cloudstack/api/ApiErrorCode.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiErrorCode.java b/api/src/org/apache/cloudstack/api/ApiErrorCode.java
index fa47f30..2784058 100644
--- a/api/src/org/apache/cloudstack/api/ApiErrorCode.java
+++ b/api/src/org/apache/cloudstack/api/ApiErrorCode.java
@@ -22,6 +22,8 @@ package org.apache.cloudstack.api;
  */
 public enum ApiErrorCode {
 
+    UNAUTHORIZED(401),
+    METHOD_NOT_ALLOWED(405),
     MALFORMED_PARAMETER_ERROR(430),
     PARAM_ERROR(431),
     UNSUPPORTED_ACTION_ERROR(432),


[04/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiConstants: add Api constant registered

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/accd5748
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/accd5748
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/accd5748

Branch: refs/heads/master
Commit: accd57486ecb1e3dab7698688962fc1b58fc96b4
Parents: c35f704
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:24:22 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 api/src/org/apache/cloudstack/api/ApiConstants.java | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/accd5748/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index 3a5a42b..f89aa14 100755
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -210,6 +210,7 @@ public class ApiConstants {
     public static final String RESOURCE_TYPE = "resourcetype";
     public static final String RESPONSE = "response";
     public static final String REVERTABLE = "revertable";
+    public static final String REGISTERED = "registered";
     public static final String QUERY_FILTER = "queryfilter";
     public static final String SCHEDULE = "schedule";
     public static final String SCOPE = "scope";


[21/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
APIAuthenticator: refactor signature of APIAuthenticator interface's authenticate

Pass HttpServletResponse as it can be useful for authenticators which need to
have their own writer interface/method

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/224dc9f8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/224dc9f8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/224dc9f8

Branch: refs/heads/master
Commit: 224dc9f8e548c222baff92db8b352af46c495ac2
Parents: 6ec1a1b
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 09:15:24 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/ApiServlet.java                          | 2 +-
 server/src/com/cloud/api/auth/APIAuthenticator.java               | 3 ++-
 .../src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java   | 2 +-
 .../src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java  | 3 ++-
 4 files changed, 6 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/224dc9f8/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
index d94894a..d09d426 100644
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -178,7 +178,7 @@ public class ApiServlet extends HttpServlet {
                     }
 
                     try {
-                        responseString = apiAuthenticator.authenticate(command, params, session, remoteAddress, responseType, auditTrailSb);
+                        responseString = apiAuthenticator.authenticate(command, params, session, remoteAddress, responseType, auditTrailSb, resp);
                     } catch (ServerApiException e) {
                         httpResponseCode = e.getErrorCode().getHttpCode();
                         responseString = e.getMessage();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/224dc9f8/server/src/com/cloud/api/auth/APIAuthenticator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/APIAuthenticator.java b/server/src/com/cloud/api/auth/APIAuthenticator.java
index a0f669e..90cd7ec 100644
--- a/server/src/com/cloud/api/auth/APIAuthenticator.java
+++ b/server/src/com/cloud/api/auth/APIAuthenticator.java
@@ -18,6 +18,7 @@ package com.cloud.api.auth;
 
 import org.apache.cloudstack.api.ServerApiException;
 
+import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.util.Map;
 
@@ -34,7 +35,7 @@ import java.util.Map;
 public interface APIAuthenticator {
     public String authenticate(String command, Map<String, Object[]> params,
                                HttpSession session, String remoteAddress, String responseType,
-                               StringBuilder auditTrailSb) throws ServerApiException;
+                               StringBuilder auditTrailSb, final HttpServletResponse resp) throws ServerApiException;
     public APIAuthenticationType getAPIType();
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/224dc9f8/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
index 5fa8e9e..fe04ed9 100644
--- a/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
+++ b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
@@ -152,7 +152,7 @@ public class DefaultLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthe
     }
 
     @Override
-    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb) throws ServerApiException {
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletResponse resp) throws ServerApiException {
 
         // FIXME: ported from ApiServlet, refactor and cleanup
         final String[] username = (String[])params.get(ApiConstants.USERNAME);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/224dc9f8/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java b/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
index ab4e162..a5802bf 100644
--- a/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
+++ b/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
@@ -25,6 +25,7 @@ import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.response.LogoutCmdResponse;
 import org.apache.log4j.Logger;
 
+import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.util.Map;
 
@@ -55,7 +56,7 @@ public class DefaultLogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuth
     }
 
     @Override
-    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb) throws ServerApiException {
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletResponse resp) throws ServerApiException {
         auditTrailSb.append("=== Logging out ===");
         LogoutCmdResponse response = new LogoutCmdResponse();
         response.setDescription("success");


[26/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiServlet: use HttpUtils instead of class specific implementation

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3cc6efce
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3cc6efce
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3cc6efce

Branch: refs/heads/master
Commit: 3cc6efce04153a013d70971cbcfdbb20ab8b7fbb
Parents: 983252c
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:06:35 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/ApiServlet.java | 45 +++++++++------------------
 1 file changed, 14 insertions(+), 31 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3cc6efce/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
index d09d426..8dff6eb 100644
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -22,10 +22,10 @@ import com.cloud.api.auth.APIAuthenticator;
 import com.cloud.user.Account;
 import com.cloud.user.AccountService;
 import com.cloud.user.User;
+import com.cloud.utils.HttpUtils;
 import com.cloud.utils.StringUtils;
 import com.cloud.utils.db.EntityManager;
 import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.managed.context.ManagedContext;
@@ -40,7 +40,6 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
-import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.util.HashMap;
@@ -125,7 +124,7 @@ public class ApiServlet extends HttpServlet {
         auditTrailSb.append(" ").append(remoteAddress);
         auditTrailSb.append(" -- ").append(req.getMethod()).append(' ');
         // get the response format since we'll need it in a couple of places
-        String responseType = BaseCmd.RESPONSE_TYPE_XML;
+        String responseType = HttpUtils.RESPONSE_TYPE_XML;
         final Map<String, Object[]> params = new HashMap<String, Object[]>();
         params.putAll(req.getParameterMap());
 
@@ -143,10 +142,11 @@ public class ApiServlet extends HttpServlet {
         }
 
         try {
-            if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
-                resp.setContentType(ApiServer.getJsonContentType() + "; charset=UTF-8");
-            } else {
-                resp.setContentType("text/xml; charset=UTF-8");
+
+            if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+                resp.setContentType(HttpUtils.JSON_CONTENT_TYPE);
+            } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)){
+                resp.setContentType(HttpUtils.XML_CONTENT_TYPE);
             }
 
             HttpSession session = req.getSession(false);
@@ -202,7 +202,7 @@ public class ApiServlet extends HttpServlet {
                             }
                         }
                     }
-                    writeResponse(resp, responseString, httpResponseCode, responseType);
+                    HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType);
                     return;
                 }
             }
@@ -229,7 +229,7 @@ public class ApiServlet extends HttpServlet {
                     auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
                     final String serializedResponse =
                         _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
-                    writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
+                    HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                     return;
                 }
 
@@ -240,7 +240,7 @@ public class ApiServlet extends HttpServlet {
                         s_logger.info("missing command, ignoring request...");
                         auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified");
                         final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType);
-                        writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType);
+                        HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType);
                         return;
                     }
                     final User user = _entityMgr.findById(User.class, userId);
@@ -256,7 +256,7 @@ public class ApiServlet extends HttpServlet {
                     auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
                     final String serializedResponse =
                         _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
-                    writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
+                    HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                     return;
                 }
             } else {
@@ -270,7 +270,7 @@ public class ApiServlet extends HttpServlet {
                 // Add the HTTP method (GET/POST/PUT/DELETE) as well into the params map.
                 params.put("httpmethod", new String[] {req.getMethod()});
                 final String response = _apiServer.handleRequest(params, responseType, auditTrailSb);
-                writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
+                HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
             } else {
                 if (session != null) {
                     try {
@@ -283,13 +283,13 @@ public class ApiServlet extends HttpServlet {
                 final String serializedResponse =
                     _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params,
                         responseType);
-                writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
+                HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
 
             }
         } catch (final ServerApiException se) {
             final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType);
             resp.setHeader("X-Description", se.getDescription());
-            writeResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType);
+            HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType);
             auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
         } catch (final Exception ex) {
             s_logger.error("unknown exception writing api response", ex);
@@ -303,21 +303,4 @@ public class ApiServlet extends HttpServlet {
             CallContext.unregister();
         }
     }
-
-    // FIXME: rather than isError, we might was to pass in the status code to give more flexibility
-    private void writeResponse(final HttpServletResponse resp, final String response, final int responseCode, final String responseType) {
-        try {
-            resp.setStatus(responseCode);
-            resp.getWriter().print(response);
-        } catch (final IOException ioex) {
-            if (s_logger.isTraceEnabled()) {
-                s_logger.trace("exception writing response: " + ioex);
-            }
-        } catch (final Exception ex) {
-            if (!(ex instanceof IllegalStateException)) {
-                s_logger.error("unknown exception writing api response", ex);
-            }
-        }
-    }
-
 }


[28/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiResponseSerializer: Use HttpUtils instead of BaseCmd

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/983252cf
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/983252cf
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/983252cf

Branch: refs/heads/master
Commit: 983252cffd69f4bd308663efe58fd7d2b7c2eeef
Parents: d64d59e
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:05:34 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/response/ApiResponseSerializer.java | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/983252cf/server/src/com/cloud/api/response/ApiResponseSerializer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java
index 5b0a46b..a32bd56 100644
--- a/server/src/com/cloud/api/response/ApiResponseSerializer.java
+++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java
@@ -21,6 +21,7 @@ import com.cloud.api.ApiResponseGsonHelper;
 import com.cloud.api.ApiServer;
 import com.cloud.serializer.Param;
 import com.cloud.user.Account;
+import com.cloud.utils.HttpUtils;
 import com.cloud.utils.encoding.URLEncoder;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.exception.ExceptionProxyObject;
@@ -54,7 +55,7 @@ public class ApiResponseSerializer {
 
     public static String toSerializedString(ResponseObject result, String responseType) {
         s_logger.trace("===Serializing Response===");
-        if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+        if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
             return toJSONSerializedString(result);
         } else {
             return toXMLSerializedString(result);


[24/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
BaseCmd: Use HttpUtils to have single source of static string values

cloud-api depends on cloud-utils, it makes sense to refactor and put common
and static stuff in cloud-utils

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/d64d59e8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/d64d59e8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/d64d59e8

Branch: refs/heads/master
Commit: d64d59e8f7d7ebb0fa6f68187f8eb5bfee5fcfb5
Parents: 315feb0
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:04:29 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 api/src/org/apache/cloudstack/api/BaseCmd.java | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d64d59e8/api/src/org/apache/cloudstack/api/BaseCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java
index ac9a208..1226566 100644
--- a/api/src/org/apache/cloudstack/api/BaseCmd.java
+++ b/api/src/org/apache/cloudstack/api/BaseCmd.java
@@ -29,6 +29,7 @@ import java.util.regex.Pattern;
 
 import javax.inject.Inject;
 
+import com.cloud.utils.HttpUtils;
 import org.apache.log4j.Logger;
 
 import org.apache.cloudstack.acl.RoleType;
@@ -84,8 +85,8 @@ import com.cloud.vm.snapshot.VMSnapshotService;
 
 public abstract class BaseCmd {
     private static final Logger s_logger = Logger.getLogger(BaseCmd.class.getName());
-    public static final String RESPONSE_TYPE_XML = "xml";
-    public static final String RESPONSE_TYPE_JSON = "json";
+    public static final String RESPONSE_TYPE_XML = HttpUtils.RESPONSE_TYPE_XML;
+    public static final String RESPONSE_TYPE_JSON = HttpUtils.RESPONSE_TYPE_JSON;
     public static final DateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
     public static final DateFormat NEW_INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     public static final String USER_ERROR_MESSAGE = "Internal error executing command, please contact your system administrator";


[11/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
APIAuthenticationManagerImpl: add the auth manager and bean entry in spring xmls

- This implements ManageBase, is a pluggable service
- Has a mechanism to return commands, useful for apidocs etc.
- Has a method to return APIAuthenticator based on API command name

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/bd2898e4
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bd2898e4
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bd2898e4

Branch: refs/heads/master
Commit: bd2898e4917727311cb76dc66b689e10ed264e1d
Parents: f7821ec
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:30:25 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../spring-server-core-managers-context.xml     |  2 +
 .../api/auth/APIAuthenticationManagerImpl.java  | 79 ++++++++++++++++++++
 2 files changed, 81 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bd2898e4/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
----------------------------------------------------------------------
diff --git a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
index 1eba0b2..17681f7 100644
--- a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
+++ b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
@@ -32,6 +32,8 @@
                       http://www.springframework.org/schema/util/spring-util-3.0.xsd"
                       >
 
+    <bean id="authenticationManagerImpl" class="com.cloud.api.auth.APIAuthenticationManagerImpl" />
+
     <bean id="accountManagerImpl" class="com.cloud.user.AccountManagerImpl">
         <property name="userAuthenticators"
             value="#{userAuthenticatorsRegistry.registered}" />

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bd2898e4/server/src/com/cloud/api/auth/APIAuthenticationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/APIAuthenticationManagerImpl.java b/server/src/com/cloud/api/auth/APIAuthenticationManagerImpl.java
new file mode 100644
index 0000000..886d277
--- /dev/null
+++ b/server/src/com/cloud/api/auth/APIAuthenticationManagerImpl.java
@@ -0,0 +1,79 @@
+// 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 com.cloud.api.auth;
+
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ManagerBase;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.log4j.Logger;
+
+import javax.ejb.Local;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Local(value = APIAuthenticationManager.class)
+@SuppressWarnings("unchecked")
+public class APIAuthenticationManagerImpl extends ManagerBase implements APIAuthenticationManager {
+    public static final Logger s_logger = Logger.getLogger(APIAuthenticationManagerImpl.class.getName());
+
+    private static Map<String, Class<?>> s_authenticators = null;
+    private static List<Class<?>> s_commandList = null;
+
+    public APIAuthenticationManagerImpl() {
+    }
+
+    @Override
+    public boolean start() {
+        s_authenticators = new HashMap<String, Class<?>>();
+        for (Class<?> authenticator: getCommands()) {
+            APICommand command = authenticator.getAnnotation(APICommand.class);
+            if (command != null && !command.name().isEmpty()
+                    && APIAuthenticator.class.isAssignableFrom(authenticator)) {
+                s_authenticators.put(command.name(), authenticator);
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public List<Class<?>> getCommands() {
+        if (s_commandList == null) {
+            s_commandList = new ArrayList<Class<?>>();
+            s_commandList.add(DefaultLoginAPIAuthenticatorCmd.class);
+            s_commandList.add(DefaultLogoutAPIAuthenticatorCmd.class);
+        }
+        return s_commandList;
+    }
+
+    @Override
+    public APIAuthenticator getAPIAuthenticator(String name) {
+        APIAuthenticator apiAuthenticator = null;
+        if (s_authenticators != null && s_authenticators.containsKey(name)) {
+            try {
+                apiAuthenticator = (APIAuthenticator) s_authenticators.get(name).newInstance();
+                apiAuthenticator = ComponentContext.inject(apiAuthenticator);
+            } catch (InstantiationException | IllegalAccessException e) {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("APIAuthenticationManagerImpl::getAPIAuthenticator failed: " + e.getMessage());
+                }
+            }
+        }
+        return apiAuthenticator;
+    }
+}


[12/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
APIAuthenticationType: Add auth enum type, login or logout

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4d3fbc54
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4d3fbc54
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4d3fbc54

Branch: refs/heads/master
Commit: 4d3fbc54ade6c41dfbb5b8968597e191fe40290c
Parents: 31722c2
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:27:20 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../cloud/api/auth/APIAuthenticationType.java   | 21 ++++++++++++++++++++
 1 file changed, 21 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d3fbc54/server/src/com/cloud/api/auth/APIAuthenticationType.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/APIAuthenticationType.java b/server/src/com/cloud/api/auth/APIAuthenticationType.java
new file mode 100644
index 0000000..bdd37ec
--- /dev/null
+++ b/server/src/com/cloud/api/auth/APIAuthenticationType.java
@@ -0,0 +1,21 @@
+// 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 com.cloud.api.auth;
+
+public enum APIAuthenticationType {
+    LOGIN_API, LOGOUT_API
+}


[27/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
utils: fix pom.xml to have references for javax.servlet api interfaces

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/bae8f2a8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bae8f2a8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bae8f2a8

Branch: refs/heads/master
Commit: bae8f2a8cb68621ea34e7a50b42f3a217261b041
Parents: 384acff
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:13:56 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 utils/pom.xml                            | 5 +++++
 utils/src/com/cloud/utils/HttpUtils.java | 3 +++
 2 files changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bae8f2a8/utils/pom.xml
----------------------------------------------------------------------
diff --git a/utils/pom.xml b/utils/pom.xml
index cc6de3b..27eeee3 100755
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -99,6 +99,11 @@
       <groupId>commons-configuration</groupId>
       <artifactId>commons-configuration</artifactId>
     </dependency>
+    <dependency>
+      <groupId>javax.servlet</groupId>
+      <artifactId>servlet-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
     <!-- Test dependency in mysql for db tests -->
     <dependency>
       <groupId>mysql</groupId>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bae8f2a8/utils/src/com/cloud/utils/HttpUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/HttpUtils.java b/utils/src/com/cloud/utils/HttpUtils.java
index f608b86..0ed2afa 100644
--- a/utils/src/com/cloud/utils/HttpUtils.java
+++ b/utils/src/com/cloud/utils/HttpUtils.java
@@ -1,3 +1,4 @@
+//
 // 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
@@ -14,6 +15,8 @@
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License.
+//
+
 package com.cloud.utils;
 
 import org.apache.log4j.Logger;


[13/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
APIAuthenticationManager: Add Auth manager definition

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/ac3adfec
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/ac3adfec
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/ac3adfec

Branch: refs/heads/master
Commit: ac3adfeca7efd307d221565ca37ff257c51b28ee
Parents: 4d3fbc5
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:27:52 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../api/auth/APIAuthenticationManager.java      | 24 ++++++++++++++++++++
 1 file changed, 24 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ac3adfec/server/src/com/cloud/api/auth/APIAuthenticationManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/APIAuthenticationManager.java b/server/src/com/cloud/api/auth/APIAuthenticationManager.java
new file mode 100644
index 0000000..7fd4da9
--- /dev/null
+++ b/server/src/com/cloud/api/auth/APIAuthenticationManager.java
@@ -0,0 +1,24 @@
+// 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 com.cloud.api.auth;
+
+import com.cloud.utils.component.PluggableService;
+
+public interface APIAuthenticationManager extends PluggableService {
+    public APIAuthenticator getAPIAuthenticator(String name);
+}


[10/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiResponseSerializer: Skip extra boxing for Auth responses

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b587291d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b587291d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b587291d

Branch: refs/heads/master
Commit: b587291d55aa734fcae1ac99c19f62edb5e18691
Parents: d29f467
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:32:38 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../api/response/ApiResponseSerializer.java     | 44 ++++++++++----------
 1 file changed, 21 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b587291d/server/src/com/cloud/api/response/ApiResponseSerializer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java
index 482834a..5b0a46b 100644
--- a/server/src/com/cloud/api/response/ApiResponseSerializer.java
+++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java
@@ -16,40 +16,38 @@
 // under the License.
 package com.cloud.api.response;
 
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.log4j.Logger;
-
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.ApiResponseGsonHelper;
+import com.cloud.api.ApiServer;
+import com.cloud.serializer.Param;
+import com.cloud.user.Account;
+import com.cloud.utils.encoding.URLEncoder;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.exception.ExceptionProxyObject;
 import com.google.gson.Gson;
 import com.google.gson.annotations.SerializedName;
-
 import org.apache.cloudstack.acl.RoleType;
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ResponseObject;
 import org.apache.cloudstack.api.response.AsyncJobResponse;
+import org.apache.cloudstack.api.response.AuthenticationCmdResponse;
 import org.apache.cloudstack.api.response.CreateCmdResponse;
 import org.apache.cloudstack.api.response.ExceptionResponse;
 import org.apache.cloudstack.api.response.ListResponse;
 import org.apache.cloudstack.api.response.SuccessResponse;
 import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
 
-import com.cloud.api.ApiDBUtils;
-import com.cloud.api.ApiResponseGsonHelper;
-import com.cloud.api.ApiServer;
-import com.cloud.serializer.Param;
-import com.cloud.user.Account;
-import com.cloud.utils.encoding.URLEncoder;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.exception.ExceptionProxyObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 public class ApiResponseSerializer {
     private static final Logger s_logger = Logger.getLogger(ApiResponseSerializer.class.getName());
@@ -120,7 +118,7 @@ public class ApiResponseSerializer {
                 String jsonStr = gson.toJson(result);
                 if ((jsonStr != null) && !"".equals(jsonStr)) {
                     jsonStr = unescape(jsonStr);
-                    if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse) {
+                    if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse || result instanceof AuthenticationCmdResponse) {
                         sb.append(jsonStr);
                     } else {
                         sb.append(" { \"").append(result.getObjectName()).append("\" : ").append(jsonStr).append(" } ");
@@ -153,7 +151,7 @@ public class ApiResponseSerializer {
                 }
             }
         } else {
-            if (result instanceof CreateCmdResponse || result instanceof AsyncJobResponse) {
+            if (result instanceof CreateCmdResponse || result instanceof AsyncJobResponse || result instanceof AuthenticationCmdResponse) {
                 serializeResponseObjFieldsXML(sb, result);
             } else {
                 serializeResponseObjXML(sb, result);


[22/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiServletTest: Fix test, now login/logout have their own API/class

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f11dcf8e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f11dcf8e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f11dcf8e

Branch: refs/heads/master
Commit: f11dcf8ef51008fd74d0ebe9e7a1e103fd979155
Parents: 224dc9f
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 09:16:52 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 server/test/com/cloud/api/ApiServletTest.java | 110 ++++++++-------------
 1 file changed, 41 insertions(+), 69 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f11dcf8e/server/test/com/cloud/api/ApiServletTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/api/ApiServletTest.java b/server/test/com/cloud/api/ApiServletTest.java
index 4d54599..0a90296 100644
--- a/server/test/com/cloud/api/ApiServletTest.java
+++ b/server/test/com/cloud/api/ApiServletTest.java
@@ -16,23 +16,14 @@
 // under the License.
 package com.cloud.api;
 
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Field;
-import java.net.URLEncoder;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
+import com.cloud.api.auth.APIAuthenticationManager;
+import com.cloud.api.auth.APIAuthenticationType;
+import com.cloud.api.auth.APIAuthenticator;
+import com.cloud.server.ManagementServer;
+import com.cloud.user.Account;
+import com.cloud.user.AccountService;
+import com.cloud.user.User;
 import org.apache.cloudstack.api.ApiConstants;
-import org.apache.commons.collections.iterators.IteratorEnumeration;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -41,17 +32,17 @@ import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.runners.MockitoJUnitRunner;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.XMLReaderFactory;
 
-import com.cloud.server.ManagementServer;
-import com.cloud.user.Account;
-import com.cloud.user.AccountService;
-import com.cloud.user.User;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Field;
+import java.net.URLEncoder;
+import java.util.HashMap;
 
 @RunWith(MockitoJUnitRunner.class)
 public class ApiServletTest {
@@ -69,6 +60,12 @@ public class ApiServletTest {
     AccountService accountService;
 
     @Mock
+    APIAuthenticationManager authManager;
+
+    @Mock
+    APIAuthenticator authenticator;
+
+    @Mock
     User user;
 
     @Mock
@@ -94,11 +91,20 @@ public class ApiServletTest {
         Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1");
         Mockito.when(accountService.getSystemUser()).thenReturn(user);
         Mockito.when(accountService.getSystemAccount()).thenReturn(account);
+
         Field accountMgrField = ApiServlet.class
                 .getDeclaredField("_accountMgr");
         accountMgrField.setAccessible(true);
         accountMgrField.set(servlet, accountService);
 
+        Mockito.when(authManager.getAPIAuthenticator(Mockito.anyString())).thenReturn(authenticator);
+        Mockito.when(authenticator.authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class),
+                Mockito.anyString(), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletResponse.class))).thenReturn("{\"loginresponse\":{}");
+
+        Field authManagerField = ApiServlet.class.getDeclaredField("_authManager");
+        authManagerField.setAccessible(true);
+        authManagerField.set(servlet, authManager);
+
         Field apiServerField = ApiServlet.class.getDeclaredField("_apiServer");
         apiServerField.setAccessible(true);
         apiServerField.set(servlet, apiServer);
@@ -197,9 +203,14 @@ public class ApiServletTest {
         params.put(ApiConstants.COMMAND, new String[] { "logout" });
         Mockito.when(request.getParameterMap()).thenReturn(params);
 
+        Mockito.when(authenticator.getAPIType()).thenReturn(APIAuthenticationType.LOGOUT_API);
+
         servlet.processRequestInContext(request, response);
 
-        Mockito.verify(apiServer).logoutUser(1l);
+
+        Mockito.verify(authManager).getAPIAuthenticator("logout");
+        Mockito.verify(authenticator).authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class),
+                Mockito.anyString(), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletResponse.class));
         Mockito.verify(session).invalidate();
     }
 
@@ -216,50 +227,11 @@ public class ApiServletTest {
         params.put(ApiConstants.DOMAIN_ID, new String[] { "42" });
         params.put(ApiConstants.DOMAIN, new String[] { "TEST-DOMAIN" });
         Mockito.when(request.getParameterMap()).thenReturn(params);
-        Mockito.when(apiServer.fetchDomainId("42")).thenReturn(null);
-        Mockito.when(session.getAttribute("userid")).thenReturn(1l);
-        Mockito.when(session.getAttribute("accountobj")).thenReturn(account);
 
         servlet.processRequestInContext(request, response);
 
-        Mockito.verify(request).getSession(true);
-        Mockito.verify(apiServer).loginUser(Mockito.any(HttpSession.class),
-                Mockito.eq("TEST"), Mockito.eq("TEST-PWD"), Mockito.eq(42l),
-                Mockito.eq("/TEST-DOMAIN/"), Mockito.eq("127.0.0.1"),
-                Mockito.any(Map.class));
-        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    public void getLoginSuccessResponseJson() throws JsonParseException,
-            IOException {
-        Mockito.when(session.getAttributeNames()).thenReturn(
-                new IteratorEnumeration(Arrays.asList("foo", "bar", "userid",
-                        "domainid").iterator()));
-        Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(
-                "TEST");
-
-        String loginResponse = servlet.getLoginSuccessResponse(session, "json");
-
-        ObjectNode node = (ObjectNode) new ObjectMapper()
-                .readTree(loginResponse);
-        Assert.assertNotNull(node.get("loginresponse"));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Test
-    public void getLoginSuccessResponseXml() throws JsonParseException,
-            IOException, SAXException {
-        Mockito.when(session.getAttributeNames()).thenReturn(
-                new IteratorEnumeration(Arrays.asList("foo", "bar", "userid",
-                        "domainid").iterator()));
-        Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(
-                "TEST");
-        String loginResponse = servlet.getLoginSuccessResponse(session, "xml");
-        XMLReaderFactory.createXMLReader().parse(
-                new InputSource(new StringReader(loginResponse)));
-        ;
+        Mockito.verify(authManager).getAPIAuthenticator("login");
+        Mockito.verify(authenticator).authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class),
+                Mockito.anyString(), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletResponse.class));
     }
-
 }


[14/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
DefaultLoginAPIAuthenticatorCmd: Refactor and implement the default login mechanism

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f7821ecf
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f7821ecf
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f7821ecf

Branch: refs/heads/master
Commit: f7821ecf0945ee5e2b249f2d9d8d19bb3d9cc888
Parents: 1330559
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:29:41 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../auth/DefaultLoginAPIAuthenticatorCmd.java   | 228 +++++++++++++++++++
 1 file changed, 228 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f7821ecf/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
new file mode 100644
index 0000000..5fa8e9e
--- /dev/null
+++ b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
@@ -0,0 +1,228 @@
+// 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 com.cloud.api.auth;
+
+import com.cloud.api.ApiServerService;
+import com.cloud.api.response.ApiResponseSerializer;
+import com.cloud.exception.CloudAuthenticationException;
+import com.cloud.user.Account;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ResponseObject;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.LoginCmdResponse;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.util.Enumeration;
+import java.util.Map;
+
+@APICommand(name = "login", description = "Logs a user into the CloudStack. A successful login attempt will generate a JSESSIONID cookie value that can be passed in subsequent Query command calls until the \"logout\" command has been issued or the session has expired.", requestHasSensitiveInfo = true, responseObject = LoginCmdResponse.class, entityType = {})
+public class DefaultLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator {
+
+    public static final Logger s_logger = Logger.getLogger(DefaultLoginAPIAuthenticatorCmd.class.getName());
+    private static final String s_name = "loginresponse";
+
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+    @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "Username", required = true)
+    private String username;
+
+    @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.", required = true)
+    private String password;
+
+    @Parameter(name = ApiConstants.DOMAIN, type = CommandType.STRING, description = "Path of the domain that the user belongs to. Example: domain=/com/cloud/internal. If no domain is passed in, the ROOT (/) domain is assumed.")
+    private String domain;
+
+    @Parameter(name = ApiConstants.DOMAIN__ID, type = CommandType.LONG, description = "The id of the domain that the user belongs to. If both domain and domainId are passed in, \"domainId\" parameter takes precendence")
+    private Long domainId;
+
+    @Inject
+    ApiServerService _apiServer;
+
+    /////////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public String getUsername() {
+        return username;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public String getDomain() {
+        return domain;
+    }
+
+    public Long getDomainId() {
+        return domainId;
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        return Account.ACCOUNT_TYPE_NORMAL;
+    }
+
+    @Override
+    public void execute() throws ServerApiException {
+        // We should never reach here
+        throw new ServerApiException(ApiErrorCode.METHOD_NOT_ALLOWED, "This is an authentication api, cannot be used directly");
+    }
+
+    private String createLoginResponse(HttpSession session, String responseType) {
+        LoginCmdResponse response = new LoginCmdResponse();
+        response.setTimeout(session.getMaxInactiveInterval());
+
+        final String user_UUID = (String)session.getAttribute("user_UUID");
+        session.removeAttribute("user_UUID");
+        response.setUserId(user_UUID);
+
+        final String domain_UUID = (String)session.getAttribute("domain_UUID");
+        session.removeAttribute("domain_UUID");
+        response.setDomainId(domain_UUID);
+
+        // FIXME: the while loop mess
+        final Enumeration attrNames = session.getAttributeNames();
+        if (attrNames != null) {
+            while (attrNames.hasMoreElements()) {
+                final String attrName = (String) attrNames.nextElement();
+                final Object attrObj = session.getAttribute(attrName);
+                if (ApiConstants.USER_ID.equalsIgnoreCase(attrName)) {
+                    response.setUserId(attrObj.toString());
+                }
+                if (ApiConstants.USERNAME.equalsIgnoreCase(attrName)) {
+                    response.setUsername(attrObj.toString());
+                }
+                if (ApiConstants.ACCOUNT.equalsIgnoreCase(attrName)) {
+                    response.setAccount(attrObj.toString());
+                }
+                if (ApiConstants.FIRSTNAME.equalsIgnoreCase(attrName)) {
+                    response.setFirstName(attrObj.toString());
+                }
+                if (ApiConstants.LASTNAME.equalsIgnoreCase(attrName)) {
+                    response.setLastName(attrObj.toString());
+                }
+                if (ApiConstants.TYPE.equalsIgnoreCase(attrName)) {
+                    response.setType((attrObj.toString()));
+                }
+                if (ApiConstants.TIMEZONE.equalsIgnoreCase(attrName)) {
+                    response.setTimeZone(attrObj.toString());
+                }
+                if (ApiConstants.REGISTERED.equalsIgnoreCase(attrName)) {
+                    response.setRegistered(attrObj.toString());
+                }
+                if (ApiConstants.SESSIONKEY.equalsIgnoreCase(attrName)) {
+                    response.setSessionKey(attrObj.toString());
+                }
+            }
+        }
+        response.setResponseName(getCommandName());
+        return ApiResponseSerializer.toSerializedString((ResponseObject) response, responseType);
+    }
+
+    @Override
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb) throws ServerApiException {
+
+        // FIXME: ported from ApiServlet, refactor and cleanup
+        final String[] username = (String[])params.get(ApiConstants.USERNAME);
+        final String[] password = (String[])params.get(ApiConstants.PASSWORD);
+        String[] domainIdArr = (String[])params.get(ApiConstants.DOMAIN_ID);
+
+        if (domainIdArr == null) {
+            domainIdArr = (String[])params.get(ApiConstants.DOMAIN__ID);
+        }
+        final String[] domainName = (String[])params.get(ApiConstants.DOMAIN);
+        Long domainId = null;
+        if ((domainIdArr != null) && (domainIdArr.length > 0)) {
+            try {
+                //check if UUID is passed in for domain
+                domainId = _apiServer.fetchDomainId(domainIdArr[0]);
+                if (domainId == null) {
+                    domainId = Long.parseLong(domainIdArr[0]);
+                }
+                auditTrailSb.append(" domainid=" + domainId);// building the params for POST call
+            } catch (final NumberFormatException e) {
+                s_logger.warn("Invalid domain id entered by user");
+                auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
+                throw new ServerApiException(ApiErrorCode.UNAUTHORIZED,
+                        _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
+                                responseType));
+            }
+        }
+
+        String domain = null;
+        if (domainName != null) {
+            domain = domainName[0];
+            auditTrailSb.append(" domain=" + domain);
+            if (domain != null) {
+                // ensure domain starts with '/' and ends with '/'
+                if (!domain.endsWith("/")) {
+                    domain += '/';
+                }
+                if (!domain.startsWith("/")) {
+                    domain = "/" + domain;
+                }
+            }
+        }
+
+        String serializedResponse = null;
+        if (username != null) {
+            final String pwd = ((password == null) ? null : password[0]);
+            try {
+                _apiServer.loginUser(session, username[0], pwd, domainId, domain, remoteAddress, params);
+                auditTrailSb.insert(0, "(userId=" + session.getAttribute("userid") + " accountId=" + ((Account) session.getAttribute("accountobj")).getId() +
+                        " sessionId=" + session.getId() + ")");
+                return createLoginResponse(session, responseType);
+            } catch (final CloudAuthenticationException ex) {
+                // TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
+                try {
+                    session.invalidate();
+                } catch (final IllegalStateException ise) {
+                }
+                auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage()
+                        : "failed to authenticate user, check if username/password are correct");
+                serializedResponse =
+                        _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage()
+                                : "failed to authenticate user, check if username/password are correct", params, responseType);
+            }
+        }
+        // We should not reach here and if we do we throw an exception
+        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, serializedResponse);
+    }
+
+    @Override
+    public APIAuthenticationType getAPIType() {
+        return APIAuthenticationType.LOGIN_API;
+    }
+}


[18/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiServlet: move setting of response type up in the layer

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6ec1a1b6
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6ec1a1b6
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6ec1a1b6

Branch: refs/heads/master
Commit: 6ec1a1b604e32ba000f72a8978e41b2799a9acd8
Parents: 7434f1b
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 09:14:50 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:31 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/ApiServlet.java | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6ec1a1b6/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
index 5a8cf94..d94894a 100644
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -143,6 +143,12 @@ public class ApiServlet extends HttpServlet {
         }
 
         try {
+            if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+                resp.setContentType(ApiServer.getJsonContentType() + "; charset=UTF-8");
+            } else {
+                resp.setContentType("text/xml; charset=UTF-8");
+            }
+
             HttpSession session = req.getSession(false);
             final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE);
             if (responseTypeParam != null) {
@@ -301,12 +307,6 @@ public class ApiServlet extends HttpServlet {
     // FIXME: rather than isError, we might was to pass in the status code to give more flexibility
     private void writeResponse(final HttpServletResponse resp, final String response, final int responseCode, final String responseType) {
         try {
-            if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
-                resp.setContentType(ApiServer.getJsonContentType() + "; charset=UTF-8");
-            } else {
-                resp.setContentType("text/xml; charset=UTF-8");
-            }
-
             resp.setStatus(responseCode);
             resp.getWriter().print(response);
         } catch (final IOException ioex) {


[23/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
DefaultLoginAPIAuthenticatorCmd: return userId as UUID

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/ae207bea
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/ae207bea
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/ae207bea

Branch: refs/heads/master
Commit: ae207bea988dee9b222301e58e488b29cff7989a
Parents: bae8f2a
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:55:07 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 .../src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java   | 3 ---
 1 file changed, 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ae207bea/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
index fe04ed9..f5d633e 100644
--- a/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
+++ b/server/src/com/cloud/api/auth/DefaultLoginAPIAuthenticatorCmd.java
@@ -118,9 +118,6 @@ public class DefaultLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthe
             while (attrNames.hasMoreElements()) {
                 final String attrName = (String) attrNames.nextElement();
                 final Object attrObj = session.getAttribute(attrName);
-                if (ApiConstants.USER_ID.equalsIgnoreCase(attrName)) {
-                    response.setUserId(attrObj.toString());
-                }
                 if (ApiConstants.USERNAME.equalsIgnoreCase(attrName)) {
                     response.setUsername(attrObj.toString());
                 }


[15/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
DefaultLogoutAPIAuthenticatorCmd: Refactor and implement the logout mechanism

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/1330559b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/1330559b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/1330559b

Branch: refs/heads/master
Commit: 1330559b8dfe94e2df484b538809dc5741d216dc
Parents: ac3adfe
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:29:14 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../auth/DefaultLogoutAPIAuthenticatorCmd.java  | 70 ++++++++++++++++++++
 1 file changed, 70 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/1330559b/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java b/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
new file mode 100644
index 0000000..ab4e162
--- /dev/null
+++ b/server/src/com/cloud/api/auth/DefaultLogoutAPIAuthenticatorCmd.java
@@ -0,0 +1,70 @@
+// 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 com.cloud.api.auth;
+
+import com.cloud.api.response.ApiResponseSerializer;
+import com.cloud.user.Account;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.LogoutCmdResponse;
+import org.apache.log4j.Logger;
+
+import javax.servlet.http.HttpSession;
+import java.util.Map;
+
+@APICommand(name = "logout", description = "Logs out the user", responseObject = LogoutCmdResponse.class, entityType = {})
+public class DefaultLogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator {
+
+    public static final Logger s_logger = Logger.getLogger(DefaultLoginAPIAuthenticatorCmd.class.getName());
+    private static final String s_name = "logoutresponse";
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        return Account.ACCOUNT_TYPE_NORMAL;
+    }
+
+    @Override
+    public void execute() throws ServerApiException {
+        // We should never reach here
+        throw new ServerApiException(ApiErrorCode.METHOD_NOT_ALLOWED, "This is an authentication api, cannot be used directly");
+    }
+
+    @Override
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb) throws ServerApiException {
+        auditTrailSb.append("=== Logging out ===");
+        LogoutCmdResponse response = new LogoutCmdResponse();
+        response.setDescription("success");
+        response.setResponseName(getCommandName());
+        return ApiResponseSerializer.toSerializedString(response, responseType);
+    }
+
+    @Override
+    public APIAuthenticationType getAPIType() {
+        return APIAuthenticationType.LOGOUT_API;
+    }
+}


[25/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
ApiServer: take UTF_8 and other static vars from HttpUtils

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/384acfff
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/384acfff
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/384acfff

Branch: refs/heads/master
Commit: 384acffff4548ce30f09641621096caa6bcd6f21
Parents: 3cc6efc
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 10:08:04 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:32 2014 +0200

----------------------------------------------------------------------
 server/src/com/cloud/api/ApiServer.java | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/384acfff/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java
index f5f5c81..5d6c925 100755
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@ -53,6 +53,7 @@ import javax.naming.ConfigurationException;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
+import com.cloud.utils.HttpUtils;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.http.ConnectionClosedException;
 import org.apache.http.HttpException;
@@ -174,7 +175,6 @@ import com.cloud.utils.exception.ExceptionProxyObject;
 
 @Component
 public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiServerService {
-    private static final String UTF_8 = "UTF-8";
     private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
     private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
 
@@ -392,7 +392,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
         try {
             List<NameValuePair> paramList = null;
             try {
-                paramList = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), UTF_8);
+                paramList = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), HttpUtils.UTF_8);
             } catch (final URISyntaxException e) {
                 s_logger.error("Error parsing url request", e);
             }
@@ -403,7 +403,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
             // (Immutable)Multimap<String, String> paramMultiMap = HashMultimap.create();
             // Map<String, Collection<String>> parameterMap = paramMultiMap.asMap();
             final Map parameterMap = new HashMap<String, String[]>();
-            String responseType = BaseCmd.RESPONSE_TYPE_XML;
+            String responseType = HttpUtils.RESPONSE_TYPE_XML;
             for (final NameValuePair param : paramList) {
                 if (param.getName().equalsIgnoreCase("response")) {
                     responseType = param.getValue();
@@ -416,8 +416,8 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
             parameterMap.put("httpmethod", new String[] {request.getRequestLine().getMethod()});
 
             // Check responseType, if not among valid types, fallback to JSON
-            if (!(responseType.equals(BaseCmd.RESPONSE_TYPE_JSON) || responseType.equals(BaseCmd.RESPONSE_TYPE_XML))) {
-                responseType = BaseCmd.RESPONSE_TYPE_XML;
+            if (!(responseType.equals(HttpUtils.RESPONSE_TYPE_JSON) || responseType.equals(HttpUtils.RESPONSE_TYPE_XML))) {
+                responseType = HttpUtils.RESPONSE_TYPE_XML;
             }
 
             try {
@@ -827,9 +827,9 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
                     }
 
                     if (unsignedRequest == null) {
-                        unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, UTF_8).replaceAll("\\+", "%20");
+                        unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                     } else {
-                        unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, UTF_8).replaceAll("\\+", "%20");
+                        unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, HttpUtils.UTF_8).replaceAll("\\+", "%20");
                     }
                 }
             }
@@ -1077,21 +1077,21 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
             resp.setReasonPhrase(reasonPhrase);
 
             final BasicHttpEntity body = new BasicHttpEntity();
-            if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
+            if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
                 // JSON response
                 body.setContentType(jsonContentType);
                 if (responseText == null) {
-                    body.setContent(new ByteArrayInputStream("{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes(UTF_8)));
+                    body.setContent(new ByteArrayInputStream("{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes(HttpUtils.UTF_8)));
                 }
             } else {
                 body.setContentType("text/xml");
                 if (responseText == null) {
-                    body.setContent(new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes(UTF_8)));
+                    body.setContent(new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes(HttpUtils.UTF_8)));
                 }
             }
 
             if (responseText != null) {
-                body.setContent(new ByteArrayInputStream(responseText.getBytes(UTF_8)));
+                body.setContent(new ByteArrayInputStream(responseText.getBytes(HttpUtils.UTF_8)));
             }
             resp.setEntity(body);
         } catch (final Exception ex) {


[09/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
response: add command response for login and logout command classes

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/d29f467d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/d29f467d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/d29f467d

Branch: refs/heads/master
Commit: d29f467d914f34f0ef691aeb8919afecac0aa4b1
Parents: bd2898e
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:31:51 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:30 2014 +0200

----------------------------------------------------------------------
 .../api/response/AuthenticationCmdResponse.java |  22 +++
 .../api/response/LoginCmdResponse.java          | 156 +++++++++++++++++++
 .../api/response/LogoutCmdResponse.java         |  36 +++++
 3 files changed, 214 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d29f467d/api/src/org/apache/cloudstack/api/response/AuthenticationCmdResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/AuthenticationCmdResponse.java b/api/src/org/apache/cloudstack/api/response/AuthenticationCmdResponse.java
new file mode 100644
index 0000000..43aaee4
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/AuthenticationCmdResponse.java
@@ -0,0 +1,22 @@
+// 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.cloudstack.api.response;
+
+import org.apache.cloudstack.api.BaseResponse;
+
+public class AuthenticationCmdResponse extends BaseResponse {
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d29f467d/api/src/org/apache/cloudstack/api/response/LoginCmdResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/LoginCmdResponse.java b/api/src/org/apache/cloudstack/api/response/LoginCmdResponse.java
new file mode 100644
index 0000000..3139b6f
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/LoginCmdResponse.java
@@ -0,0 +1,156 @@
+// 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.cloudstack.api.response;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+import org.apache.cloudstack.api.ApiConstants;
+
+public class LoginCmdResponse extends AuthenticationCmdResponse {
+
+    @SerializedName(value = ApiConstants.USERNAME)
+    @Param(description = "Username")
+    private String username;
+
+    @SerializedName(value = ApiConstants.USER_ID)
+    @Param(description = "User ID")
+    private String userId;
+
+    @SerializedName(value = ApiConstants.DOMAIN_ID)
+    @Param(description = "Domain ID that the user belongs to")
+    private String domainId;
+
+    @SerializedName(value = ApiConstants.TIMEOUT)
+    @Param(description = "the time period before the session has expired")
+    private Integer timeout;
+
+    @SerializedName(value = ApiConstants.ACCOUNT)
+    @Param(description = "the account name the user belongs to")
+    private String account;
+
+    @SerializedName(value = ApiConstants.FIRSTNAME)
+    @Param(description = "first name of the user")
+    private String firstName;
+
+    @SerializedName(value = ApiConstants.LASTNAME)
+    @Param(description = "last name of the user")
+    private String lastName;
+
+    @SerializedName(value = ApiConstants.TYPE)
+    @Param(description = "the account type (admin, domain-admin, read-only-admin, user)")
+    private String type;
+
+    @SerializedName(value = ApiConstants.TIMEZONE)
+    @Param(description = "user time zone")
+    private String timeZone;
+
+    @SerializedName(value = ApiConstants.REGISTERED)
+    @Param(description = "Is user registered")
+    private String registered;
+
+    @SerializedName(value = ApiConstants.SESSIONKEY)
+    @Param(description = "Session key that can be passed in subsequent Query command calls")
+    private String sessionKey;
+
+    public String getUsername() {
+        return username;
+    }
+
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
+    public String getDomainId() {
+        return domainId;
+    }
+
+    public void setDomainId(String domainId) {
+        this.domainId = domainId;
+    }
+
+    public Integer getTimeout() {
+        return timeout;
+    }
+
+    public void setTimeout(Integer timeout) {
+        this.timeout = timeout;
+    }
+
+    public String getAccount() {
+        return account;
+    }
+
+    public void setAccount(String account) {
+        this.account = account;
+    }
+
+    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 getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getTimeZone() {
+        return timeZone;
+    }
+
+    public void setTimeZone(String timeZone) {
+        this.timeZone = timeZone;
+    }
+
+    public String getRegistered() {
+        return registered;
+    }
+
+    public void setRegistered(String registered) {
+        this.registered = registered;
+    }
+
+    public String getSessionKey() {
+        return sessionKey;
+    }
+
+    public void setSessionKey(String sessionKey) {
+        this.sessionKey = sessionKey;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d29f467d/api/src/org/apache/cloudstack/api/response/LogoutCmdResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/LogoutCmdResponse.java b/api/src/org/apache/cloudstack/api/response/LogoutCmdResponse.java
new file mode 100644
index 0000000..4f872f5
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/LogoutCmdResponse.java
@@ -0,0 +1,36 @@
+// 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.cloudstack.api.response;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+import org.apache.cloudstack.api.ApiConstants;
+
+@SuppressWarnings("unused")
+public class LogoutCmdResponse extends AuthenticationCmdResponse {
+    @SerializedName(value = ApiConstants.DESCRIPTION)
+    @Param(description = "Response description")
+    private String description;
+
+    public String getDescription() {
+        return this.description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+}


[08/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
commands.properties: add login,logout,samlsso,samlslo apis

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6016613d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6016613d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6016613d

Branch: refs/heads/master
Commit: 6016613d5b8041d84ce655c43a9f095b407054b9
Parents: e6d2b23
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Tue Aug 12 07:25:08 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 client/tomcatconf/commands.properties.in | 6 ++++++
 1 file changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6016613d/client/tomcatconf/commands.properties.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index 33699c0..e3e892b 100644
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -18,6 +18,12 @@
 ### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER
 ### Please standardize naming conventions to camel-case (even for acronyms).
 
+### CloudStack authentication commands
+login=15
+logout=15
+samlsso=15
+samlslo=15
+
 ### Account commands
 createAccount=7
 deleteAccount=7


[05/28] git commit: updated refs/heads/master to ae207be

Posted by bh...@apache.org.
saml2: add spring security saml2 extension 1.0.0.RELEASE

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c35f704f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c35f704f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c35f704f

Branch: refs/heads/master
Commit: c35f704f21db3d42e8d0a7bd711a159f9fe867ab
Parents: f7f8f07
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Fri Aug 8 10:11:37 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue Aug 12 12:01:29 2014 +0200

----------------------------------------------------------------------
 plugins/user-authenticators/saml2/pom.xml | 7 +++++++
 1 file changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c35f704f/plugins/user-authenticators/saml2/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/pom.xml b/plugins/user-authenticators/saml2/pom.xml
index bfe5eb7..00b3ff0 100644
--- a/plugins/user-authenticators/saml2/pom.xml
+++ b/plugins/user-authenticators/saml2/pom.xml
@@ -26,4 +26,11 @@
     <version>4.5.0-SNAPSHOT</version>
     <relativePath>../../pom.xml</relativePath>
   </parent>
+  <dependencies>
+    <dependency>
+      <groupId>org.springframework.security.extensions</groupId>
+      <artifactId>spring-security-saml2-core</artifactId>
+      <version>1.0.0.RELEASE</version>
+    </dependency>
+  </dependencies>
 </project>