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 package org.collectionspace.services.authorization.storage;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.UUID;
30 import javax.persistence.EntityExistsException;
31 import javax.persistence.EntityManager;
32 import javax.persistence.EntityManagerFactory;
33 import javax.persistence.NoResultException;
35 import org.collectionspace.services.authorization.perms.ActionType;
36 import org.collectionspace.services.authorization.CSpaceAction;
37 import org.collectionspace.services.authorization.perms.Permission;
38 import org.collectionspace.services.authorization.perms.PermissionAction;
39 import org.collectionspace.services.authorization.perms.PermissionsList;
40 import org.collectionspace.services.client.PermissionClient;
41 import org.collectionspace.services.client.PermissionClient.ActionCompare;
42 import org.collectionspace.services.authorization.URIResourceImpl;
43 import org.collectionspace.services.common.authorization_mgt.AuthorizationStore;
44 import org.collectionspace.services.common.document.BadRequestException;
45 import org.collectionspace.services.common.document.DocumentException;
46 import org.collectionspace.services.common.document.DocumentFilter;
47 import org.collectionspace.services.common.document.DocumentWrapper;
48 import org.collectionspace.services.common.document.JaxbUtils;
49 import org.collectionspace.services.common.security.SecurityUtils;
50 import org.collectionspace.services.common.storage.jpa.JpaDocumentHandler;
51 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Document handler for Permission
59 public class PermissionDocumentHandler
60 extends JpaDocumentHandler<Permission, PermissionsList, Permission, List> {
62 private final Logger logger = LoggerFactory.getLogger(PermissionDocumentHandler.class);
63 private Permission permission;
64 private PermissionsList permissionsList;
66 public CSpaceAction getAction(ActionType action) {
67 if (ActionType.CREATE.name().equals(action.name())) {
68 return CSpaceAction.CREATE;
69 } else if (ActionType.READ.equals(action)) {
70 return CSpaceAction.READ;
71 } else if (ActionType.UPDATE.equals(action)) {
72 return CSpaceAction.UPDATE;
73 } else if (ActionType.DELETE.equals(action)) {
74 return CSpaceAction.DELETE;
75 } else if (ActionType.SEARCH.equals(action)) {
76 return CSpaceAction.SEARCH;
77 } else if (ActionType.ADMIN.equals(action)) {
78 return CSpaceAction.ADMIN;
79 } else if (ActionType.START.equals(action)) {
80 return CSpaceAction.START;
81 } else if (ActionType.STOP.equals(action)) {
82 return CSpaceAction.STOP;
85 // We could not find a match, so we need to throw an exception.
87 throw new IllegalArgumentException("action = " + action.toString());
91 * Add the ACE hashed ID to the permission action so we can map the permission to the Spring Security
94 private void handlePermissionActions(Permission perm) throws DocumentException {
96 // Verify the permission actions. If the action group is missing, create it from the action list and vice versa.
98 ActionCompare compareResult = PermissionClient.validatePermActions(perm);
99 switch (compareResult) {
100 case ACTIONS_MISSING:
101 String msg = "Permission resource encountered with missing action group and action list.";
102 throw new DocumentException(msg);
104 case ACTION_GROUP_EMPTY:
105 String actionGroup = PermissionClient.getActionGroup(perm.getAction());
106 perm.setActionGroup(actionGroup);
109 case ACTION_LIST_EMPTY:
110 List<PermissionAction> actionList = PermissionClient.getActionList(perm.getActionGroup());
111 perm.setAction(actionList);
119 msg = String.format("Permission has mismatching action group and action list. Action group='%s' and Action list = '%s'.",
120 perm.getActionGroup(), PermissionClient.getActionGroup(perm.getAction()));
121 throw new DocumentException(msg);
124 List<PermissionAction> permActions = perm.getAction();
125 for (PermissionAction permAction : permActions) {
126 CSpaceAction action = getAction(permAction.getName());
127 URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), perm.getResourceName(), action);
128 permAction.setObjectIdentity(uriRes.getHashedId().toString());
129 permAction.setObjectIdentityResource(uriRes.getId());
130 //PermissionActionUtil.update(perm, permAction);
134 private Permission findExistingPermission(EntityManager em, Permission perm) {
135 Permission result = null;
136 String tenantId = getServiceContext().getTenantId(); // we need a tenant ID
139 result = (Permission)JpaStorageUtils.getEntityByDualKeys(em,
140 Permission.class.getName(),
141 PermissionStorageConstants.RESOURCE_NAME, perm.getResourceName(),
142 PermissionStorageConstants.ACTION_GROUP, perm.getActionGroup(),
144 } catch (NoResultException e) {
145 if (logger.isTraceEnabled()) {
146 String msg = String.format("Looked for but could not find permission with resource name = '%s', action group = '%s', tenat ID = '%s'.",
147 perm.getResourceName(), perm.getActionGroup(), tenantId);
156 public void handleCreate(DocumentWrapper<Permission> wrapDoc) throws EntityExistsException, DocumentException {
158 // First check to see if an equivalent permission exists
160 Permission permission = wrapDoc.getWrappedObject();
162 EntityManager em = (EntityManager) this.getServiceContext().getProperty(AuthorizationStore.ENTITY_MANAGER_PROP_KEY);
163 Permission existingPermission = findExistingPermission(em, permission);
165 if (existingPermission == null) {
166 String id = UUID.randomUUID().toString();
167 permission.setCsid(id);
168 setTenant(permission);
169 handlePermissionActions(permission);
171 String msg = String.format("Found existing permission with resource name = '%s', action group = '%s', and tenant ID = '%s'.",
172 existingPermission.getResourceName(), existingPermission.getActionGroup(), existingPermission.getTenantId());
173 wrapDoc.resetWrapperObject(existingPermission); // update the wrapped document with the existing permission instance
174 throw new EntityExistsException(msg);
179 public void completeCreate(DocumentWrapper<Permission> wrapDoc) throws Exception {
183 public void handleUpdate(DocumentWrapper<Permission> wrapDoc) throws Exception {
184 Permission permissionFound = wrapDoc.getWrappedObject();
185 Permission permissionReceived = getCommonPart();
186 merge(permissionReceived, permissionFound);
190 * merge manually merges the from from to the to permission
191 * -this method is created due to inefficiency of JPA EM merge
194 * @return merged permission
196 private Permission merge(Permission from, Permission to) throws Exception {
197 if (!(from.getResourceName().equalsIgnoreCase(to.getResourceName()))) {
198 String msg = "Resource name cannot be changed " + to.getResourceName();
200 throw new BadRequestException(msg);
202 //resource name, attribute cannot be changed
204 if (from.getDescription() != null) {
205 to.setDescription(from.getDescription());
207 if (from.getEffect() != null) {
208 to.setEffect(from.getEffect());
210 List<PermissionAction> fromActions = from.getAction();
211 if (!fromActions.isEmpty()) {
212 // Override the whole list, no reconciliation by design
213 to.setAction(fromActions);
214 // Update the actionGroup field to reflect the new action list
215 to.setActionGroup(PermissionClient.getActionGroup(fromActions));
218 if (logger.isDebugEnabled()) {
219 logger.debug("merged permission=" + JaxbUtils.toString(to, Permission.class));
222 handlePermissionActions(to);
227 public void completeUpdate(DocumentWrapper<Permission> wrapDoc) throws Exception {
228 Permission upAcc = wrapDoc.getWrappedObject();
229 getServiceContext().setOutput(upAcc);
231 //FIXME update lower-layer authorization (acls)
232 //will require deleting old permissions for this resource and adding
233 //new based on new actions and effect
237 public void handleGet(DocumentWrapper<Permission> wrapDoc) throws Exception {
238 setCommonPart(extractCommonPart(wrapDoc));
239 sanitize(getCommonPart());
240 getServiceContext().setOutput(permission);
244 public void handleGetAll(DocumentWrapper<List> wrapDoc) throws Exception {
245 PermissionsList permissionsList = extractCommonPartList(wrapDoc);
246 setCommonPartList(permissionsList);
247 getServiceContext().setOutput(getCommonPartList());
251 public void completeDelete(DocumentWrapper<Permission> wrapDoc) throws Exception {
255 public Permission extractCommonPart(
256 DocumentWrapper<Permission> wrapDoc)
258 return wrapDoc.getWrappedObject();
262 public void fillCommonPart(Permission obj, DocumentWrapper<Permission> wrapDoc)
264 throw new UnsupportedOperationException("operation not relevant for AccountDocumentHandler");
268 public PermissionsList extractCommonPartList(
269 DocumentWrapper<List> wrapDoc)
272 PermissionsList permissionsList = new PermissionsList();
273 List<Permission> list = new ArrayList<Permission>();
274 permissionsList.setPermission(list);
275 for (Object obj : wrapDoc.getWrappedObject()) {
276 Permission permission = (Permission) obj;
277 sanitize(permission);
278 list.add(permission);
280 return permissionsList;
284 public Permission getCommonPart() {
289 public void setCommonPart(Permission permission) {
290 this.permission = permission;
294 public PermissionsList getCommonPartList() {
295 return permissionsList;
299 public void setCommonPartList(PermissionsList permissionsList) {
300 this.permissionsList = permissionsList;
304 public String getQProperty(
310 public DocumentFilter createDocumentFilter() {
311 DocumentFilter filter = new PermissionJpaFilter(this.getServiceContext());
316 * Sanitize removes data not needed to be sent to the consumer
319 private void sanitize(Permission permission) {
320 if (!SecurityUtils.isCSpaceAdmin()) {
321 // permission.setTenantId(null); // REM - Why are we removing the tenant ID from the payload? Commenting out this line for now.
325 private void setTenant(Permission permission) {
326 //set tenant only if not available from input
327 if (permission.getTenantId() == null || permission.getTenantId().isEmpty()) {
328 permission.setTenantId(getServiceContext().getTenantId());