| 1 |
|
package org.trails.hibernate; |
| 2 |
|
|
| 3 |
|
import java.io.Serializable; |
| 4 |
|
|
| 5 |
|
import org.acegisecurity.GrantedAuthority; |
| 6 |
|
import org.acegisecurity.context.SecurityContext; |
| 7 |
|
import org.acegisecurity.context.SecurityContextHolder; |
| 8 |
|
import org.hibernate.criterion.DetachedCriteria; |
| 9 |
|
import org.hibernate.criterion.Restrictions; |
| 10 |
|
import org.hibernate.criterion.SimpleExpression; |
| 11 |
|
import org.trails.security.EntityModificationInterception; |
| 12 |
|
import org.trails.security.annotation.ViewRequiresAssociation; |
| 13 |
|
import org.trails.security.annotation.ViewRequiresRole; |
| 14 |
|
|
| 15 |
9 |
public class SecurePersistenceServiceImpl extends HibernatePersistenceServiceImpl { |
| 16 |
|
@Override |
| 17 |
|
protected DetachedCriteria alterCriteria(Class type, DetachedCriteria criteria) { |
| 18 |
42 |
SecurityContext context = SecurityContextHolder.getContext(); |
| 19 |
|
|
| 20 |
|
|
| 21 |
42 |
if (context == null || context.getAuthentication() == null) return criteria; |
| 22 |
|
|
| 23 |
|
|
| 24 |
5 |
ViewRequiresRole viewRoleRestriction = (ViewRequiresRole)type.getAnnotation(ViewRequiresRole.class ); |
| 25 |
8 |
if (viewRoleRestriction != null) for (GrantedAuthority authority : context.getAuthentication().getAuthorities()) |
| 26 |
5 |
for (String role : viewRoleRestriction.value()) if (authority.getAuthority().equals(role) ) return criteria; |
| 27 |
|
|
| 28 |
3 |
ViewRequiresAssociation viewRestriction = (ViewRequiresAssociation)type.getAnnotation(ViewRequiresAssociation.class ); |
| 29 |
|
|
| 30 |
3 |
if (viewRoleRestriction == null && viewRestriction == null) return criteria; |
| 31 |
|
|
| 32 |
3 |
if (viewRestriction == null) { |
| 33 |
|
|
| 34 |
|
|
| 35 |
|
|
| 36 |
|
|
| 37 |
|
|
| 38 |
|
|
| 39 |
|
|
| 40 |
|
|
| 41 |
|
|
| 42 |
|
|
| 43 |
|
|
| 44 |
1 |
return criteria.add(Restrictions.idEq(null) ); |
| 45 |
|
} |
| 46 |
|
|
| 47 |
2 |
String currentUsername = context.getAuthentication().getName(); |
| 48 |
2 |
String ownerPropertyAssociation = viewRestriction.value(); |
| 49 |
|
|
| 50 |
2 |
SimpleExpression usernameRestriction = Restrictions.eq("username",currentUsername); |
| 51 |
2 |
if ("".equals(ownerPropertyAssociation)) criteria.add(usernameRestriction); |
| 52 |
0 |
else criteria.createCriteria(ownerPropertyAssociation).add(usernameRestriction); |
| 53 |
2 |
return criteria; |
| 54 |
|
} |
| 55 |
|
|
| 56 |
|
public <T> T loadInstance(final Class<T> type, Serializable id) |
| 57 |
|
{ |
| 58 |
0 |
return getInstance(type, id); |
| 59 |
|
} |
| 60 |
|
|
| 61 |
|
} |