Project

General

Profile

Download (8.89 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.persistence.hibernate.permission;
10

    
11
import java.io.Serializable;
12
import java.lang.reflect.Constructor;
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.Collection;
15
import java.util.EnumSet;
16
import java.util.HashSet;
17

    
18
import org.apache.log4j.Logger;
19
import org.springframework.security.access.AccessDecisionManager;
20
import org.springframework.security.access.AccessDeniedException;
21
import org.springframework.security.access.ConfigAttribute;
22
import org.springframework.security.authentication.InsufficientAuthenticationException;
23
import org.springframework.security.core.Authentication;
24
import org.springframework.security.core.GrantedAuthority;
25
import org.springframework.stereotype.Component;
26

    
27
import eu.etaxonomy.cdm.model.common.CdmBase;
28

    
29
/**
30
 * @author k.luther
31
 * @author a.kohlbecker
32
 * @since 06.07.2011
33
 */
34
@Component
35
public class CdmPermissionEvaluator implements ICdmPermissionEvaluator {
36

    
37
    protected static final Logger logger = Logger.getLogger(CdmPermissionEvaluator.class);
38

    
39
    private AccessDecisionManager accessDecisionManager;
40

    
41
    public AccessDecisionManager getAccessDecisionManager() {
42
        return accessDecisionManager;
43
    }
44

    
45
    public CdmPermissionEvaluator() {
46

    
47
    }
48

    
49
    public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager) {
50
        this.accessDecisionManager = accessDecisionManager;
51
    }
52

    
53
    @Override
54
    public boolean hasPermission(Authentication authentication,
55
            Serializable targetId, String targetType, Object permission) {
56
        logger.warn("UNINMPLEMENTED: hasPermission always returns false");
57
        // TODO Auto-generated method stub
58
        return false;
59
    }
60

    
61
    @Override
62
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
63

    
64

    
65
        EnumSet<CRUD> requiredOperation = null;
66

    
67
        TargetEntityStates cdmEntitiyStates;
68
        if(targetDomainObject instanceof CdmBase){
69
            cdmEntitiyStates = new TargetEntityStates((CdmBase)targetDomainObject);
70
        } else {
71
            cdmEntitiyStates = (TargetEntityStates)targetDomainObject;
72
        }
73

    
74
        if(logger.isDebugEnabled()){
75
            String targteDomainObjText = "  Object: " + (targetDomainObject == null? "null":cdmEntitiyStates.getEntity().instanceToString());
76
            logUserAndRequirement(authentication, permission.toString(), targteDomainObjText);
77
        }
78
        try {
79
            requiredOperation = operationFrom(permission);
80

    
81
        } catch (IllegalArgumentException e) {
82
            logger.debug("permission string '"+ permission.toString() + "' not parsable => true");
83
            return false;
84
        }
85

    
86
        return hasPermission(authentication, cdmEntitiyStates, requiredOperation);
87

    
88
    }
89

    
90
    /**
91
     * @param authentication
92
     * @param targetDomainObject
93
     * @param requiredOperation
94
     * @return
95
     */
96
    @Override
97
    public boolean hasPermission(Authentication authentication, CdmBase targetEntity, EnumSet<CRUD> requiredOperation) {
98
        return hasPermission(authentication, new TargetEntityStates(targetEntity), requiredOperation);
99
    }
100

    
101
    /**
102
     * @param authentication
103
     * @param targetDomainObject
104
     * @param requiredOperation
105
     * @return
106
     */
107
    @Override
108
    public boolean hasPermission(Authentication authentication, TargetEntityStates targetEntityStates, EnumSet<CRUD> requiredOperation) {
109

    
110
        if(authentication == null) {
111
            return false;
112
        }
113

    
114
        CdmAuthority evalPermission = authorityRequiredFor(targetEntityStates.getEntity(), requiredOperation);
115

    
116
        if (evalPermission.getPermissionClass() != null) {
117
            logger.debug("starting evaluation => ...");
118
            return evalPermission(authentication, evalPermission, targetEntityStates);
119
        }else{
120
            logger.debug("skipping evaluation => true");
121
            return true;
122
        }
123
    }
124

    
125

    
126
    @Override
127
    public <T extends CdmBase> boolean hasPermission(Authentication authentication, Class<T> targetDomainObjectClass,
128
            EnumSet<CRUD> requiredOperations) {
129

    
130
        if(authentication == null) {
131
            return false;
132
        }
133

    
134
        if(logger.isDebugEnabled()){
135
            String targteDomainObjClassText = "  Cdm-Type: " + targetDomainObjectClass.getSimpleName();
136
            logUserAndRequirement(authentication, requiredOperations.toString(), targteDomainObjClassText);
137
        }
138

    
139
        CdmAuthority evalPermission = new CdmAuthority(CdmPermissionClass.getValueOf(targetDomainObjectClass), null, requiredOperations, null);
140

    
141
        T instance;
142
        try {
143
            Constructor<T> c = targetDomainObjectClass.getDeclaredConstructor();
144
            c.setAccessible(true);
145
            instance = c.newInstance();
146
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
147
            logger.error("Error while creating permission test instance ==> will deny", e);
148
            return false;
149
        }
150

    
151
        return evalPermission(authentication, evalPermission, new TargetEntityStates(instance));
152
    }
153

    
154
    /**
155
     * @param authentication
156
     * @param permission
157
     * @param targteDomainObjText
158
     */
159
    protected void logUserAndRequirement(Authentication authentication, String permissions, String targteDomainObjText) {
160
        StringBuilder grantedAuthoritiesTxt = new StringBuilder();
161
        for(GrantedAuthority ga : authentication.getAuthorities()){
162
            grantedAuthoritiesTxt.append("    - ").append(ga.getAuthority()).append("\n");
163
        }
164
        if(grantedAuthoritiesTxt.length() == 0){
165
            grantedAuthoritiesTxt.append("    - ").append("<No GrantedAuthority given>").append("\n");
166
        }
167
        logger.debug("hasPermission()\n"
168
                + "  User '" + authentication.getName() + "':\n"
169
                + grantedAuthoritiesTxt
170
                + targteDomainObjText + "\n"
171
                + "  Permission: " + permissions);
172
    }
173

    
174
    /**
175
     * @param permission
176
     * @return
177
     */
178
    protected EnumSet<CRUD> operationFrom(Object permission) {
179
        EnumSet<CRUD> requiredOperation;
180
        // FIXME refactor into Operation ======
181
        if (Operation.isOperation(permission)){
182
            requiredOperation = (EnumSet<CRUD>)permission;
183
        } else {
184
            // try to treat as string
185
            requiredOperation = Operation.fromString(permission.toString());
186
        }
187
        // =======================================
188
        return requiredOperation;
189
    }
190

    
191
    /**
192
     * @param targetEntity
193
     * @param requiredOperation
194
     * @return
195
     */
196
    private CdmAuthority authorityRequiredFor(CdmBase targetEntity, EnumSet<CRUD> requiredOperation) {
197
        CdmAuthority evalPermission = new CdmAuthority(targetEntity, requiredOperation);
198
        return evalPermission;
199
    }
200

    
201

    
202
    /**
203
     * @param authorities
204
     * @param evalPermission
205
     * @param targetDomainObject
206
     * @return
207
     */
208
    private boolean evalPermission(Authentication authentication, CdmAuthority evalPermission, TargetEntityStates targetEntityStates){
209

    
210
        //if user has administrator rights return true;
211
        if( hasOneOfRoles(authentication, Role.ROLE_ADMIN)){
212
            return true;
213
        }
214

    
215
        // === run voters
216
        Collection<ConfigAttribute> attributes = new HashSet<ConfigAttribute>();
217
        attributes.add(evalPermission);
218

    
219
        logger.debug("AccessDecisionManager will decide ...");
220
        try {
221
            accessDecisionManager.decide(authentication, targetEntityStates, attributes);
222
        } catch (InsufficientAuthenticationException e) {
223
            logger.debug("AccessDecisionManager denied by " + e, e);
224
            return false;
225
        } catch (AccessDeniedException e) {
226
            logger.debug("AccessDecisionManager denied by " + e, e);
227
            return false;
228
        }
229

    
230
        return true;
231
    }
232

    
233
    /**
234
     * @param authentication
235
     */
236
    @Override
237
    public boolean hasOneOfRoles(Authentication authentication, Role ... roles) {
238
        for (GrantedAuthority authority: authentication.getAuthorities()){
239
            for(Role role : roles){
240
                 if (role != null && authority.getAuthority().equals(role.getAuthority())){
241
                     if(logger.isDebugEnabled()){
242
                         logger.debug(role.getAuthority() + " found => true");
243
                     }
244
                     return true;
245
                 }
246
            }
247
         }
248
        return false;
249
    }
250

    
251
}
(5-5/11)