Project

General

Profile

Download (9.4 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 sun.security.provider.PolicyParser.ParsingException;
23
import eu.etaxonomy.cdm.model.common.CdmBase;
24
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
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, UUID uuid){
82
        this.permissionClass = CdmPermissionClass.getValueOf(targetDomainObject);
83
        this.property = null;
84
        if(operation != null) {
85
        	this.operation = operation;
86
        }
87
        this.targetUuid = uuid;
88
    }
89

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

    
99

    
100
    public CdmAuthority(CdmPermissionClass permissionClass, String property, EnumSet<CRUD> operation, UUID uuid){
101
        this.permissionClass = permissionClass;
102
        this.property = property;
103
        if(operation != null) {
104
        	this.operation = operation;
105
        }
106
        this.targetUuid = uuid;
107
    }
108

    
109
    private CdmAuthority (String authority) throws ParsingException{
110

    
111
        String[] tokens = parse(authority);
112
        // className must never be null
113

    
114
        try {
115
            permissionClass = CdmPermissionClass.valueOf(tokens[0]);
116
        } catch (IllegalArgumentException e) {
117
            throw new ParsingException(authority);
118
        }
119
        property = tokens[1];
120

    
121
        if(tokens[2] != null){
122
            try {
123
                operation = Operation.fromString(tokens[2]);
124
            } catch (IllegalArgumentException e) {
125
                logger.warn("cannot parse Operation " + tokens[2]);
126
                throw new ParsingException(authority);
127
            }
128
        }
129
        if(tokens[3] != null){
130
            targetUuid = UUID.fromString(tokens[3]);
131
        }
132
    }
133

    
134
    public CdmPermissionClass getPermissionClass(){
135
        return permissionClass;
136
    }
137

    
138
    public String getProperty(){
139
        return property;
140
    }
141

    
142
    public EnumSet<CRUD> getOperation(){
143
        return operation;
144
    }
145

    
146
    public void setOperation(EnumSet<CRUD> operation) {
147
        this.operation = operation;
148
    }
149

    
150
    public UUID getTargetUUID(){
151
        return targetUuid;
152
    }
153

    
154
    public boolean hasTargetUuid() {
155
        return targetUuid != null;
156
    }
157

    
158
    public boolean hasProperty() {
159
        return property != null;
160
    }
161

    
162
    /**
163
     * Parses the given <code>authority</code> and returns an array of tokens.
164
     * The array has a length of four elements whereas the elements can be null.
165
     * The elements in the array correspond to the fields of {@link CdmAuthority}:
166
     * <ol>
167
     * <li>{@link CdmAuthority#permissionClass}</li>
168
     * <li>{@link CdmAuthority#property}</li>
169
     * <li>{@link CdmAuthority#operation}</li>
170
     * <li>{@link CdmAuthority#targetUuid}</li>
171
     * </ol>
172
     * @param authority
173
     * @return an array of tokens
174
     * @throws ParsingException
175
     */
176
    protected String[] parse(String authority) throws ParsingException {
177
        //
178
        // regex pattern explained:
179
        //  (\\w*)             -> classname
180
        //  (?:\\((\\w*)\\))?  -> (property)
181
        //  \\.?               -> .
182
        //  (?:\\[(\\D*)\\])(?:\\{([\\da-z\\-]+)\\})? -> Permission and targetUuid
183
        //
184
        String regex = "(\\w*)(?:\\((\\w*)\\))?\\.?(?:\\[(\\D*)\\])?(?:\\{([\\da-z\\-]+)\\})?";
185
        Pattern pattern = Pattern.compile(regex);
186
        String[] tokens = new String[4];
187
        logger.debug("parsing '" + authority + "'");
188
        Matcher m = pattern.matcher(authority);
189

    
190
        if (m.find() && m.groupCount() == 4 ) {
191
            for (int i = 0; i < m.groupCount(); i++) {
192
                tokens[i] = m.group(i+1);
193
                // normalize empty strings to null
194
                if(tokens[i] != null && tokens[i].length() == 0){
195
                    tokens[i] = null;
196
                }
197
                logger.trace("[" + i + "]: " + tokens[i]+ "\n");
198
            }
199
        } else {
200
            logger.debug("no match");
201
            throw new ParsingException("Unsupported authority string: '" + authority + "'");
202
        }
203

    
204
        return tokens;
205
    }
206

    
207
    /**
208
     * {@inheritDoc}
209
     *
210
     * same as {@link #toString()} and  {@link #getAttribute()}
211
     */
212
    @Override
213
    public String getAuthority() {
214
        return toString();
215
    }
216

    
217
    /**
218
     * {@inheritDoc}
219
     *
220
     * same as {@link #toString()} and  {@link #getAuthority()}
221
     */
222
    @Override
223
    public String getAttribute() {
224
        return toString();
225
    }
226

    
227
    @Override
228
    public String toString() {
229
        StringBuilder sb = new StringBuilder();
230
        sb.append(permissionClass.toString());
231
        if(property != null){
232
            sb.append('(').append(property).append(')');
233
        }
234
        sb.append('.').append(operation.toString());
235
        if(targetUuid != null){
236
            sb.append('{').append(targetUuid.toString()).append('}');
237
        }
238
        return sb.toString() ;
239
    }
240

    
241
    /**
242
     * Constructs a new CdmAuthority by parsing the authority string.
243
     * For details on the syntax please refer to the class
244
     * documentation above.
245
     * <p>
246
     * This method is mainly used by the permission voters ({@link CdmPermissionVoter)}.
247
     * In order to improve the voting process this method is caching the <code>CdmAuthority</code>
248
     * instances per <code>GrantedAuthority</code> string in a map.
249
     *
250
     * @param authority
251
     * @throws ParsingException
252
     */
253
    public static CdmAuthority fromGrantedAuthority(GrantedAuthority authority) throws ParsingException {
254
        CdmAuthority cdmAuthority = grantedAuthorityCache.get(authority.getAuthority());
255
        if(cdmAuthority == null){
256
            cdmAuthority = new CdmAuthority(authority.getAuthority());
257
        }
258
        return cdmAuthority;
259
//        return  new CdmAuthority(authority.getAuthority());
260
    }
261

    
262
    /* (non-Javadoc)
263
     * @see eu.etaxonomy.cdm.persistence.hibernate.permission.IGrantedAuthorityConverter#asNewGrantedAuthority()
264
     */
265
    @Override
266
    public GrantedAuthorityImpl asNewGrantedAuthority() throws ParsingException {
267
        GrantedAuthorityImpl grantedAuthority = GrantedAuthorityImpl.NewInstance();
268
        grantedAuthority.setAuthority(getAuthority());
269
        return grantedAuthority;
270
    }
271

    
272

    
273

    
274
}
(2-2/9)