1 21 22 package com.jaspersoft.jasperserver.api.metadata.user.service.impl; 23 24 import java.util.ArrayList ; 25 import java.util.Collection ; 26 import java.util.HashSet ; 27 import java.util.Iterator ; 28 import java.util.List ; 29 import java.util.Set ; 30 31 import org.acegisecurity.GrantedAuthority; 32 import org.acegisecurity.context.SecurityContextHolder; 33 import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; 34 import org.acegisecurity.userdetails.UserDetails; 35 import org.acegisecurity.userdetails.UserDetailsService; 36 import org.acegisecurity.userdetails.UsernameNotFoundException; 37 import org.apache.commons.collections.CollectionUtils; 38 import org.apache.commons.collections.Predicate; 39 import org.apache.commons.logging.Log; 40 import org.apache.commons.logging.LogFactory; 41 import org.hibernate.criterion.DetachedCriteria; 42 import org.hibernate.criterion.Restrictions; 43 import org.springframework.dao.DataAccessException; 44 45 import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext; 46 import com.jaspersoft.jasperserver.api.common.domain.impl.ExecutionContextImpl; 47 import com.jaspersoft.jasperserver.api.metadata.common.service.ResourceFactory; 48 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.HibernateDaoImpl; 49 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.PersistentObjectResolver; 50 import com.jaspersoft.jasperserver.api.metadata.user.domain.Role; 51 import com.jaspersoft.jasperserver.api.metadata.user.domain.User; 52 import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.client.MetadataUserDetails; 53 import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.hibernate.RepoRole; 54 import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.hibernate.RepoUser; 55 import com.jaspersoft.jasperserver.api.metadata.view.domain.FilterCriteria; 56 57 61 public class UserAuthorityServiceImpl extends HibernateDaoImpl implements UserDetailsService, ExternalUserService, PersistentObjectResolver { 62 63 protected static final Log log = LogFactory.getLog(UserAuthorityServiceImpl.class); 64 private ResourceFactory objectFactory; 65 private ResourceFactory persistentClassFactory; 66 67 private List defaultInternalRoles; 68 69 public ResourceFactory getObjectMappingFactory() { 70 return objectFactory; 71 } 72 73 public void setObjectMappingFactory(ResourceFactory objectFactory) { 74 this.objectFactory = objectFactory; 75 } 76 77 public ResourceFactory getPersistentClassFactory() { 78 return persistentClassFactory; 79 } 80 81 public void setPersistentClassFactory(ResourceFactory persistentClassFactory) { 82 this.persistentClassFactory = persistentClassFactory; 83 } 84 85 protected RepoUser getRepoUser(ExecutionContext context, String username) { 86 DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClassFactory().getImplementationClass(User.class)); 87 criteria.add(Restrictions.eq("username", username)); 88 List userList = getHibernateTemplate().findByCriteria(criteria); 89 RepoUser user = null; 90 if (userList.isEmpty()) { 91 log.debug("User not found with username \"" + username + "\""); 92 } else { 93 user = (RepoUser) userList.get(0); 94 } 95 return user; 96 } 97 98 101 public User getUser(ExecutionContext context, String username) { 102 RepoUser user = getRepoUser(context, username); 103 User userDTO = null; 104 if (user != null) { 105 userDTO = (User) user.toClient(getObjectMappingFactory()); 106 } else { 107 log.debug("No such user as: " + username); 108 } 109 return userDTO; 110 } 111 112 protected RepoUser getRepoUser(ExecutionContext context, Long id) { 113 RepoUser user = (RepoUser) getHibernateTemplate().load(getPersistentClassFactory().getImplementationClass(User.class), id); 114 return user; 115 } 116 117 120 protected User getUser(ExecutionContext context, Long id) { 121 RepoUser user = getRepoUser(context, id); 122 User userDTO = null; 123 if (user != null) { 124 userDTO = (User) user.toClient(getObjectMappingFactory()); 125 } 126 return userDTO; 127 } 128 129 132 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { 133 User u = getUser(null, username); 134 135 if (u == null) { 136 throw new UsernameNotFoundException("User not found with username \"" + username + "\""); 137 } else { 138 return new MetadataUserDetails(u); 139 } 140 } 141 142 145 public void putUser(ExecutionContext context, User aUser) { 146 RepoUser existingUser = getRepoUser(context, aUser.getUsername()); 147 if (existingUser == null) { 148 existingUser = (RepoUser) getPersistentClassFactory().newObject(User.class); 149 } 150 existingUser.copyFromClient(aUser, this); 151 getHibernateTemplate().saveOrUpdate(existingUser); 152 } 153 154 160 public List getUsers(ExecutionContext context, FilterCriteria filterCriteria) { 161 List results = getHibernateTemplate().loadAll(getPersistentClassFactory().getImplementationClass(User.class)); 163 List userDTOs = null; 164 165 if (results != null) { 166 userDTOs = new ArrayList (results.size()); 167 Iterator it = results.iterator(); 168 while (it.hasNext()) { 169 RepoUser u = (RepoUser) it.next(); 170 User newUser = (User) u.toClient(getObjectMappingFactory()); 171 userDTOs.add(newUser); 172 } 173 } 174 return userDTOs; 175 } 176 177 183 public User newUser(ExecutionContext context) { 184 return (User) getObjectMappingFactory().newObject(User.class); 185 } 186 187 190 protected boolean disableUser(ExecutionContext context, Long id) { 191 RepoUser user = getRepoUser(context, id); 192 if (user != null && user.isEnabled()) { 193 user.setEnabled(false); 194 return true; 195 } else { 196 return false; 197 } 198 } 199 200 203 public boolean disableUser(ExecutionContext context, String username) { 204 RepoUser user = getRepoUser(context, username); 205 if (user != null && user.isEnabled()) { 206 user.setEnabled(false); 207 return true; 208 } else { 209 return false; 210 } 211 } 212 213 216 protected boolean enableUser(ExecutionContext context, Long id) { 217 RepoUser user = getRepoUser(context, id); 218 if (user != null && !user.isEnabled()) { 219 user.setEnabled(true); 220 return true; 221 } else { 222 return false; 223 } 224 } 225 226 229 public boolean enableUser(ExecutionContext context, String username) { 230 RepoUser user = getRepoUser(context, username); 231 if (user != null && !user.isEnabled()) { 232 user.setEnabled(true); 233 return true; 234 } else { 235 return false; 236 } 237 } 238 239 public void deleteUser (ExecutionContext context, String username) { 240 RepoUser user = getRepoUser(context, username); 241 if (user == null) { 242 return; 243 } 244 removeAllRoles(context, (User) user); 245 246 248 getHibernateTemplate().delete(user); 249 } 250 251 public void addRole(ExecutionContext context, User user, Role role) { 252 if (user == null) { 253 return; 254 } 255 256 RepoUser existingUser = getRepoUser(context, user.getUsername()); 257 if (existingUser != null) { 258 existingUser.addRole(role); 259 putUser(null, existingUser); 260 } 261 user.addRole(role); 262 } 263 264 265 public void removeRole(ExecutionContext context, User user, Role role) { 266 if (user == null) { 267 return; 268 } 269 270 RepoUser existingUser = getRepoUser(context, user.getUsername()); 271 if (existingUser != null) { 272 existingUser.removeRole(role); 273 putUser(null, existingUser); 274 } 275 user.removeRole(role); 276 } 277 278 public void removeAllRoles(ExecutionContext context, User user) { 279 if (user == null) { 280 return; 281 } 282 283 RepoUser existingUser = getRepoUser(context, user.getUsername()); 284 if (existingUser == null) { 285 return; 286 } 287 288 295 296 existingUser.getRoles().clear(); putUser(null, existingUser); 298 299 } 300 301 304 public Role getRole(ExecutionContext context, String roleName) { 305 DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClassFactory().getImplementationClass(Role.class)); 306 criteria.add(Restrictions.eq("roleName", roleName)); 307 List roleList = getHibernateTemplate().findByCriteria(criteria); 308 Role role = null; 309 if (roleList.isEmpty()) { 310 log.debug("Role not found with role name \"" + roleName + "\""); 311 } else { 312 RepoRole repoRole = (RepoRole) roleList.get(0); 313 role = (Role) repoRole.toClient((ResourceFactory) getObjectMappingFactory()); 314 } 315 return role; 316 } 317 318 321 protected RepoRole getRepoRole(ExecutionContext context, String roleName) { 322 DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClassFactory().getImplementationClass(Role.class)); 324 criteria.add(Restrictions.eq("roleName", roleName)); 325 List userList = getHibernateTemplate().findByCriteria(criteria); 326 RepoRole role = null; 327 if (userList.isEmpty()) { 328 log.debug("Role not found with role name \"" + roleName + "\""); 329 } else { 330 role = (RepoRole) userList.get(0); 331 } 332 return role; 333 } 334 335 338 public void putRole(ExecutionContext context, Role aRole) { 339 RepoRole existingRole = getRepoRole(context, aRole.getRoleName()); 340 log.debug("putRole: " + aRole.getRoleName() + ", " + existingRole); 341 if (existingRole == null) { 342 existingRole = (RepoRole) getPersistentClassFactory().newObject(Role.class); 343 log.debug("New Object"); 344 } 345 existingRole.copyFromClient(aRole, this); 346 getHibernateTemplate().saveOrUpdate(existingRole); 347 348 Set repoUsers = existingRole.getUsers(); 349 for (Iterator it = repoUsers.iterator(); it.hasNext();) { 350 RepoUser repoUser = (RepoUser) it.next(); 351 repoUser.getRoles().remove(getPersistentObject(aRole)); 352 } 353 354 Set users = aRole.getUsers(); 355 for (Iterator it = users.iterator(); it.hasNext();) { 356 User user = (User) it.next(); 357 addRole(context, user, aRole); 358 } 359 360 } 361 362 368 public List getRoles(ExecutionContext context, FilterCriteria filterCriteria) { 369 List results = getHibernateTemplate().loadAll(getPersistentClassFactory().getImplementationClass(Role.class)); 370 List roleDTOs = null; 371 372 if (results != null) { 373 roleDTOs = new ArrayList (results.size()); 374 Iterator it = results.iterator(); 375 while (it.hasNext()) { 376 RepoRole r = (RepoRole) it.next(); 377 Role newRole = (Role) r.toClient((ResourceFactory) getObjectMappingFactory()); 378 roleDTOs.add(newRole); 379 } 380 } 381 return roleDTOs; 382 } 383 384 387 public Role newRole(ExecutionContext context) { 388 return (Role) getObjectMappingFactory().newObject(Role.class); 390 } 391 392 public void deleteRole(ExecutionContext context, String roleName) { 393 RepoRole role = getRepoRole(context, roleName); 394 if (role == null) { 395 return; 396 } 397 398 400 DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClassFactory().getImplementationClass(User.class)); 401 criteria.createAlias("roles", "r") 402 .add( Restrictions.eq("r.roleName", roleName) ); 403 List userList = getHibernateTemplate().findByCriteria(criteria); 404 405 for (Iterator it = userList.iterator(); it.hasNext(); ) { 406 RepoUser u = (RepoUser) it.next(); 407 u.removeRole(role); 408 } 409 410 413 getHibernateTemplate().delete(role); 415 } 416 417 public List getUsersNotInRole(ExecutionContext context, String roleName) 418 { 419 List allUsers = getUsers(context, null); 420 List usersInRole = getUsersInRole(context, roleName); 421 allUsers.removeAll(usersInRole); 422 423 return allUsers; 424 } 425 426 public List getUsersInRole(ExecutionContext context, String roleName) 427 { 428 RepoRole repoRole = getRepoRole(context, roleName); 429 Set repoUsers = repoRole.getUsers(); 430 List users = new ArrayList (); 431 432 for (Iterator it = repoUsers.iterator(); it.hasNext();) 433 { 434 RepoUser repoUser = (RepoUser) it.next(); 435 User user = (User) repoUser.toClient(getObjectMappingFactory()); 436 users.add(user); 437 } 438 439 return users; 440 } 441 442 443 450 public Object getPersistentObject(Object clientObject) { 451 if (clientObject instanceof Role) { 452 Role r = (Role) clientObject; 453 return getRepoRole(null, r.getRoleName()); 454 } else if (clientObject instanceof User) { 455 User u = (User) clientObject; 456 return getRepoUser(null, u.getUsername()); 457 } 458 return null; 459 } 460 461 466 public void maintainInternalUser(UserDetails externalUserDetails) { 467 468 log.debug("External user: " + externalUserDetails.getUsername()); 469 470 User user = getUser(new ExecutionContextImpl(), externalUserDetails.getUsername()); 471 472 if (user == null) { 473 user = createNewExternalUser(externalUserDetails); 474 } 475 476 alignInternalAndExternalUser(externalUserDetails, user); 477 478 } 479 486 private User createNewExternalUser(UserDetails userDetails) { 487 User user = newUser(new ExecutionContextImpl()); 488 user.setUsername(userDetails.getUsername()); 489 user.setFullName(userDetails.getUsername()); user.setExternallyDefined(true); 493 user.setEnabled(true); 494 log.warn("Created new external user: " + user.getUsername()); 495 return user; 496 } 497 498 506 private void alignInternalAndExternalUser(UserDetails userDetails, User user) { 507 508 Set externalRoles = getRolesFromUserDetails(userDetails); 509 510 final Predicate externallyDefinedRoles = new Predicate() { 511 public boolean evaluate(Object input) { 512 if (!(input instanceof Role)) { 513 return false; 514 } 515 return ((Role) input).isExternallyDefined(); 516 } 517 }; 518 519 Set currentRoles = user.getRoles(); 520 521 boolean persistUserNeeded = (currentRoles.size() == 0); 523 Collection currentExternalRoles = CollectionUtils.select(user.getRoles(), externallyDefinedRoles); 531 if (log.isDebugEnabled()) { 532 log.debug("Login of external User: " + userDetails.getUsername() ); 533 log.debug("Roles from authentication:\n" + roleCollectionToString(externalRoles)); 534 log.debug("Current roles from metadata:\n" + roleCollectionToString(user.getRoles())); 535 log.debug("Current external roles for user from metadata: " + user.getUsername() + "\n" + roleCollectionToString(currentExternalRoles)); 536 } 537 538 541 Collection newExternalRoles = CollectionUtils.subtract(externalRoles, currentExternalRoles); 542 543 if (newExternalRoles.size() > 0) { 544 currentRoles.addAll(newExternalRoles); 545 if (log.isWarnEnabled()) { 546 log.warn("Added following external roles to: " + user.getUsername() + "\n" + roleCollectionToString(newExternalRoles)); 547 } 548 persistUserNeeded = true; 549 } 550 551 554 Collection rolesNeedingRemoval = CollectionUtils.subtract(currentExternalRoles, externalRoles); 555 556 if (rolesNeedingRemoval.size() > 0) { 557 currentRoles.removeAll(rolesNeedingRemoval); 558 if (log.isWarnEnabled()) { 559 log.warn("Removed following external roles from: " + user.getUsername() + "\n" + roleCollectionToString(rolesNeedingRemoval)); 560 } 561 persistUserNeeded = true; 562 } 563 564 567 Collection defaultInternalRolesToAdd = CollectionUtils.subtract(getNewDefaultInternalRoles(), currentRoles); 568 569 if (defaultInternalRolesToAdd.size() > 0) { 570 if (log.isDebugEnabled()) { 571 log.debug("Default internal roles: " + roleCollectionToString(getNewDefaultInternalRoles())); 572 } 573 currentRoles.addAll(defaultInternalRolesToAdd); 574 if (log.isWarnEnabled()) { 575 log.warn("Added following new default internal roles to: " + user.getUsername() + "\n" + roleCollectionToString(defaultInternalRolesToAdd)); 576 } 577 persistUserNeeded = true; 578 } 579 580 if (persistUserNeeded) { 581 if (log.isWarnEnabled()) { 582 log.warn("Updated user: " + user.getUsername() + ". Roles are now:\n" + roleCollectionToString(currentRoles)); 583 } 584 user.setRoles(currentRoles); 585 putUser(new ExecutionContextImpl(), user); 587 if (log.isWarnEnabled()) { 588 log.warn("Updated user: " + user.getUsername() + ". Roles are now:\n" + roleCollectionToString(currentRoles)); 589 } 590 } 591 592 } 593 594 private String roleCollectionToString(Collection coll) { 595 Iterator it = coll.iterator(); 596 StringBuffer rolesPrint = new StringBuffer (); 597 while (it.hasNext()) { 598 String s = ((Role) it.next()).getRoleName(); 599 rolesPrint.append(s).append("\n"); 600 } 601 return rolesPrint.toString(); 602 } 603 604 611 private Set getRolesFromUserDetails(UserDetails ud) { 612 Set set = new HashSet (); 613 614 GrantedAuthority[] authorities = ud.getAuthorities(); 615 616 if (authorities == null || authorities.length == 0) 617 return set; 618 619 for (int i = 0; i < authorities.length; i++) { 620 GrantedAuthority auth = authorities[i]; 621 622 String authorityName = auth.getAuthority(); 623 624 626 authorityName = authorityName.replace(' ', '_'); 627 628 set.add(getOrCreateRole(authorityName, true)); 629 } 630 return set; 631 } 632 633 639 private Set getNewDefaultInternalRoles() { 640 Set set = new HashSet (); 641 642 if (getDefaultInternalRoles() == null || getDefaultInternalRoles().size() == 0) 643 return set; 644 645 for (int i = 0; i < getDefaultInternalRoles().size(); i++) { 646 String roleName = (String ) getDefaultInternalRoles().get(i); 647 648 set.add(getOrCreateRole(roleName, false)); 649 } 650 return set; 651 } 652 653 private Role getOrCreateRole(String roleName, boolean externallyDefined) { 654 Role r = getRole(new ExecutionContextImpl(), roleName); 655 if (r == null) { 656 r = newRole(new ExecutionContextImpl()); 657 r.setRoleName(roleName); 658 r.setExternallyDefined(externallyDefined); 659 putRole(new ExecutionContextImpl(), r); 660 log.warn("Created new " + (externallyDefined ? "external" : "internal") + " role: " + roleName); 661 } 662 663 return r; 664 } 665 666 public void makeUserLoggedIn(String username) { 667 668 try { 669 671 UserDetails ourUserDetails = loadUserByUsername(username); 672 673 675 if (ourUserDetails.getAuthorities().length != 0) { 676 UsernamePasswordAuthenticationToken ourAuthentication = new UsernamePasswordAuthenticationToken(ourUserDetails, 677 ourUserDetails.getPassword(), ourUserDetails.getAuthorities()); 678 679 if (log.isDebugEnabled()) { 680 log.debug("Setting Authentication to: " + ourAuthentication); 681 } 682 SecurityContextHolder.getContext().setAuthentication(ourAuthentication); 683 } else { 684 685 SecurityContextHolder.getContext().setAuthentication(null); 689 } 690 } catch (UsernameNotFoundException e) { 691 log.warn("User: " + username + " was not found to make them logged in"); 692 } 693 } 694 695 698 public List getDefaultInternalRoles() { 699 return defaultInternalRoles; 700 } 701 702 705 public void setDefaultInternalRoles(List defaultInternalRoles) { 706 this.defaultInternalRoles = defaultInternalRoles; 707 } 708 709 } 710 | Popular Tags |