use of org.hisp.dhis.user.UserService in project dhis2-core by dhis2.
the class DhisConvenienceTest method createUserAndInjectSecurityContext.
/**
* Creates a user and injects into the security context with username
* "username". Requires <code>identifiableObjectManager</code> and
* <code>userService</code> to be injected into the test.
*
* @param organisationUnits the organisation units of the user.
* @param dataViewOrganisationUnits user's data view organisation units.
* @param allAuth whether to grant the ALL authority.
* @param auths authorities to grant to user.
* @return the user.
*/
protected User createUserAndInjectSecurityContext(Set<OrganisationUnit> organisationUnits, Set<OrganisationUnit> dataViewOrganisationUnits, boolean allAuth, String... auths) {
Assert.notNull(userService, "UserService must be injected in test");
Set<String> authorities = new HashSet<>();
if (allAuth) {
authorities.add(UserAuthorityGroup.AUTHORITY_ALL);
}
if (auths != null) {
authorities.addAll(Lists.newArrayList(auths));
}
UserAuthorityGroup userAuthorityGroup = new UserAuthorityGroup();
userAuthorityGroup.setName("Superuser");
userAuthorityGroup.getAuthorities().addAll(authorities);
userService.addUserAuthorityGroup(userAuthorityGroup);
User user = createUser('A');
if (organisationUnits != null) {
user.setOrganisationUnits(organisationUnits);
}
if (dataViewOrganisationUnits != null) {
user.setDataViewOrganisationUnits(dataViewOrganisationUnits);
}
user.getUserCredentials().getUserAuthorityGroups().add(userAuthorityGroup);
userService.addUser(user);
user.getUserCredentials().setUserInfo(user);
userService.addUserCredentials(user.getUserCredentials());
Set<GrantedAuthority> grantedAuths = authorities.stream().map(a -> new SimpleGrantedAuthority(a)).collect(Collectors.toSet());
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuths);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "", grantedAuths);
SecurityContextHolder.getContext().setAuthentication(authentication);
return user;
}
Aggregations