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 tenantsQuery;
92 private boolean suspendResume;
95 * CSpace Database Realm
96 * @param datasourceName datasource name
98 public CSpaceDbRealm(Map options) {
99 datasourceName = (String) options.get("dsJndiName");
100 if (datasourceName == null) {
101 datasourceName = "java:/DefaultDS";
103 Object tmp = options.get("principalsQuery");
105 principalsQuery = tmp.toString();
107 tmp = options.get("rolesQuery");
109 rolesQuery = tmp.toString();
111 tmp = options.get("tenantsQuery");
113 tenantsQuery = tmp.toString();
115 tmp = options.get("suspendResume");
117 suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
119 if (logger.isTraceEnabled()) {
120 logger.trace("DatabaseServerLoginModule, dsJndiName=" + datasourceName);
121 logger.trace("principalsQuery=" + principalsQuery);
122 logger.trace("rolesQuery=" + rolesQuery);
123 logger.trace("suspendResume=" + suspendResume);
129 public String getUsersPassword(String username) throws LoginException {
131 String password = null;
132 Connection conn = null;
133 PreparedStatement ps = null;
136 conn = getConnection();
138 if (logger.isDebugEnabled()) {
139 logger.debug("Executing query: " + principalsQuery + ", with username: " + username);
141 ps = conn.prepareStatement(principalsQuery);
142 ps.setString(1, username);
143 rs = ps.executeQuery();
144 if (rs.next() == false) {
145 if (logger.isDebugEnabled()) {
146 logger.debug(principalsQuery + " returned no matches from db");
148 throw new FailedLoginException("No matching username found");
151 password = rs.getString(1);
152 } catch (SQLException ex) {
153 LoginException le = new LoginException("Query failed");
156 } catch (Exception ex) {
157 LoginException le = new LoginException("Unknown Exception");
164 } catch (SQLException e) {
170 } catch (SQLException e) {
176 } catch (SQLException ex) {
184 * Execute the rolesQuery against the datasourceName to obtain the roles for
185 * the authenticated user.
186 * @return collection containing the roles
189 public Collection<Group> getRoles(String username, String principalClassName, String groupClassName) throws LoginException {
191 if (logger.isDebugEnabled()) {
192 logger.debug("getRoleSets using rolesQuery: " + rolesQuery + ", username: " + username);
195 Connection conn = null;
196 HashMap<String, Group> groupsMap = new HashMap<String, Group>();
197 PreparedStatement ps = null;
201 conn = getConnection();
202 // Get the user role names
203 if (logger.isDebugEnabled()) {
204 logger.debug("Executing query: " + rolesQuery + ", with username: " + username);
207 ps = conn.prepareStatement(rolesQuery);
209 ps.setString(1, username);
210 } catch (ArrayIndexOutOfBoundsException ignore) {
211 // The query may not have any parameters so just try it
213 rs = ps.executeQuery();
214 if (rs.next() == false) {
215 if (logger.isDebugEnabled()) {
216 logger.debug("No roles found");
218 // if(aslm.getUnauthenticatedIdentity() == null){
219 // throw new FailedLoginException("No matching username found in Roles");
221 /* We are running with an unauthenticatedIdentity so create an
222 empty Roles set and return.
225 Group g = createGroup(groupClassName, "Roles");
226 groupsMap.put(g.getName(), g);
227 return groupsMap.values();
231 String roleName = rs.getString(1);
232 String groupName = rs.getString(2);
233 if (groupName == null || groupName.length() == 0) {
237 Group group = (Group) groupsMap.get(groupName);
239 group = createGroup(groupClassName, groupName);
240 groupsMap.put(groupName, group);
244 Principal p = createPrincipal(principalClassName, roleName);
245 if (logger.isDebugEnabled()) {
246 logger.debug("Assign user to role " + roleName);
250 } catch (Exception e) {
251 logger.error("Failed to create principal: " + roleName + " " + e.toString());
255 } catch (SQLException ex) {
256 LoginException le = new LoginException("Query failed");
259 } catch (Exception e) {
260 LoginException le = new LoginException("unknown exception");
267 } catch (SQLException e) {
273 } catch (SQLException e) {
279 } catch (Exception ex) {
285 return groupsMap.values();
290 * Execute the tenantsQuery against the datasourceName to obtain the tenants for
291 * the authenticated user.
292 * @return collection containing the roles
295 public Collection<Group> getTenants(String username, String groupClassName) throws LoginException {
297 if (logger.isDebugEnabled()) {
298 logger.debug("getTenants using tenantsQuery: " + tenantsQuery + ", username: " + username);
301 Connection conn = null;
302 HashMap<String, Group> groupsMap = new HashMap<String, Group>();
303 PreparedStatement ps = null;
307 conn = getConnection();
308 // Get the user role names
309 if (logger.isDebugEnabled()) {
310 logger.debug("Executing query: " + tenantsQuery + ", with username: " + username);
313 ps = conn.prepareStatement(tenantsQuery);
315 ps.setString(1, username);
316 } catch (ArrayIndexOutOfBoundsException ignore) {
317 // The query may not have any parameters so just try it
319 rs = ps.executeQuery();
320 if (rs.next() == false) {
321 if (logger.isDebugEnabled()) {
322 logger.debug("No tenants found");
324 // We are running with an unauthenticatedIdentity so create an
325 // empty Tenants set and return.
326 // FIXME should this be allowed?
327 Group g = createGroup(groupClassName, "Tenants");
328 groupsMap.put(g.getName(), g);
329 return groupsMap.values();
333 String tenantId = rs.getString(1);
334 String tenantName = rs.getString(2);
335 String groupName = rs.getString(3);
336 if (groupName == null || groupName.length() == 0) {
337 groupName = "Tenants";
340 Group group = (Group) groupsMap.get(groupName);
342 group = createGroup(groupClassName, groupName);
343 groupsMap.put(groupName, group);
347 Principal p = createTenant(tenantName, tenantId);
348 if (logger.isDebugEnabled()) {
349 logger.debug("Assign user to tenant " + tenantName);
353 } catch (Exception e) {
354 logger.error("Failed to create tenant: " + tenantName + " " + e.toString());
357 } catch (SQLException ex) {
358 LoginException le = new LoginException("Query failed");
361 } catch (Exception e) {
362 LoginException le = new LoginException("unknown exception");
369 } catch (SQLException e) {
375 } catch (SQLException e) {
381 } catch (Exception ex) {
387 return groupsMap.values();
390 private CSpaceTenant createTenant(String name, String id) throws Exception {
391 return new CSpaceTenant(name, id);
394 private Group createGroup(String groupClassName, String name) throws Exception {
395 return (Group) createPrincipal(groupClassName, name);
398 private Principal createPrincipal(String principalClassName, String name) throws Exception {
399 ClassLoader loader = Thread.currentThread().getContextClassLoader();
400 Class clazz = loader.loadClass(principalClassName);
401 Class[] ctorSig = {String.class};
402 Constructor ctor = clazz.getConstructor(ctorSig);
403 Object[] ctorArgs = {name};
404 Principal p = (Principal) ctor.newInstance(ctorArgs);
408 private Connection getConnection() throws LoginException, SQLException {
409 InitialContext ctx = null;
410 Connection conn = null;
411 String dataSourceName = getDataSourceName();
412 DataSource ds = null;
414 ctx = new InitialContext();
416 ds = (DataSource) ctx.lookup(dataSourceName);
417 } catch (Exception e) {}
420 Context envCtx = (Context) ctx.lookup("java:comp/env");
421 ds = (DataSource) envCtx.lookup(dataSourceName);
422 } catch (Exception e) {}
425 Context envCtx = (Context) ctx.lookup("java:comp");
426 ds = (DataSource) envCtx.lookup(dataSourceName);
427 } catch (Exception e) {}
430 Context envCtx = (Context) ctx.lookup("java:");
431 ds = (DataSource) envCtx.lookup(dataSourceName);
432 } catch (Exception e) {}
435 Context envCtx = (Context) ctx.lookup("java");
436 ds = (DataSource) envCtx.lookup(dataSourceName);
437 } catch (Exception e) {}
440 ds = (DataSource) ctx.lookup("java:/" + dataSourceName);
441 } catch (Exception e) {}
444 ds = AuthN.getDataSource();
448 throw new IllegalArgumentException("datasource not found: " + dataSourceName);
451 conn = ds.getConnection();
453 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.
456 } catch (NamingException ex) {
457 LoginException le = new LoginException("Error looking up DataSource from: " + dataSourceName);
464 } catch (Exception e) {
473 * @return the datasourceName
475 public String getDataSourceName() {
476 return datasourceName;
480 * @return the principalQuery
482 public String getPrincipalQuery() {
483 return principalsQuery;
487 * @param principalQuery the principalQuery to set
489 public void setPrincipalQuery(String principalQuery) {
490 this.principalsQuery = principalQuery;
494 * @return the roleQuery
496 public String getRoleQuery() {
501 * @param roleQuery the roleQuery to set
503 public void setRoleQuery(String roleQuery) {
504 this.rolesQuery = roleQuery;
508 * @return the tenantQuery
510 public String getTenantQuery() {
515 * @param tenantQuery the tenantQuery to set
517 public void setTenantQuery(String tenantQuery) {
518 this.tenantsQuery = tenantQuery;