Project

General

Profile

Download (10 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2012 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.util.EnumSet;
12
import java.util.HashMap;
13
import java.util.Map;
14
import java.util.UUID;
15
import java.util.regex.Matcher;
16
import java.util.regex.Pattern;
17

    
18
import org.apache.log4j.Logger;
19
import org.springframework.security.access.ConfigAttribute;
20
import org.springframework.security.core.GrantedAuthority;
21

    
22
import eu.etaxonomy.cdm.model.common.CdmBase;
23
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
24
import sun.security.provider.PolicyParser.ParsingException;
25

    
26
/**
27
 * A <code>CdmAuthority</code> consists basically of two parts which are separated
28
 * by a dot character '.'.
29
 *
30
 * <ul>
31
 * <li><code>permissionClass</code>: an {@link CdmPermissionClass} instance with represents a cdm
32
 * type or a part of the cdm type hierarchy. The className is always represented
33
 * as an upper case string.</li>
34
 * <li><code>property</code>: The <code>CdmAuthority</code> only applies to instances
35
 * which satisfy the specified property. Interpretation is up to type specific voters.</li>
36
 * <li><code>operation</code>: A string enclosed in brackets <code>[]</code>
37
 * which specifies one {@link Operation} or
38
 * multiple on that set of cdm types. Multiple {@link Operation} must be comma
39
 * separated.</li>
40
 * <li><code>targetUuid</code>: The <code>operation</code> may be restricted to a specific cdm entity by adding
41
 * the entity uuid to the <code>operation</code>. The uuid string is enclosed in curly brackets '<code>{</code>'
42
 * , '<code>}</code>' and appended to the end of the <code>operation</code>.</li>
43
 * </ul>
44
 *
45
 * <h3>Examples for permissionStrings</h3>
46
 *
47
 * <pre>
48
 * TAXONBASE.[CREATE]
49
 * TAXONBASE.[READ]
50
 * TAXONBASE.[UPDATE]
51
 * TAXONBASE.[DELETE]
52
 * DESCRIPTIONBASE.[UPDATE]
53
 * DESCRIPTIONBASE.[CREATE,UPDATE,DELETE,READ]
54
 * DESCRIPTIONELEMENTBASE(Ecology).[UPDATE]
55
 * TAXONNODE.[UPDATE]{20c8f083-5870-4cbd-bf56-c5b2b98ab6a7}
56
 * </pre>
57
 *
58
 * The method {@link #getPermissionString(String)} parses a full authority and returns  permissionString and
59
 * the {@link CdmAuthority} from the <code>authority</code>.
60
 *
61
 *
62
 * @author k.luther
63
 * @author Andreas Kohlbecker
64
 */
65
public class CdmAuthority implements GrantedAuthority, ConfigAttribute, IGrantedAuthorityConverter {
66

    
67
    private static final long serialVersionUID = 1L;
68

    
69
    public static final Logger logger = Logger.getLogger(CdmAuthority.class);
70

    
71
    private static Map<String, CdmAuthority> grantedAuthorityCache = new HashMap<String, CdmAuthority>();
72

    
73
    CdmPermissionClass permissionClass;
74
    String property;
75
    // Making sure that operation is always initialized, for both
76
    // - the string representation to have a '[]'
77
    // - and the object representation to never be null (with check in constructors)
78
    EnumSet<CRUD> operation = EnumSet.noneOf(CRUD.class);
79
    UUID targetUuid;
80

    
81
    public CdmAuthority(CdmBase targetDomainObject, EnumSet<CRUD> operation){
82
        this.permissionClass = CdmPermissionClass.getValueOf(targetDomainObject);
83
        this.property = null;
84
        if(operation != null) {
85
        	this.operation = operation;
86
        }
87
        if(targetDomainObject.getUuid() == null){
88
            throw new NullPointerException("UUID of targetDomainObject is null. CDM entities need to be saved prior using this function");
89
        }
90
        this.targetUuid = targetDomainObject.getUuid();
91
    }
92

    
93
     public CdmAuthority(CdmBase targetDomainObject, String property, EnumSet<CRUD> operation, UUID uuid){
94
       this.permissionClass = CdmPermissionClass.getValueOf(targetDomainObject);
95
        this.property = property;
96
        if(operation != null) {
97
        	this.operation = operation;
98
        }
99
        this.targetUuid = uuid;
100
    }
101

    
102
     public CdmAuthority(Class<? extends CdmBase> targetDomainType, String property, EnumSet<CRUD> operation, UUID uuid){
103
         this.permissionClass = CdmPermissionClass.getValueOf(targetDomainType);
104
          this.property = property;
105
          if(operation != null) {
106
              this.operation = operation;
107
          }
108
          this.targetUuid = uuid;
109
      }
110

    
111

    
112
    public CdmAuthority(CdmPermissionClass permissionClass, String property, EnumSet<CRUD> operation, UUID uuid){
113
        this.permissionClass = permissionClass;
114
        this.property = property;
115
        if(operation != null) {
116
        	this.operation = operation;
117
        }
118
        this.targetUuid = uuid;
119
    }
120

    
121
    public CdmAuthority(CdmPermissionClass permissionClass, EnumSet<CRUD> operation){
122
        this.permissionClass = permissionClass;
123
        if(operation != null) {
124
            this.operation = operation;
125
        }
126
    }
127

    
128
    private CdmAuthority (String authority) throws ParsingException{
129

    
130
        String[] tokens = parse(authority);
131
        // className must never be null
132

    
133
        try {
134
            permissionClass = CdmPermissionClass.valueOf(tokens[0]);
135
        } catch (IllegalArgumentException e) {
136
            throw new ParsingException(authority);
137
        }
138
        property = tokens[1];
139

    
140
        if(tokens[2] != null){
141
            try {
142
                operation = Operation.fromString(tokens[2]);
143
            } catch (IllegalArgumentException e) {
144
                logger.warn("cannot parse Operation " + tokens[2]);
145
                throw new ParsingException(authority);
146
            }
147
        }
148
        if(tokens[3] != null){
149
            targetUuid = UUID.fromString(tokens[3]);
150
        }
151
    }
152

    
153
    public CdmPermissionClass getPermissionClass(){
154
        return permissionClass;
155
    }
156

    
157
    public String getProperty(){
158
        return property;
159
    }
160

    
161
    public EnumSet<CRUD> getOperation(){
162
        return operation;
163
    }
164

    
165
    public void setOperation(EnumSet<CRUD> operation) {
166
        this.operation = operation;
167
    }
168

    
169
    public UUID getTargetUUID(){
170
        return targetUuid;
171
    }
172

    
173
    public boolean hasTargetUuid() {
174
        return targetUuid != null;
175
    }
176

    
177
    public boolean hasProperty() {
178
        return property != null;
179
    }
180

    
181
    /**
182
     * Parses the given <code>authority</code> and returns an array of tokens.
183
     * The array has a length of four elements whereas the elements can be null.
184
     * The elements in the array correspond to the fields of {@link CdmAuthority}:
185
     * <ol>
186
     * <li>{@link CdmAuthority#permissionClass}</li>
187
     * <li>{@link CdmAuthority#property}</li>
188
     * <li>{@link CdmAuthority#operation}</li>
189
     * <li>{@link CdmAuthority#targetUuid}</li>
190
     * </ol>
191
     * @param authority
192
     * @return an array of tokens
193
     * @throws ParsingException
194
     */
195
    protected String[] parse(String authority) throws ParsingException {
196
        //
197
        // regex pattern explained:
198
        //  (\\w*)             -> classname
199
        //  (?:\\((\\w*)\\))?  -> (property)
200
        //  \\.?               -> .
201
        //  (?:\\[(\\D*)\\])(?:\\{([\\da-z\\-]+)\\})? -> Permission and targetUuid
202
        //
203
        String regex = "(\\w*)(?:\\((\\w*)\\))?\\.?(?:\\[(\\D*)\\])?(?:\\{([\\da-z\\-]+)\\})?";
204
        Pattern pattern = Pattern.compile(regex);
205
        String[] tokens = new String[4];
206
        logger.debug("parsing '" + authority + "'");
207
        Matcher m = pattern.matcher(authority);
208

    
209
        if (m.find() && m.groupCount() == 4 ) {
210
            for (int i = 0; i < m.groupCount(); i++) {
211
                tokens[i] = m.group(i+1);
212
                // normalize empty strings to null
213
                if(tokens[i] != null && tokens[i].length() == 0){
214
                    tokens[i] = null;
215
                }
216
                logger.trace("[" + i + "]: " + tokens[i]+ "\n");
217
            }
218
        } else {
219
            logger.debug("no match");
220
            throw new ParsingException("Unsupported authority string: '" + authority + "'");
221
        }
222

    
223
        return tokens;
224
    }
225

    
226
    /**
227
     * {@inheritDoc}
228
     *
229
     * same as {@link #toString()} and  {@link #getAttribute()}
230
     */
231
    @Override
232
    public String getAuthority() {
233
        return toString();
234
    }
235

    
236
    /**
237
     * {@inheritDoc}
238
     *
239
     * same as {@link #toString()} and  {@link #getAuthority()}
240
     */
241
    @Override
242
    public String getAttribute() {
243
        return toString();
244
    }
245

    
246
    @Override
247
    public String toString() {
248
        StringBuilder sb = new StringBuilder();
249
        sb.append(permissionClass.toString());
250
        if(property != null){
251
            sb.append('(').append(property).append(')');
252
        }
253
        sb.append('.').append(operation.toString());
254
        if(targetUuid != null){
255
            sb.append('{').append(targetUuid.toString()).append('}');
256
        }
257
        return sb.toString() ;
258
    }
259

    
260
    /**
261
     * Constructs a new CdmAuthority by parsing the authority string.
262
     * For details on the syntax please refer to the class
263
     * documentation above.
264
     * <p>
265
     * This method is mainly used by the permission voters ({@link CdmPermissionVoter)}.
266
     * In order to improve the voting process this method is caching the <code>CdmAuthority</code>
267
     * instances per <code>GrantedAuthority</code> string in a map.
268
     *
269
     * @param authority
270
     * @throws ParsingException
271
     */
272
    public static CdmAuthority fromGrantedAuthority(GrantedAuthority authority) throws ParsingException {
273
        CdmAuthority cdmAuthority = grantedAuthorityCache.get(authority.getAuthority());
274
        if(cdmAuthority == null){
275
            cdmAuthority = new CdmAuthority(authority.getAuthority());
276
        }
277
        return cdmAuthority;
278
//        return  new CdmAuthority(authority.getAuthority());
279
    }
280

    
281

    
282
    @Override
283
    public GrantedAuthorityImpl asNewGrantedAuthority() throws ParsingException {
284
        GrantedAuthorityImpl grantedAuthority = GrantedAuthorityImpl.NewInstance(getAuthority());
285
        return grantedAuthority;
286
    }
287

    
288

    
289

    
290
}
(2-2/9)