Skip to content
Snippets Groups Projects
Commit 4c09aa32 authored by Sharon Goliath's avatar Sharon Goliath
Browse files

Merge branch 'nep110' into s1668

parents 1f064407 3f08cda6
No related branches found
No related tags found
No related merge requests found
Showing
with 4062 additions and 0 deletions
JAR files required for the OpenCADC cadcAccessControl-Server project
====================================================================
Name in build.xml Versioned Name Project URL
----------------- -------------- -----------
jdom.jar jdom-1.1 http://www.jdom.org
log4j.jar log4j-1.2.15 http://logging.apache.org
xerces.jar xerces-2_9_1 http://xerces.apache.org
servlet-api.jar apache-tomcat-5.5.20 http://tomcat.apache.org
jdom2jar jdom-2.0.5 http://www.jdom.org
cadcRegistryClient.jar http://code.google.com/p/opencadc
cadcUtil.jar http://code.google.com/p/opencadc
cadcAccessControl.jar http://code.google.com/p/opencadc
cadcUWS.jar http://code.google.com/p/opencadc
cadcLog.jar http://code.google.com/p/opencadc
\ No newline at end of file
## commented out values are the defaults, shown as examples
## to customise behaviour, subclass the specified class and
## change the configuration here
## UserPersistence implementation
ca.nrc.cadc.ac.server.UserPersistence = ca.nrc.cadc.ac.server.ldap.LdapUserPersistence
## GroupPersistence implementation
ca.nrc.cadc.ac.server.GroupPersistence = ca.nrc.cadc.ac.server.ldap.LdapGroupPersistence
\ No newline at end of file
<!--
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2009. (c) 2009.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
-->
<!DOCTYPE project>
<project default="build" basedir=".">
<property environment="env"/>
<property file="local.build.properties" />
<!-- site-specific build properties or overrides of values in opencadc.properties -->
<property file="${env.CADC_PREFIX}/etc/local.properties" />
<!-- site-specific targets, e.g. install, cannot duplicate those in opencadc.targets.xml -->
<import file="${env.CADC_PREFIX}/etc/local.targets.xml" optional="true" />
<!-- default properties and targets -->
<property file="${env.CADC_PREFIX}/etc/opencadc.properties" />
<import file="${env.CADC_PREFIX}/etc/opencadc.targets.xml"/>
<!-- developer convenience: place for extra targets and properties -->
<import file="extras.xml" optional="true" />
<property name="project" value="cadcAccessControl-Server" />
<property name="cadcAccessControl" value="${lib}/cadcAccessControl.jar" />
<property name="cadcLog" value="${lib}/cadcLog.jar" />
<property name="cadcRegistry" value="${lib}/cadcRegistryClient.jar" />
<property name="cadcUtil" value="${lib}/cadcUtil.jar" />
<property name="cadcUWS" value="${lib}/cadcUWS.jar" />
<property name="jdom2" value="${ext.lib}/jdom2.jar" />
<property name="log4j" value="${ext.lib}/log4j.jar" />
<property name="servlet" value="${ext.lib}/servlet-api.jar" />
<property name="unboundid" value="${ext.lib}/unboundid-ldapsdk-se.jar" />
<property name="xerces" value="${ext.lib}/xerces.jar" />
<property name="jars" value="${cadcAccessControl}:${cadcLog}:${cadcRegistry}:${cadcUtil}:${cadcUWS}:${jdom2}:${log4j}:${servlet}:${unboundid}:${xerces}" />
<target name="build" depends="compile">
<jar jarfile="${build}/lib/${project}.jar"
basedir="${build}/class"
update="no">
<include name="ca/nrc/cadc/**" />
</jar>
</target>
<!-- JAR files needed to run the test suite -->
<property name="gson" value="${ext.lib}/gson.jar" />
<property name="easyMock" value="${ext.dev}/easymock.jar" />
<property name="junit" value="${ext.dev}/junit.jar" />
<property name="xmlunit" value="${ext.dev}/xmlunit.jar" />
<property name="xerces" value="${ext.lib}/xerces.jar" />
<property name="cglib" value="${ext.dev}/cglib.jar" />
<property name="objenesis" value="${ext.dev}/objenesis.jar" />
<property name="asm" value="${ext.dev}/asm.jar" />
<property name="testingJars" value="${jars}:${gson}:${easyMock}:${junit}:${xmlunit}:${xerces}:${cglib}:${asm}:${objenesis}" />
<target name="resources">
<copy todir="${build}/class">
<fileset dir="config">
<include name="**.properties" />
</fileset>
</copy>
</target>
<!-- <target name="test" depends="compile-test,resources">
<echo message="Running test suite..." />
<junit printsummary="yes" haltonfailure="yes" fork="yes">
<classpath>
<pathelement path="${build}/class"/>
<pathelement path="${build}/test/class"/>
<pathelement path="${testingJars}"/>
</classpath>
<test name="ca.nrc.cadc.ac.server.ldap.LdapDAOTest" />
<formatter type="plain" usefile="false" />
</junit>
</target>-->
</project>
# This are the configuration fields required by the Ldap ldap-dao unit tests
server = mach275.cadc.dao.nrc.ca
port = 389
admin = uid=webproxy,ou=administrators,ou=topologymanagement,o=netscaperoot
passwd = go4it
usersDn = ou=Users,ou=ds,dc=canfar,dc=net
groupsDn = ou=Groups,ou=ds,dc=canfar,dc=net
deletedGroupsDN = ou=DeletedGroups,ou=ds,dc=canfar,dc=net
testGroupsDN = ou=TestGroups,ou=ds,dc=canfar,dc=net
\ No newline at end of file
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Collection;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupAlreadyExistsException;
import ca.nrc.cadc.ac.GroupNotFoundException;
import ca.nrc.cadc.ac.Role;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.net.TransientException;
public abstract interface GroupPersistence<T extends Principal>
{
/**
* Get the group with the given Group ID.
*
* @param groupID The Group ID.
*
* @return A Group instance
*
* @throws GroupNotFoundException If the group was not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract Group getGroup(String groupID)
throws GroupNotFoundException, TransientException,
AccessControlException;
/**
* Creates the group.
*
* @param group The group to create
*
* @return created group
*
* @throws GroupAlreadyExistsException If a group with the same ID already
* exists.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
* @throws UserNotFoundException If owner or a member not valid user.
*/
public abstract Group addGroup(Group group)
throws GroupAlreadyExistsException, TransientException,
AccessControlException, UserNotFoundException;
/**
* Deletes the group.
*
* @param groupID The Group ID.
*
* @throws GroupNotFoundException If the group was not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract void deleteGroup(String groupID)
throws GroupNotFoundException, TransientException,
AccessControlException;
/**
* Modify the given group.
*
* @param group The group to update.
*
* @return The newly updated group.
*
* @throws GroupNotFoundException If the group was not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
* @throws UserNotFoundException If owner or group members not valid users.
*/
public abstract Group modifyGroup(Group group)
throws GroupNotFoundException, TransientException,
AccessControlException, UserNotFoundException;
/**
* Obtain a Collection of Groups that fit the given query.
*
* @param userID The userID.
* @param role Role of the user, either owner, member, or read/write.
* @param groupID The Group ID.
*
* @return Collection of Groups matching the query, or empty Collection.
* Never null.
*
* @throws UserNotFoundException If owner or group members not valid users.
* @throws ca.nrc.cadc.ac.GroupNotFoundException
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract Collection<Group> getGroups(T userID, Role role,
String groupID)
throws UserNotFoundException, GroupNotFoundException,
TransientException, AccessControlException;
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server;
import ca.nrc.cadc.ac.server.ldap.LdapGroupPersistence;
import ca.nrc.cadc.ac.server.ldap.LdapUserPersistence;
import java.net.URL;
import java.security.Principal;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
public class PluginFactory
{
private static final Logger log = Logger.getLogger(PluginFactory.class);
private static final String CONFIG = PluginFactory.class.getSimpleName() + ".properties";
private Properties config;
public PluginFactory()
{
init();
}
@Override
public String toString()
{
return getClass().getName() + "[" + config.entrySet().size() + "]";
}
private void init()
{
config = new Properties();
URL url = null;
try
{
url = PluginFactory.class.getClassLoader().getResource(CONFIG);
if (url != null)
{
config.load(url.openStream());
}
}
catch (Exception ex)
{
throw new RuntimeException("failed to read " + CONFIG + " from " + url, ex);
}
}
@SuppressWarnings("unchecked")
public <T extends Principal> GroupPersistence<T> getGroupPersistence()
{
GroupPersistence<T> ret = null;
String name = GroupPersistence.class.getName();
String cname = config.getProperty(name);
if (cname == null)
{
ret = new LdapGroupPersistence<T>();
}
else
{
try
{
Class<?> c = Class.forName(cname);
ret = (GroupPersistence<T>) c.newInstance();
}
catch (Exception ex)
{
throw new RuntimeException("config error: failed to create GroupPersistence " + cname, ex);
}
}
return ret;
}
@SuppressWarnings("unchecked")
public <T extends Principal> UserPersistence<T> getUserPersistence()
{
UserPersistence<T> ret = null;
String name = UserPersistence.class.getName();
String cname = config.getProperty(name);
if (cname == null)
{
ret = new LdapUserPersistence<T>();
}
else
{
try
{
Class<?> c = Class.forName(cname);
ret = (UserPersistence<T>) c.newInstance();
}
catch (Exception ex)
{
throw new RuntimeException("config error: failed to create UserPersistence " + cname, ex);
}
}
return ret;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server;
import java.security.Principal;
import java.util.List;
import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.Role;
import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.uws.Parameter;
import ca.nrc.cadc.uws.ParameterUtil;
/**
* Request Validator. This class extracts and validates the ID, TYPE, ROLE
* and GURI parameters.
*
*/
public class RequestValidator
{
private static final Logger log = Logger.getLogger(RequestValidator.class);
private Principal principal;
private Role role;
private String groupID;
public RequestValidator() { }
private void clear()
{
this.principal = null;
this.role = null;
this.groupID = null;
}
public void validate(List<Parameter> paramList)
{
clear();
if (paramList == null || paramList.isEmpty())
{
throw new IllegalArgumentException(
"Missing required parameters: ID, IDTYPE, ROLE");
}
// ID
String param = ParameterUtil.findParameterValue("ID", paramList);
if (param == null || param.trim().isEmpty())
{
throw new IllegalArgumentException(
"ID parameter required but not found");
}
String userID = param.trim();
log.debug("ID: " + userID);
// TYPE
param = ParameterUtil.findParameterValue("IDTYPE", paramList);
if (param == null || param.trim().isEmpty())
{
throw new IllegalArgumentException(
"IDTYPE parameter required but not found");
}
principal =
AuthenticationUtil.createPrincipal(userID,
param.trim());
log.debug("TYPE: " + param.trim());
// ROLE
param = ParameterUtil.findParameterValue("ROLE", paramList);
if (param == null || param.trim().isEmpty())
{
throw new IllegalArgumentException(
"ROLE parameter required but not found");
}
this.role = Role.toValue(param);
log.debug("ROLE: " + role);
// GROUPID
param = ParameterUtil.findParameterValue("GROUPID", paramList);
if (param != null)
{
if (param.isEmpty())
throw new IllegalArgumentException(
"GROUPID parameter specified without a value");
this.groupID = param.trim();
}
log.debug("GROUPID: " + groupID);
}
public Principal getPrincipal()
{
return principal;
}
public Role getRole()
{
return role;
}
public String getGroupID()
{
return groupID;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.net.TransientException;
import com.unboundid.ldap.sdk.DN;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Collection;
public abstract interface UserPersistence<T extends Principal>
{
/**
* Get the user specified by userID.
*
* @param userID The userID.
*
* @return User instance.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract User<T> getUser(T userID)
throws UserNotFoundException, TransientException,
AccessControlException;
/**
* Get all groups the user specified by userID belongs to.
*
* @param userID The userID.
* @param isAdmin return only admin Groups when true, else return non-admin
* Groups.
*
* @return Collection of group DN.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract Collection<DN> getUserGroups(T userID, boolean isAdmin)
throws UserNotFoundException, TransientException,
AccessControlException;
/**
* Check whether the user is a member of the group.
*
* @param userID The userID.
* @param groupID The groupID.
*
* @return true or false
*
* @throws UserNotFoundException If the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public abstract boolean isMember(T userID, String groupID)
throws UserNotFoundException, TransientException,
AccessControlException;
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.ldap;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import ca.nrc.cadc.util.StringUtil;
public class LdapConfig
{
private static final Logger logger = Logger.getLogger(LdapConfig.class);
public static final String CONFIG = LdapConfig.class.getSimpleName() +
".properties";
public static final String LDAP_SERVER = "server";
public static final String LDAP_PORT = "port";
public static final String LDAP_ADMIN = "admin";
public static final String LDAP_PASSWD = "passwd";
public static final String LDAP_USERS_DN = "usersDn";
public static final String LDAP_GROUPS_DN = "groupsDn";
public static final String LDAP_ADMIN_GROUPS_DN = "adminGroupsDn";
public static final String LDAP_AVAIL_TEST_GROUP = "availabilityTestGroup";
public static final String LDAP_AVAIL_TEST_CALLING_USER_DN = "availabilityTestCallingUserDN";
private String usersDN;
private String groupsDN;
private String adminGroupsDN;
private String server;
private int port;
private String adminUserDN;
private String adminPasswd;
private String availabilityTestGroup;
private String availabilityTestCallingUserDN;
public static LdapConfig getLdapConfig()
{
Properties config = new Properties();
URL url = null;
try
{
url = LdapConfig.class.getClassLoader().getResource(CONFIG);
logger.debug("Using config from: " + url);
if (url != null)
{
config.load(url.openStream());
}
else
{
throw new IOException("File not found");
}
}
catch (Exception ex)
{
throw new RuntimeException("failed to read " + CONFIG +
" from " + url, ex);
}
String server = config.getProperty(LDAP_SERVER);
if (!StringUtil.hasText(server))
{
throw new RuntimeException("failed to read property " +
LDAP_SERVER);
}
String port = config.getProperty(LDAP_PORT);
if (!StringUtil.hasText(port))
{
throw new RuntimeException("failed to read property " + LDAP_PORT);
}
String ldapAdmin = config.getProperty(LDAP_ADMIN);
if (!StringUtil.hasText(ldapAdmin))
{
throw new RuntimeException("failed to read property " + LDAP_ADMIN);
}
String ldapPasswd = config.getProperty(LDAP_PASSWD);
if (!StringUtil.hasText(ldapPasswd))
{
throw new RuntimeException("failed to read property " +
LDAP_PASSWD);
}
String ldapUsersDn = config.getProperty(LDAP_USERS_DN);
if (!StringUtil.hasText(ldapUsersDn))
{
throw new RuntimeException("failed to read property " +
LDAP_USERS_DN);
}
String ldapGroupsDn = config.getProperty(LDAP_GROUPS_DN);
if (!StringUtil.hasText(ldapGroupsDn))
{
throw new RuntimeException("failed to read property " +
LDAP_GROUPS_DN);
}
String ldapAdminGroupsDn = config.getProperty(LDAP_ADMIN_GROUPS_DN);
if (!StringUtil.hasText(ldapAdminGroupsDn))
{
throw new RuntimeException("failed to read property " +
LDAP_ADMIN_GROUPS_DN);
}
String availGroup = config.getProperty(LDAP_AVAIL_TEST_GROUP);
if (!StringUtil.hasText(availGroup))
{
throw new RuntimeException("failed to read property " +
LDAP_AVAIL_TEST_GROUP);
}
String availUser = config.getProperty(LDAP_AVAIL_TEST_CALLING_USER_DN);
if (!StringUtil.hasText(availUser))
{
throw new RuntimeException("failed to read property " +
LDAP_AVAIL_TEST_CALLING_USER_DN);
}
return new LdapConfig(server, Integer.valueOf(port), ldapAdmin,
ldapPasswd, ldapUsersDn, ldapGroupsDn,
ldapAdminGroupsDn, availGroup, availUser);
}
public LdapConfig(String server, int port, String adminUserDN,
String adminPasswd, String usersDN, String groupsDN,
String adminGroupsDN)
{
this(server, port, adminUserDN, adminPasswd, usersDN, groupsDN, adminGroupsDN, null, null);
}
public LdapConfig(String server, int port, String adminUserDN,
String adminPasswd, String usersDN, String groupsDN,
String adminGroupsDN, String availGroup, String availUser)
{
if (!StringUtil.hasText(server))
{
throw new IllegalArgumentException("Illegal LDAP server name");
}
if (port < 0)
{
throw new IllegalArgumentException("Illegal LDAP server port: " +
port);
}
if (!StringUtil.hasText(adminUserDN))
{
throw new IllegalArgumentException("Illegal Admin DN");
}
if (!StringUtil.hasText(adminPasswd))
{
throw new IllegalArgumentException("Illegal Admin password");
}
if (!StringUtil.hasText(usersDN))
{
throw new IllegalArgumentException("Illegal users LDAP DN");
}
if (!StringUtil.hasText(groupsDN))
{
throw new IllegalArgumentException("Illegal groups LDAP DN");
}
if (!StringUtil.hasText(adminGroupsDN))
{
throw new IllegalArgumentException("Illegal admin groups LDAP DN");
}
this.server = server;
this.port = port;
this.adminUserDN = adminUserDN;
this.adminPasswd = adminPasswd;
this.usersDN = usersDN;
this.groupsDN = groupsDN;
this.adminGroupsDN = adminGroupsDN;
this.availabilityTestGroup = availGroup;
this.availabilityTestCallingUserDN = availUser;
}
public String getUsersDN()
{
return this.usersDN;
}
public String getGroupsDN()
{
return this.groupsDN;
}
public String getAdminGroupsDN()
{
return this.adminGroupsDN;
}
public String getServer()
{
return this.server;
}
public int getPort()
{
return this.port;
}
public String getAdminUserDN()
{
return this.adminUserDN;
}
public String getAdminPasswd()
{
return this.adminPasswd;
}
public String getAvailabilityTestGroup()
{
return this.availabilityTestGroup;
}
public String getAvailabilityTestCallingUserDN()
{
return this.availabilityTestCallingUserDN;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.ldap;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.Principal;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.auth.NumericPrincipal;
import ca.nrc.cadc.auth.OpenIdPrincipal;
import ca.nrc.cadc.net.TransientException;
import com.unboundid.ldap.sdk.DN;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
public abstract class LdapDAO
{
private LDAPConnection conn;
LdapConfig config;
DN subjDN = null;
public LdapDAO(LdapConfig config)
{
if (config == null)
{
throw new IllegalArgumentException("LDAP config required");
}
this.config = config;
}
public void close()
{
if (conn != null)
{
conn.close();
}
}
protected LDAPConnection getConnection()
throws LDAPException, AccessControlException
{
if (conn == null)
{
conn = new LDAPConnection(config.getServer(), config.getPort());
conn.bind(config.getAdminUserDN(), config.getAdminPasswd());
}
return conn;
}
protected DN getSubjectDN() throws LDAPException
{
if (subjDN == null)
{
Subject callerSubject =
Subject.getSubject(AccessController.getContext());
if (callerSubject == null)
{
throw new AccessControlException("Caller not authenticated.");
}
Set<Principal> principals = callerSubject.getPrincipals();
if (principals.isEmpty())
{
throw new AccessControlException("Caller not authenticated.");
}
String ldapField = null;
for (Principal p : principals)
{
if (p instanceof HttpPrincipal)
{
ldapField = "(uid=" + p.getName() + ")";
break;
}
if (p instanceof NumericPrincipal)
{
ldapField = "(entryid=" + p.getName() + ")";
break;
}
if (p instanceof X500Principal)
{
ldapField = "(distinguishedname=" + p.getName() + ")";
break;
}
if (p instanceof OpenIdPrincipal)
{
ldapField = "(openid=" + p.getName() + ")";
break;
}
}
if (ldapField == null)
{
throw new AccessControlException("Identity of caller unknown.");
}
SearchResult searchResult =
getConnection().search(config.getUsersDN(), SearchScope.ONE,
ldapField, new String[] {"entrydn"});
if (searchResult.getEntryCount() < 1)
{
throw new AccessControlException(
"No LDAP account when search with rule " + ldapField);
}
subjDN = ((SearchResultEntry) searchResult.getSearchEntries()
.get(0)).getAttributeValueAsDN("entrydn");
}
return subjDN;
}
/**
* Checks the Ldap result code, and if the result is not SUCCESS,
* throws an appropriate exception. This is the place to decide on
* mapping between ldap errors and exception types
* @param code
* @param errorMsg
* @throws TransientException
*/
protected static void checkLdapResult(ResultCode code)
throws TransientException
{
if (code == ResultCode.INSUFFICIENT_ACCESS_RIGHTS)
{
throw new AccessControlException("Not authorized ");
}
else if (code == ResultCode.INVALID_CREDENTIALS)
{
throw new AccessControlException("Invalid credentials ");
}
else if ((code == ResultCode.SUCCESS) || (code == ResultCode.NO_SUCH_OBJECT) )
{
// all good. nothing to do
}
else if (code == ResultCode.PARAM_ERROR)
{
throw new IllegalArgumentException("Error in Ldap parameters ");
}
else if (code == ResultCode.BUSY ||
code == ResultCode.CONNECT_ERROR )
{
throw new TransientException("Connection problems ");
}
else
{
throw new RuntimeException("Ldap error (" + code.getName() + ")");
}
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.ldap;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Collection;
import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupAlreadyExistsException;
import ca.nrc.cadc.ac.GroupNotFoundException;
import ca.nrc.cadc.ac.Role;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.ac.server.GroupPersistence;
import ca.nrc.cadc.net.TransientException;
public class LdapGroupPersistence<T extends Principal>
implements GroupPersistence<T>
{
private static final Logger log =
Logger.getLogger(LdapGroupPersistence.class);
private final LdapConfig config;
public LdapGroupPersistence()
{
config = LdapConfig.getLdapConfig();
}
public Group getGroup(String groupName)
throws GroupNotFoundException, TransientException,
AccessControlException
{
LdapGroupDAO<T> groupDAO = null;
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(config);
groupDAO = new LdapGroupDAO<T>(config, userDAO);
Group ret = groupDAO.getGroup(groupName);
return ret;
}
finally
{
if (groupDAO != null)
{
groupDAO.close();
}
if (userDAO != null)
{
userDAO.close();
}
}
}
public Group addGroup(Group group)
throws GroupAlreadyExistsException, TransientException,
AccessControlException, UserNotFoundException
{
LdapGroupDAO<T> groupDAO = null;
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(config);
groupDAO = new LdapGroupDAO<T>(config, userDAO);
Group ret = groupDAO.addGroup(group);
return ret;
}
finally
{
if (groupDAO != null)
{
groupDAO.close();
}
if (userDAO != null)
{
userDAO.close();
}
}
}
public void deleteGroup(String groupName)
throws GroupNotFoundException, TransientException,
AccessControlException
{
LdapGroupDAO<T> groupDAO = null;
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(config);
groupDAO = new LdapGroupDAO<T>(config, userDAO);
groupDAO.deleteGroup(groupName);
}
finally
{
if (groupDAO != null)
{
groupDAO.close();
}
if (userDAO != null)
{
userDAO.close();
}
}
}
public Group modifyGroup(Group group)
throws GroupNotFoundException, TransientException,
AccessControlException, UserNotFoundException
{
LdapGroupDAO<T> groupDAO = null;
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(config);
groupDAO = new LdapGroupDAO<T>(config, userDAO);
Group ret = groupDAO.modifyGroup(group);
return ret;
}
finally
{
if (groupDAO != null)
{
groupDAO.close();
}
if (userDAO != null)
{
userDAO.close();
}
}
}
public Collection<Group> getGroups(T userID, Role role, String groupID)
throws UserNotFoundException, GroupNotFoundException,
TransientException, AccessControlException
{
LdapGroupDAO<T> groupDAO = null;
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(config);
groupDAO = new LdapGroupDAO<T>(config, userDAO);
Collection<Group> ret = groupDAO.getGroups(userID, role, groupID);
return ret;
}
finally
{
if (groupDAO != null)
{
groupDAO.close();
}
if (userDAO != null)
{
userDAO.close();
}
}
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.ldap;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.PersonalDetails;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.net.TransientException;
import com.unboundid.ldap.sdk.DN;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl;
public class LdapUserDAO<T extends Principal> extends LdapDAO
{
private static final Logger logger = Logger.getLogger(LdapUserDAO.class);
// Map of identity type to LDAP attribute
private Map<Class<?>, String> userLdapAttrib = new HashMap<Class<?>, String>();
// User attributes returned to the GMS
private static final String LDAP_FNAME = "givenname";
private static final String LDAP_LNAME = "sn";
//TODO to add the rest
private String[] userAttribs = new String[]{LDAP_FNAME, LDAP_LNAME};
private String[] memberAttribs = new String[]{LDAP_FNAME, LDAP_LNAME};
public LdapUserDAO(LdapConfig config)
{
super(config);
this.userLdapAttrib.put(HttpPrincipal.class, "uid");
this.userLdapAttrib.put(X500Principal.class, "distinguishedname");
// add the id attributes to user and member attributes
String[] princs = userLdapAttrib.values().toArray(new String[userLdapAttrib.values().size()]);
String[] tmp = new String[userAttribs.length + princs.length];
System.arraycopy(princs, 0, tmp, 0, princs.length);
System.arraycopy(userAttribs, 0, tmp, princs.length, userAttribs.length);
userAttribs = tmp;
tmp = new String[memberAttribs.length + princs.length];
System.arraycopy(princs, 0, tmp, 0, princs.length);
System.arraycopy(memberAttribs, 0, tmp, princs.length, memberAttribs.length);
memberAttribs = tmp;
}
/**
* Get the user specified by userID.
*
* @param userID The userID.
*
* @return User instance.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public User<T> getUser(T userID)
throws UserNotFoundException, TransientException, AccessControlException
{
String searchField = (String) userLdapAttrib.get(userID.getClass());
if (searchField == null)
{
throw new IllegalArgumentException(
"Unsupported principal type " + userID.getClass());
}
searchField = "(&(objectclass=cadcaccount)(" + searchField + "=" + userID.getName() + "))";
SearchResultEntry searchResult = null;
try
{
SearchRequest searchRequest = new SearchRequest(config.getUsersDN(),
SearchScope.SUB, searchField, userAttribs);
searchRequest.addControl(
new ProxiedAuthorizationV2RequestControl("dn:" +
getSubjectDN().toNormalizedString()));
searchResult = getConnection().searchForEntry(searchRequest);
}
catch (LDAPException e)
{
LdapDAO.checkLdapResult(e.getResultCode());
}
if (searchResult == null)
{
String msg = "User not found " + userID.toString();
logger.debug(msg);
throw new UserNotFoundException(msg);
}
User<T> user = new User<T>(userID);
user.getIdentities().add(
new HttpPrincipal(searchResult.getAttributeValue(userLdapAttrib
.get(HttpPrincipal.class))));
String fname = searchResult.getAttributeValue(LDAP_FNAME);
String lname = searchResult.getAttributeValue(LDAP_LNAME);
user.details.add(new PersonalDetails(fname, lname));
//TODO populate user with the other returned personal or posix attributes
return user;
}
/**
* Get all groups the user specified by userID belongs to.
*
* @param userID The userID.
* @param isAdmin
*
* @return Collection of Group instances.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred., e.getMessage(
* @throws AccessControlException If the operation is not permitted.
*/
public Collection<DN> getUserGroups(final T userID, final boolean isAdmin)
throws UserNotFoundException, TransientException, AccessControlException
{
Collection<DN> groupDNs = new HashSet<DN>();
try
{
String searchField = (String) userLdapAttrib.get(userID.getClass());
if (searchField == null)
{
throw new IllegalArgumentException(
"Unsupported principal type " + userID.getClass());
}
User<T> user = getUser(userID);
Filter filter = Filter.createANDFilter(
Filter.createEqualityFilter(searchField,
user.getUserID().getName()),
Filter.createPresenceFilter("memberOf"));
SearchRequest searchRequest =
new SearchRequest(config.getUsersDN(), SearchScope.SUB,
filter, "memberOf");
searchRequest.addControl(
new ProxiedAuthorizationV2RequestControl("dn:" +
getSubjectDN().toNormalizedString()));
SearchResultEntry searchResult =
getConnection().searchForEntry(searchRequest);
DN parentDN;
if (isAdmin)
{
parentDN = new DN(config.getAdminGroupsDN());
}
else
{
parentDN = new DN(config.getGroupsDN());
}
if (searchResult != null)
{
String[] members = searchResult.getAttributeValues("memberOf");
if (members != null)
{
for (String member : members)
{
DN groupDN = new DN(member);
if (groupDN.isDescendantOf(parentDN, false))
{
groupDNs.add(groupDN);
}
}
}
}
}
catch (LDAPException e)
{
LdapDAO.checkLdapResult(e.getResultCode());
}
return groupDNs;
}
/**
* Check whether the user is a member of the group.
*
* @param userID The userID.
* @param groupID The groupID.
*
* @return true or false
*
* @throws UserNotFoundException If the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public boolean isMember(T userID, String groupID)
throws UserNotFoundException, TransientException,
AccessControlException
{
try
{
String searchField = (String) userLdapAttrib.get(userID.getClass());
if (searchField == null)
{
throw new IllegalArgumentException(
"Unsupported principal type " + userID.getClass());
}
User<T> user = getUser(userID);
Filter filter = Filter.createANDFilter(
Filter.createEqualityFilter(searchField,
user.getUserID().getName()),
Filter.createEqualityFilter("memberOf", groupID));
SearchRequest searchRequest =
new SearchRequest(config.getUsersDN(), SearchScope.SUB,
filter, new String[] {"cn"});
searchRequest.addControl(
new ProxiedAuthorizationV2RequestControl("dn:" +
getSubjectDN().toNormalizedString()));
SearchResultEntry searchResults =
getConnection().searchForEntry(searchRequest);
if (searchResults == null)
{
return false;
}
return true;
}
catch (LDAPException e)
{
LdapDAO.checkLdapResult(e.getResultCode());
}
return false;
}
// public boolean isMember(T userID, String groupID)
// throws UserNotFoundException, TransientException,
// AccessControlException
// {
// try
// {
// String searchField = (String) userLdapAttrib.get(userID.getClass());
// if (searchField == null)
// {
// throw new IllegalArgumentException(
// "Unsupported principal type " + userID.getClass());
// }
//
// User<T> user = getUser(userID);
// DN userDN = getUserDN(user);
//
// CompareRequest compareRequest =
// new CompareRequest(userDN.toNormalizedString(),
// "memberOf", groupID);
//
// compareRequest.addControl(
// new ProxiedAuthorizationV2RequestControl("dn:" +
// getSubjectDN().toNormalizedString()));
//
// CompareResult compareResult =
// getConnection().compare(compareRequest);
// return compareResult.compareMatched();
// }
// catch (LDAPException e)
// {
// LdapDAO.checkLdapResult(e.getResultCode());
// throw new RuntimeException("Unexpected LDAP exception", e);
// }
// }
/**
* Returns a member user identified by the X500Principal only. The
* returned object has the fields required by the GMS.
* Note that this method binds as a proxy user and not as the
* subject.
* @param userDN
* @return
* @throws UserNotFoundException
* @throws LDAPException
*/
User<X500Principal> getMember(DN userDN)
throws UserNotFoundException, LDAPException
{
Filter filter =
Filter.createEqualityFilter("entrydn",
userDN.toNormalizedString());
SearchRequest searchRequest =
new SearchRequest(this.config.getUsersDN(), SearchScope.SUB,
filter, memberAttribs);
SearchResultEntry searchResult =
getConnection().searchForEntry(searchRequest);
if (searchResult == null)
{
String msg = "Member not found " + userDN;
logger.debug(msg);
throw new UserNotFoundException(msg);
}
User<X500Principal> user = new User<X500Principal>(
new X500Principal(searchResult.getAttributeValue(
(String) userLdapAttrib.get(X500Principal.class))));
String princ = searchResult.getAttributeValue(
(String) userLdapAttrib.get(HttpPrincipal.class));
if (princ != null)
{
user.getIdentities().add(new HttpPrincipal(princ));
}
String fname = searchResult.getAttributeValue(LDAP_FNAME);
String lname = searchResult.getAttributeValue(LDAP_LNAME);
user.details.add(new PersonalDetails(fname, lname));
return user;
}
DN getUserDN(User<? extends Principal> user)
throws UserNotFoundException, TransientException
{
String searchField = (String) userLdapAttrib.get(user.getUserID().getClass());
if (searchField == null)
{
throw new IllegalArgumentException(
"Unsupported principal type " + user.getUserID().getClass());
}
searchField = "(" + searchField + "=" +
user.getUserID().getName() + ")";
SearchResultEntry searchResult = null;
try
{
SearchRequest searchRequest = new SearchRequest(this.config.getUsersDN(), SearchScope.SUB,
searchField, new String[] {"entrydn"});
searchResult =
getConnection().searchForEntry(searchRequest);
} catch (LDAPException e)
{
LdapDAO.checkLdapResult(e.getResultCode());
}
if (searchResult == null)
{
String msg = "User not found " + user.getUserID().getName();
logger.debug(msg);
throw new UserNotFoundException(msg);
}
return searchResult.getAttributeValueAsDN("entrydn");
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.ldap;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.net.TransientException;
import com.unboundid.ldap.sdk.DN;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Collection;
import org.apache.log4j.Logger;
public class LdapUserPersistence<T extends Principal>
implements UserPersistence<T>
{
private static final Logger logger = Logger.getLogger(LdapUserPersistence.class);
private LdapConfig config;
public LdapUserPersistence()
{
try
{
this.config = LdapConfig.getLdapConfig();
}
catch (RuntimeException e)
{
logger.error("test/config/LdapConfig.properties file required.", e);
}
}
/**
* Get the user specified by userID.
*
* @param userID The userID.
*
* @return User instance.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public User<T> getUser(T userID)
throws UserNotFoundException, TransientException, AccessControlException
{
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(this.config);
User<T> ret = userDAO.getUser(userID);
return ret;
}
finally
{
if (userDAO != null)
{
userDAO.close();
}
}
}
/**
* Get all groups the user specified by userID belongs to.
*
* @param userID The userID.
* @param isAdmin return only admin Groups when true, else return non-admin
* Groups.
*
* @return Collection of Group DN.
*
* @throws UserNotFoundException when the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public Collection<DN> getUserGroups(T userID, boolean isAdmin)
throws UserNotFoundException, TransientException, AccessControlException
{
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(this.config);
Collection<DN> ret = userDAO.getUserGroups(userID, isAdmin);
return ret;
}
finally
{
if (userDAO != null)
{
userDAO.close();
}
}
}
/**
* Check whether the user is a member of the group.
*
* @param userID The userID.
* @param groupID The groupID.
*
* @return true or false
*
* @throws UserNotFoundException If the user is not found.
* @throws TransientException If an temporary, unexpected problem occurred.
* @throws AccessControlException If the operation is not permitted.
*/
public boolean isMember(T userID, String groupID)
throws UserNotFoundException, TransientException,
AccessControlException
{
LdapUserDAO<T> userDAO = null;
try
{
userDAO = new LdapUserDAO<T>(this.config);
boolean ret = userDAO.isMember(userID, groupID);
return ret;
}
finally
{
if (userDAO != null)
{
userDAO.close();
}
}
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web;
import java.io.IOException;
import java.security.AccessControlContext;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.Principal;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupNotFoundException;
import ca.nrc.cadc.ac.GroupsWriter;
import ca.nrc.cadc.ac.UserNotFoundException;
import ca.nrc.cadc.ac.server.GroupPersistence;
import ca.nrc.cadc.ac.server.PluginFactory;
import ca.nrc.cadc.ac.server.RequestValidator;
import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.net.TransientException;
import ca.nrc.cadc.uws.ExecutionPhase;
import ca.nrc.cadc.uws.Job;
import ca.nrc.cadc.uws.server.JobRunner;
import ca.nrc.cadc.uws.server.JobUpdater;
import ca.nrc.cadc.uws.server.SyncOutput;
import ca.nrc.cadc.uws.util.JobLogInfo;
public class ACSearchRunner implements JobRunner
{
private static Logger log = Logger.getLogger(ACSearchRunner.class);
private JobUpdater jobUpdater;
private SyncOutput syncOut;
private Job job;
private JobLogInfo logInfo;
@Override
public void setJobUpdater(JobUpdater jobUpdater)
{
this.jobUpdater = jobUpdater;
}
@Override
public void setJob(Job job)
{
this.job = job;
}
@Override
public void setSyncOutput(SyncOutput syncOut)
{
this.syncOut = syncOut;
}
@Override
public void run()
{
AccessControlContext acContext = AccessController.getContext();
Subject subject = Subject.getSubject(acContext);
log.debug("RUN ACSearchRunner: " + subject);
if (log.isDebugEnabled())
{
Set<Principal> principals = subject.getPrincipals();
Iterator<Principal> i = principals.iterator();
while (i.hasNext())
{
Principal next = i.next();
log.debug("Principal " +
next.getClass().getSimpleName()
+ ": " + next.getName());
}
}
logInfo = new JobLogInfo(job);
logInfo.setSubject(subject);
String startMessage = logInfo.start();
log.info(startMessage);
long t1 = System.currentTimeMillis();
search(subject);
long t2 = System.currentTimeMillis();
logInfo.setElapsedTime(t2 - t1);
String endMessage = logInfo.end();
log.info(endMessage);
}
@SuppressWarnings("unchecked")
private void search(Subject subject)
{
// Note: This search runner is customized to run with
// InMemoryJobPersistence, and synchronous POST requests are
// dealt with immediately, rather than returning results via
// a redirect.
// Jobs in this runner are never updated after execution begins
// in case the in-memory job has gone away. Error reporting
// is done directly through the response on both POST and GET
try
{
ExecutionPhase ep =
jobUpdater.setPhase(job.getID(), ExecutionPhase.QUEUED,
ExecutionPhase.EXECUTING, new Date());
if ( !ExecutionPhase.EXECUTING.equals(ep) )
{
throw new IllegalStateException("QUEUED -> EXECUTING [FAILED]");
}
log.debug(job.getID() + ": QUEUED -> EXECUTING [OK]");
RequestValidator rv = new RequestValidator();
rv.validate(job.getParameterList());
// only allow users to search themselves...
Principal userBeingSearched = rv.getPrincipal();
boolean idMatch = false;
if (userBeingSearched instanceof X500Principal)
{
Set<X500Principal> x500Principals = subject.getPrincipals(X500Principal.class);
Iterator<X500Principal> i = x500Principals.iterator();
while (i.hasNext())
{
X500Principal next = i.next();
log.debug(String.format("Comparing x500: [%s][%s]",
next.getName(), userBeingSearched.getName()));
if (AuthenticationUtil.equals(next, userBeingSearched))
idMatch = true;
}
}
else if (userBeingSearched instanceof HttpPrincipal)
{
Set<HttpPrincipal> httpPrincipals = subject.getPrincipals(HttpPrincipal.class);
Iterator<HttpPrincipal> i = httpPrincipals.iterator();
while (i.hasNext())
{
HttpPrincipal next = i.next();
log.debug(String.format("Comparing http: [%s][%s]",
next.getName(), userBeingSearched.getName()));
if (next.equals(userBeingSearched))
idMatch = true;
}
}
if (!idMatch)
throw new AccessControlException("Can only search oneself.");
PluginFactory factory = new PluginFactory();
GroupPersistence dao = factory.getGroupPersistence();
Collection<Group> groups =
dao.getGroups(rv.getPrincipal(), rv.getRole(), rv.getGroupID());
syncOut.setResponseCode(HttpServletResponse.SC_OK);
GroupsWriter.write(groups, syncOut.getOutputStream());
// Mark the Job as completed.
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.COMPLETED, new Date());
}
catch (TransientException t)
{
logInfo.setSuccess(false);
logInfo.setMessage(t.getMessage());
log.error("FAIL", t);
syncOut.setResponseCode(503);
syncOut.setHeader("Content-Type", "text/plan");
try
{
syncOut.getOutputStream().write(t.getMessage().getBytes());
}
catch (IOException e)
{
log.warn("Could not write response to output stream", e);
}
// ErrorSummary errorSummary =
// new ErrorSummary(t.getMessage(), ErrorType.FATAL);
// try
// {
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.ERROR, errorSummary,
// new Date());
// }
// catch(Throwable oops)
// {
// log.debug("failed to set final error status after " + t, oops);
// }
}
catch (UserNotFoundException t)
{
logInfo.setSuccess(false);
logInfo.setMessage(t.getMessage());
log.debug("FAIL", t);
syncOut.setResponseCode(404);
syncOut.setHeader("Content-Type", "text/plan");
try
{
syncOut.getOutputStream().write(t.getMessage().getBytes());
}
catch (IOException e)
{
log.warn("Could not write response to output stream", e);
}
// ErrorSummary errorSummary =
// new ErrorSummary(t.getMessage(), ErrorType.FATAL);
// try
// {
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.ERROR, errorSummary,
// new Date());
// }
// catch(Throwable oops)
// {
// log.debug("failed to set final error status after " + t, oops);
// }
}
catch (GroupNotFoundException t)
{
logInfo.setSuccess(false);
logInfo.setMessage(t.getMessage());
log.debug("FAIL", t);
syncOut.setResponseCode(404);
syncOut.setHeader("Content-Type", "text/plan");
try
{
syncOut.getOutputStream().write(t.getMessage().getBytes());
}
catch (IOException e)
{
log.warn("Could not write response to output stream", e);
}
// ErrorSummary errorSummary =
// new ErrorSummary(t.getMessage(), ErrorType.FATAL);
// try
// {
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.ERROR, errorSummary,
// new Date());
// }
// catch(Throwable oops)
// {
// log.debug("failed to set final error status after " + t, oops);
// }
}
catch (AccessControlException t)
{
logInfo.setSuccess(false);
logInfo.setMessage(t.getMessage());
log.debug("FAIL", t);
syncOut.setResponseCode(403);
syncOut.setHeader("Content-Type", "text/plan");
try
{
syncOut.getOutputStream().write(t.getMessage().getBytes());
}
catch (IOException e)
{
log.warn("Could not write response to output stream", e);
}
// ErrorSummary errorSummary =
// new ErrorSummary(t.getMessage(), ErrorType.FATAL);
// try
// {
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.ERROR, errorSummary,
// new Date());
// }
// catch(Throwable oops)
// {
// log.debug("failed to set final error status after " + t, oops);
// }
}
catch (Throwable t)
{
logInfo.setSuccess(false);
logInfo.setMessage(t.getMessage());
log.error("FAIL", t);
syncOut.setResponseCode(500);
syncOut.setHeader("Content-Type", "text/plan");
try
{
syncOut.getOutputStream().write(t.getMessage().getBytes());
}
catch (IOException e)
{
log.warn("Could not write response to output stream", e);
}
// ErrorSummary errorSummary =
// new ErrorSummary(t.getMessage(), ErrorType.FATAL);
// try
// {
// jobUpdater.setPhase(job.getID(), ExecutionPhase.EXECUTING,
// ExecutionPhase.ERROR, errorSummary,
// new Date());
// }
// catch(Throwable oops)
// {
// log.debug("failed to set final error status after " + t, oops);
// }
}
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupAlreadyExistsException;
import ca.nrc.cadc.ac.server.GroupPersistence;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class AddGroupMemberAction extends GroupsAction
{
private final String groupName;
private final String groupMemberName;
AddGroupMemberAction(GroupLogInfo logInfo, String groupName,
String groupMemberName)
{
super(logInfo);
this.groupName = groupName;
this.groupMemberName = groupMemberName;
}
public Object run()
throws Exception
{
GroupPersistence groupPersistence = getGroupPersistence();
Group group = groupPersistence.getGroup(this.groupName);
Group toAdd = groupPersistence.getGroup(this.groupMemberName);
if (!group.getGroupMembers().add(toAdd))
{
throw new GroupAlreadyExistsException(this.groupMemberName);
}
groupPersistence.modifyGroup(group);
List<String> addedMembers = new ArrayList<String>();
addedMembers.add(toAdd.getID());
logGroupInfo(group.getID(), null, addedMembers);
return null;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.MemberAlreadyExistsException;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.GroupPersistence;
import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.auth.AuthenticationUtil;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class AddUserMemberAction extends GroupsAction
{
private final String groupName;
private final String userID;
private final String userIDType;
AddUserMemberAction(GroupLogInfo logInfo, String groupName, String userID,
String userIDType)
{
super(logInfo);
this.groupName = groupName;
this.userID = userID;
this.userIDType = userIDType;
}
@SuppressWarnings("unchecked")
public Object run()
throws Exception
{
GroupPersistence groupPersistence = getGroupPersistence();
UserPersistence userPersistence = getUserPersistence();
Group group = groupPersistence.getGroup(this.groupName);
Principal userPrincipal = AuthenticationUtil.createPrincipal(this.userID, this.userIDType);
User toAdd = userPersistence.getUser(userPrincipal);
if (!group.getUserMembers().add(toAdd))
{
throw new MemberAlreadyExistsException();
}
groupPersistence.modifyGroup(group);
List<String> addedMembers = new ArrayList<String>();
addedMembers.add(toAdd.getUserID().getName());
logGroupInfo(group.getID(), null, addedMembers);
return null;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupReader;
import ca.nrc.cadc.ac.GroupWriter;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.GroupPersistence;
import java.io.InputStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
public class CreateGroupAction extends GroupsAction
{
private final InputStream inputStream;
CreateGroupAction(GroupLogInfo logInfo, InputStream inputStream)
{
super(logInfo);
this.inputStream = inputStream;
}
public Object run()
throws Exception
{
GroupPersistence groupPersistence = getGroupPersistence();
Group group = GroupReader.read(this.inputStream);
Group newGroup = groupPersistence.addGroup(group);
this.response.setContentType("application/xml");
GroupWriter.write(newGroup, this.response.getOutputStream());
List<String> addedMembers = null;
if ((newGroup.getUserMembers().size() > 0) || (newGroup.getGroupMembers().size() > 0))
{
addedMembers = new ArrayList<String>();
for (Group gr : newGroup.getGroupMembers())
{
addedMembers.add(gr.getID());
}
for (User usr : newGroup.getUserMembers())
{
addedMembers.add(usr.getUserID().getName());
}
}
logGroupInfo(newGroup.getID(), null, addedMembers);
return null;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.server.web;
import java.util.ArrayList;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.GroupPersistence;
public class DeleteGroupAction extends GroupsAction
{
private final String groupName;
DeleteGroupAction(GroupLogInfo logInfo, String groupName)
{
super(logInfo);
this.groupName = groupName;
}
public Object run()
throws Exception
{
GroupPersistence groupPersistence = getGroupPersistence();
Group deletedGroup = groupPersistence.getGroup(this.groupName);
groupPersistence.deleteGroup(this.groupName);
if ((deletedGroup.getUserMembers().size() > 0) || (deletedGroup.getGroupMembers().size() > 0))
{
this.logInfo.deletedMembers = new ArrayList<String>();
for (Group gr : deletedGroup.getGroupMembers())
{
this.logInfo.deletedMembers.add(gr.getID());
}
for (User usr : deletedGroup.getUserMembers())
{
this.logInfo.deletedMembers.add(usr.getUserID().getName());
}
}
return null;
}
}
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2014. (c) 2014.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/package ca.nrc.cadc.ac.server.web;
import ca.nrc.cadc.ac.Group;
import ca.nrc.cadc.ac.GroupWriter;
import ca.nrc.cadc.ac.server.GroupPersistence;
import javax.servlet.http.HttpServletResponse;
public class GetGroupAction extends GroupsAction
{
private final String groupName;
GetGroupAction(GroupLogInfo logInfo, String groupName)
{
super(logInfo);
this.groupName = groupName;
}
public Object run()
throws Exception
{
GroupPersistence groupPersistence = getGroupPersistence();
Group group = groupPersistence.getGroup(this.groupName);
this.response.setContentType("application/xml");
GroupWriter.write(group, this.response.getOutputStream());
return null;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment