2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 * This document is a part of the source code and related artifacts
25 * for CollectionSpace, an open source collections management system
26 * for museums and related institutions:
28 * http://www.collectionspace.org
29 * http://wiki.collectionspace.org
31 * Copyright 2009 University of California at Berkeley
33 * Licensed under the Educational Community License (ECL), Version 2.0.
34 * You may not use this file except in compliance with this License.
36 * You may obtain a copy of the ECL 2.0 License at
38 * https://source.collectionspace.org/collection-space/LICENSE.txt
40 * Unless required by applicable law or agreed to in writing, software
41 * distributed under the License is distributed on an "AS IS" BASIS,
42 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43 * See the License for the specific language governing permissions and
44 * limitations under the License.
47 * To change this template, choose Tools | Templates
48 * and open the template in the editor.
50 package org.collectionspace.authentication.realm.db;
52 import java.lang.reflect.Constructor;
53 import java.security.Principal;
54 import java.security.acl.Group;
55 import java.sql.Connection;
56 import java.sql.PreparedStatement;
57 import java.sql.ResultSet;
58 import java.sql.SQLException;
59 import java.util.Collection;
60 import java.util.HashMap;
63 import javax.naming.Context;
64 import javax.naming.InitialContext;
65 import javax.naming.NamingException;
66 import javax.security.auth.login.FailedLoginException;
67 import javax.security.auth.login.LoginException;
68 import javax.sql.DataSource;
70 //import org.apache.commons.logging.Log;
71 //import org.apache.commons.logging.LogFactory;
73 import org.collectionspace.authentication.AuthN;
74 import org.collectionspace.authentication.CSpaceTenant;
75 import org.collectionspace.authentication.realm.CSpaceRealm;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * CSpaceDbRealm provides access to user, password, role, tenant database
84 public class CSpaceDbRealm implements CSpaceRealm {
86 private Logger logger = LoggerFactory.getLogger(CSpaceDbRealm.class);
88 private String datasourceName;
89 private String principalsQuery;
90 private String rolesQuery;
91 private String tenantsQueryNoDisabled;
92 private String tenantsQueryWithDisabled;
93 private boolean suspendResume;
96 * CSpace Database Realm
97 * @param datasourceName datasource name
99 public CSpaceDbRealm(Map options) {
100 datasourceName = (String) options.get("dsJndiName");
101 if (datasourceName == null) {
102 datasourceName = "java:/DefaultDS";
104 Object tmp = options.get("principalsQuery");
106 principalsQuery = tmp.toString();
108 tmp = options.get("rolesQuery");
110 rolesQuery = tmp.toString();
112 tmp = options.get("tenantsQueryNoDisabled");
114 tenantsQueryNoDisabled = tmp.toString();
116 tmp = options.get("tenantsQueryWithDisabled");
118 tenantsQueryWithDisabled = tmp.toString();
120 tmp = options.get("suspendResume");
122 suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
124 if (logger.isTraceEnabled()) {
125 logger.trace("DatabaseServerLoginModule, dsJndiName=" + datasourceName);
126 logger.trace("principalsQuery=" + principalsQuery);
127 logger.trace("rolesQuery=" + rolesQuery);
128 logger.trace("suspendResume=" + suspendResume);
134 public String getUsersPassword(String username) throws LoginException {
136 String password = null;
137 Connection conn = null;
138 PreparedStatement ps = null;
141 conn = getConnection();
143 if (logger.isDebugEnabled()) {
144 logger.debug("Executing query: " + principalsQuery + ", with username: " + username);
146 ps = conn.prepareStatement(principalsQuery);
147 ps.setString(1, username);
148 rs = ps.executeQuery();
149 if (rs.next() == false) {
150 if (logger.isDebugEnabled()) {
151 logger.debug(principalsQuery + " returned no matches from db");
153 throw new FailedLoginException("No matching username found");
156 password = rs.getString(1);
157 } catch (SQLException ex) {
158 if (logger.isTraceEnabled() == true) {
159 logger.error("Could not open database to read AuthN tables.", ex);
161 LoginException le = new LoginException("Authentication query failed: " + ex.getLocalizedMessage());
164 } catch (Exception ex) {
165 LoginException le = new LoginException("Unknown Exception");
172 } catch (SQLException e) {
178 } catch (SQLException e) {
184 } catch (SQLException ex) {
192 * Execute the rolesQuery against the datasourceName to obtain the roles for
193 * the authenticated user.
194 * @return collection containing the roles
197 public Collection<Group> getRoles(String username, String principalClassName, String groupClassName) throws LoginException {
199 if (logger.isDebugEnabled()) {
200 logger.debug("getRoleSets using rolesQuery: " + rolesQuery + ", username: " + username);
203 Connection conn = null;
204 HashMap<String, Group> groupsMap = new HashMap<String, Group>();
205 PreparedStatement ps = null;
209 conn = getConnection();
210 // Get the user role names
211 if (logger.isDebugEnabled()) {
212 logger.debug("Executing query: " + rolesQuery + ", with username: " + username);
215 ps = conn.prepareStatement(rolesQuery);
217 ps.setString(1, username);
218 } catch (ArrayIndexOutOfBoundsException ignore) {
219 // The query may not have any parameters so just try it
221 rs = ps.executeQuery();
222 if (rs.next() == false) {
223 if (logger.isDebugEnabled()) {
224 logger.debug("No roles found");
226 // if(aslm.getUnauthenticatedIdentity() == null){
227 // throw new FailedLoginException("No matching username found in Roles");
229 /* We are running with an unauthenticatedIdentity so create an
230 empty Roles set and return.
233 Group g = createGroup(groupClassName, "Roles");
234 groupsMap.put(g.getName(), g);
235 return groupsMap.values();
239 String roleName = rs.getString(1);
240 String groupName = rs.getString(2);
241 if (groupName == null || groupName.length() == 0) {
245 Group group = (Group) groupsMap.get(groupName);
247 group = createGroup(groupClassName, groupName);
248 groupsMap.put(groupName, group);
252 Principal p = createPrincipal(principalClassName, roleName);
253 if (logger.isDebugEnabled()) {
254 logger.debug("Assign user to role " + roleName);
258 } catch (Exception e) {
259 logger.error("Failed to create principal: " + roleName + " " + e.toString());
263 } catch (SQLException ex) {
264 LoginException le = new LoginException("Query failed");
267 } catch (Exception e) {
268 LoginException le = new LoginException("unknown exception");
275 } catch (SQLException e) {
281 } catch (SQLException e) {
287 } catch (Exception ex) {
293 return groupsMap.values();
297 public Collection<Group> getTenants(String username, String groupClassName) throws LoginException {
298 return getTenants(username, groupClassName, false);
302 * Execute the tenantsQuery against the datasourceName to obtain the tenants for
303 * the authenticated user.
304 * @return collection containing the roles
307 public Collection<Group> getTenants(String username, String groupClassName, boolean includeDisabledTenants) throws LoginException {
309 String tenantsQuery = getTenantQuery(includeDisabledTenants);
311 if (logger.isDebugEnabled()) {
312 logger.debug("getTenants using tenantsQuery: " + tenantsQuery + ", username: " + username);
315 Connection conn = null;
316 HashMap<String, Group> groupsMap = new HashMap<String, Group>();
317 PreparedStatement ps = null;
321 conn = getConnection();
323 ps = conn.prepareStatement(tenantsQuery);
325 ps.setString(1, username);
326 } catch (ArrayIndexOutOfBoundsException ignore) {
327 // The query may not have any parameters so just try it
329 rs = ps.executeQuery();
330 if (rs.next() == false) {
331 if (logger.isDebugEnabled()) {
332 logger.debug("No tenants found");
334 // We are running with an unauthenticatedIdentity so create an
335 // empty Tenants set and return.
336 // FIXME should this be allowed?
337 Group g = createGroup(groupClassName, "Tenants");
338 groupsMap.put(g.getName(), g);
339 return groupsMap.values();
343 String tenantId = rs.getString(1);
344 String tenantName = rs.getString(2);
345 String groupName = rs.getString(3);
346 if (groupName == null || groupName.length() == 0) {
347 groupName = "Tenants";
350 Group group = (Group) groupsMap.get(groupName);
352 group = createGroup(groupClassName, groupName);
353 groupsMap.put(groupName, group);
357 Principal p = createTenant(tenantName, tenantId);
358 if (logger.isDebugEnabled()) {
359 logger.debug("Assign user to tenant " + tenantName);
363 } catch (Exception e) {
364 logger.error("Failed to create tenant: " + tenantName + " " + e.toString());
367 } catch (SQLException ex) {
368 LoginException le = new LoginException("Query failed");
371 } catch (Exception e) {
372 LoginException le = new LoginException("unknown exception");
379 } catch (SQLException e) {
385 } catch (SQLException e) {
391 } catch (Exception ex) {
397 return groupsMap.values();
400 private CSpaceTenant createTenant(String name, String id) throws Exception {
401 return new CSpaceTenant(name, id);
404 private Group createGroup(String groupClassName, String name) throws Exception {
405 return (Group) createPrincipal(groupClassName, name);
408 private Principal createPrincipal(String principalClassName, String name) throws Exception {
409 ClassLoader loader = Thread.currentThread().getContextClassLoader();
410 Class clazz = loader.loadClass(principalClassName);
411 Class[] ctorSig = {String.class};
412 Constructor ctor = clazz.getConstructor(ctorSig);
413 Object[] ctorArgs = {name};
414 Principal p = (Principal) ctor.newInstance(ctorArgs);
418 private Connection getConnection() throws LoginException, SQLException {
419 InitialContext ctx = null;
420 Connection conn = null;
421 String dataSourceName = getDataSourceName();
422 DataSource ds = null;
424 ctx = new InitialContext();
426 ds = (DataSource) ctx.lookup(dataSourceName);
427 } catch (Exception e) {}
430 Context envCtx = (Context) ctx.lookup("java:comp/env");
431 ds = (DataSource) envCtx.lookup(dataSourceName);
432 } catch (Exception e) {}
435 Context envCtx = (Context) ctx.lookup("java:comp");
436 ds = (DataSource) envCtx.lookup(dataSourceName);
437 } catch (Exception e) {}
440 Context envCtx = (Context) ctx.lookup("java:");
441 ds = (DataSource) envCtx.lookup(dataSourceName);
442 } catch (Exception e) {}
445 Context envCtx = (Context) ctx.lookup("java");
446 ds = (DataSource) envCtx.lookup(dataSourceName);
447 } catch (Exception e) {}
450 ds = (DataSource) ctx.lookup("java:/" + dataSourceName);
451 } catch (Exception e) {}
454 ds = AuthN.getDataSource();
458 throw new IllegalArgumentException("datasource not found: " + dataSourceName);
461 conn = ds.getConnection();
463 conn = AuthN.getDataSource().getConnection(); //FIXME:REM - This is the result of some type of JNDI mess. Should try to solve this problem and clean up this code.
466 } catch (NamingException ex) {
467 LoginException le = new LoginException("Error looking up DataSource from: " + dataSourceName);
474 } catch (Exception e) {
483 * @return the datasourceName
485 public String getDataSourceName() {
486 return datasourceName;
490 * @return the principalQuery
492 public String getPrincipalQuery() {
493 return principalsQuery;
497 * @param principalQuery the principalQuery to set
499 public void setPrincipalQuery(String principalQuery) {
500 this.principalsQuery = principalQuery;
504 * @return the roleQuery
506 public String getRoleQuery() {
511 * @param roleQuery the roleQuery to set
513 public void setRoleQuery(String roleQuery) {
514 this.rolesQuery = roleQuery;
518 * @return the tenantQuery
520 public String getTenantQuery(boolean includeDisabledTenants) {
521 return includeDisabledTenants?tenantsQueryWithDisabled:tenantsQueryNoDisabled;
525 * @param tenantQuery the tenantQuery to set
526 public void setTenantQuery(String tenantQuery) {
527 this.tenantsQueryNoDisabled = tenantQuery;