Project

General

Profile

Download (13 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

    
10
package eu.etaxonomy.cdm.api.service;
11

    
12

    
13
import java.io.FileNotFoundException;
14
import java.util.ArrayList;
15
import java.util.List;
16
import java.util.Set;
17

    
18
import org.apache.log4j.Logger;
19
import org.junit.Assert;
20
import org.junit.Test;
21
import org.springframework.security.access.AccessDeniedException;
22
import org.springframework.security.authentication.AuthenticationManager;
23
import org.springframework.security.core.Authentication;
24
import org.springframework.security.core.GrantedAuthority;
25
import org.springframework.security.core.context.SecurityContext;
26
import org.springframework.security.core.context.SecurityContextHolder;
27
import org.unitils.dbunit.annotation.DataSet;
28
import org.unitils.spring.annotation.SpringBeanByType;
29

    
30
import eu.etaxonomy.cdm.database.PermissionDeniedException;
31
import eu.etaxonomy.cdm.model.permission.GrantedAuthorityImpl;
32
import eu.etaxonomy.cdm.model.permission.Group;
33
import eu.etaxonomy.cdm.model.permission.User;
34
import eu.etaxonomy.cdm.persistence.permission.Role;
35

    
36

    
37
/**
38
 * @author a.kohlbecker
39
 * @since Feb 4, 2014
40
 */
41
@DataSet(value="SecurityTest.xml")
42
public class UserAndGroupServiceImplTest extends AbstractSecurityTestBase {
43

    
44
    protected static final Logger logger = Logger.getLogger(UserAndGroupServiceImplTest.class);
45

    
46
    @SpringBeanByType
47
    private AuthenticationManager authenticationManager;
48

    
49
    @SpringBeanByType
50
    private IUserService userService;
51

    
52
    @SpringBeanByType
53
    private IGroupService groupService;
54

    
55
    @SpringBeanByType
56
    private IGrantedAuthorityService grantedAuthorityService;
57

    
58
    @SpringBeanByType
59
    private ITaxonService taxonService;
60

    
61
    private Authentication authentication;
62

    
63
    @Test
64
    public void testCreateUser() {
65

    
66
        authentication = authenticationManager.authenticate(tokenForAdmin);
67
        SecurityContext context = SecurityContextHolder.getContext();
68
        context.setAuthentication(authentication);
69

    
70
        try{
71
            userService.createUser(User.NewInstance("new_user_1", "00000"));
72
        }catch(Exception e){
73
            Assert.fail();
74
        }
75

    
76
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
77
        context = SecurityContextHolder.getContext();
78
        context.setAuthentication(authentication);
79

    
80
        try{
81
            userService.createUser(User.NewInstance("new_user_2", "00000"));
82
            Assert.fail();
83
        }catch(Exception e){
84
            Assert.assertEquals("Access is denied", e.getMessage());
85
        }
86
    }
87

    
88
    @Test
89
    public void testUpdateUser(){
90

    
91
        // TaxonEditor should be able to change its own email address
92
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
93
        SecurityContext context = SecurityContextHolder.getContext();
94
        context.setAuthentication(authentication);
95

    
96
        User user= userService.find(TAXON_EDITOR_UUID);
97
        user.setEmailAddress("test@bgbm.org");
98

    
99
        /* FIXME
100
        try{
101
            userService.updateUser(user);
102
        }catch (Exception e){
103
            Assert.fail("the user TaxonEditor should be able to change its own email address");
104
        }
105
        */
106

    
107
        authentication = authenticationManager.authenticate(tokenForUserManager);
108
        context = SecurityContextHolder.getContext();
109
        context.setAuthentication(authentication);
110

    
111
        user.setEmailAddress("user@bgbm.org");
112

    
113
        try{
114
            userService.updateUser(user);
115
        }catch (Exception e){
116
            Assert.fail("the user UserManager should be able to change others email addresses");
117
        }
118

    
119
        authentication = authenticationManager.authenticate(tokenForPartEditor);
120
        context = SecurityContextHolder.getContext();
121
        context.setAuthentication(authentication);
122

    
123
        try{
124
            userService.updateUser(user);
125
            Assert.fail("the user PartEditor should NOT be able to change others email addresses");
126
        }catch (Exception e){
127
            Assert.assertEquals("Access is denied", e.getMessage());
128
        }
129
    }
130

    
131
    @Test
132
    public void testChangePassword(){
133

    
134
        // the user TaxonEditor should be able to change its own password
135
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
136
        SecurityContext context = SecurityContextHolder.getContext();
137
        context.setAuthentication(authentication);
138

    
139
        userService.changePasswordForUser(tokenForTaxonEditor.getName(), "newPassword");
140

    
141
        Exception exception = null;
142
        // the user TaxonEditor should NOT be able to change others passwords
143
        try{
144
            userService.changePasswordForUser(tokenForAdmin.getName(), "newPassword");
145
            commitAndStartNewTransaction(null);
146
        } catch (AccessDeniedException e){
147
            logger.debug("Expected failure of evaluation.", e);
148
            exception  = e;
149
        } catch (RuntimeException e){
150
            exception = findThrowableOfTypeIn(PermissionDeniedException.class, e);
151
            logger.debug("Expected failure of evaluation.", exception);
152
        } finally {
153
            // needed in case saveOrUpdate was interrupted by the RuntimeException
154
            // commitAndStartNewTransaction() would raise an UnexpectedRollbackException
155
            endTransaction();
156
            startNewTransaction();
157
        }
158
        Assert.assertNotNull("must fail here!", exception);
159

    
160
        // the user User manager should be able to change others passwords
161
        authentication = authenticationManager.authenticate(tokenForUserManager);
162
        context = SecurityContextHolder.getContext();
163
        context.setAuthentication(authentication);
164
        userService.changePasswordForUser(tokenForAdmin.getName(), "newPassword");
165
    }
166

    
167
    @Test
168
    public void testCreateGroup(){
169

    
170
        authentication = authenticationManager.authenticate(tokenForUserManager);
171
        SecurityContext context = SecurityContextHolder.getContext();
172
        context.setAuthentication(authentication);
173

    
174
        List<GrantedAuthority> authorityList = new ArrayList<>();
175
        GrantedAuthorityImpl roleRemotingAuthority = GrantedAuthorityImpl.NewInstance(null);
176
        roleRemotingAuthority.setAuthority(Role.ROLE_REMOTING.toString()); // testing if creating a Role from string is working
177
        authorityList.add(roleRemotingAuthority);
178

    
179
        String remotingGroupName = "publishers";
180

    
181
        groupService.createGroup(remotingGroupName, authorityList);
182

    
183
        commitAndStartNewTransaction(null);
184

    
185
        List<GrantedAuthority> groupAuthorities = groupService.findGroupAuthorities(remotingGroupName);
186

    
187
        Assert.assertEquals(Role.ROLE_REMOTING.toString(), groupAuthorities.get(0).getAuthority());
188
    }
189

    
190
    @Test
191
    public void testRefreshUser(){
192

    
193
        String newGroupName = "new_publishers";
194

    
195
        // -----------------------------------------------------------------
196
        // authenticate as TaxonEditor to load the user for the first time and to let cache it in the session
197
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
198
        SecurityContext context = SecurityContextHolder.getContext();
199
        context.setAuthentication(authentication);
200

    
201
        User user = (User) authentication.getPrincipal();
202

    
203
        // check that everything is clean
204
        for(GrantedAuthority authority : user.getAuthorities()){
205
            if(authority.equals(Role.ROLE_PUBLISH)){
206
                Assert.fail("an authority '" + Role.ROLE_PUBLISH + "' must not yet exists");
207
            }
208
        }
209
        for(Group group : user.getGroups()){
210
            if(group.getName().equals(newGroupName)){
211
                Assert.fail("the group '" + newGroupName + "' must not yet exists");
212
            }
213
        }
214

    
215
        // -----------------------------------------------------------------
216
        // authenticate as UserManager to be able to add the role ROLE_PUBLISH in various ways
217
        authentication = authenticationManager.authenticate(tokenForUserManager);
218
        context = SecurityContextHolder.getContext();
219
        context.setAuthentication(authentication);
220

    
221
        // create an entity of ROLE_PUBLISH and save it to the database
222
        commitAndStartNewTransaction(null);
223
        GrantedAuthorityImpl rolePublish = grantedAuthorityService.load(Role.ROLE_PUBLISH.getUuid());
224

    
225
        user = userService.load(TAXON_EDITOR_UUID);
226

    
227
        // 1. add to the users GrantedAuthorities
228
        // TODO is there any other way to do this?
229
        Set<GrantedAuthority> grantedAuthorities = user.getGrantedAuthorities();
230
        grantedAuthorities.add(rolePublish);
231
        user.setGrantedAuthorities(grantedAuthorities);
232
        userService.saveOrUpdate(user);
233

    
234
        commitAndStartNewTransaction(null);
235

    
236
        // 2. add to existing group
237
        Group group_special_editor = groupService.load(GROUP_SPECIAL_EDITOR_UUID);
238
        String groupSpecialEditor_Name = group_special_editor.getName();
239
        rolePublish = grantedAuthorityService.load(Role.ROLE_PUBLISH.getUuid());
240
        group_special_editor.addGrantedAuthority(rolePublish);
241
        groupService.saveOrUpdate(group_special_editor);
242

    
243
        commitAndStartNewTransaction(null);
244

    
245
        // 3. add in new group
246
        Group groupNewPublishers = Group.NewInstance(newGroupName);
247
        rolePublish = grantedAuthorityService.load(Role.ROLE_PUBLISH.getUuid());
248
        groupNewPublishers.addGrantedAuthority(rolePublish);
249
        groupService.saveOrUpdate(groupNewPublishers);
250
        groupService.addUserToGroup(user.getUsername(), newGroupName);
251

    
252
        commitAndStartNewTransaction(null);
253

    
254
        // -----------------------------------------------------------------
255
        // again authenticate as TaxonEditor
256
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
257
        context = SecurityContextHolder.getContext();
258
        context.setAuthentication(authentication);
259

    
260
        // and check if everything is updated
261
        user = (User) authentication.getPrincipal();
262

    
263
        // 1. check users authorities for the role
264
        boolean newAuthorityFound = false;
265
        for(GrantedAuthority authority : user.getAuthorities()){
266
            if(authority.equals(Role.ROLE_PUBLISH)){
267
                newAuthorityFound = true;
268
                break;
269
            }
270
        }
271
        Assert.assertTrue("the new authority '" + Role.ROLE_PUBLISH + "' is missing", newAuthorityFound);
272

    
273
        // 2. check for role in existing group
274
        boolean newAuthorityFoundInExistingGroup = false;
275
        for(Group group : user.getGroups()){
276
            if(group.getUuid().equals(GROUP_SPECIAL_EDITOR_UUID)){
277
                for(GrantedAuthority authority : group.getGrantedAuthorities()){
278
                    if(authority.equals(Role.ROLE_PUBLISH)){
279
                        newAuthorityFoundInExistingGroup = true;
280
                        break;
281
                    }
282
                }
283
                if(newAuthorityFoundInExistingGroup){
284
                    break;
285
                }
286
            }
287
        }
288
        Assert.assertTrue("the new authority '" + Role.ROLE_PUBLISH + "' is missing in existing group", newAuthorityFoundInExistingGroup);
289

    
290
        // 3. check new group
291
        boolean newGroupFound = false;
292
        for(Group group : user.getGroups()){
293
            if(group.getName().equals(newGroupName)){
294
                newGroupFound = true;
295
                break;
296
            }
297
        }
298
        Assert.assertTrue("the new group '" + newGroupName + "' is missing", newGroupFound);
299

    
300
        // ==================================================================
301
        // again authenticate as UserManager to be able to add the role ROLE_PUBLISH in various ways
302
        authentication = authenticationManager.authenticate(tokenForUserManager);
303
        context = SecurityContextHolder.getContext();
304
        context.setAuthentication(authentication);
305

    
306
        groupService.removeUserFromGroup(user.getUsername(), groupSpecialEditor_Name);
307

    
308
        commitAndStartNewTransaction(null);
309

    
310
        // -----------------------------------------------------------------
311
        // again authenticate as TaxonEditor
312
        authentication = authenticationManager.authenticate(tokenForTaxonEditor);
313
        context = SecurityContextHolder.getContext();
314
        context.setAuthentication(authentication);
315

    
316
        // and check if the group has been removed from the user
317
        user = (User) authentication.getPrincipal();
318

    
319
        for(Group group: user.getGroups()){
320
            if(group.getName().equals(groupSpecialEditor_Name)){
321
                Assert.fail("The user TaxonEditor should no longer be member of this group");
322
            }
323
        }
324
    }
325

    
326
    @Override
327
    public void createTestDataSet() throws FileNotFoundException {}
328

    
329
}
(39-39/40)