Commit f9b30825 authored by Matija Obreza's avatar Matija Obreza

/api/v1/permission controller imported

parent 7f8db3ed
/**
* Copyright 2014 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys2.server.api.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import java.io.IOException;
import java.util.Set;
public class UserSerializer extends JsonSerializer<User> {
@Override
public void serialize(User user, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonProcessingException {
if (user == null) {
jgen.writeNull();
} else {
jgen.writeStartObject();
jgen.writeObjectField("uuid", user.getUuid());
jgen.writeObjectField("name", user.getFullName());
jgen.writeObjectField("email", user.getEmail());
final Set<UserRole> roles = user.getRoles();
if (roles != null) {
jgen.writeArrayFieldStart("roles");
for (final UserRole role : roles) {
jgen.writeObject(role);
}
jgen.writeEndArray();
}
jgen.writeEndObject();
}
}
}
/*
* Copyright 2018 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys2.server.api.v1;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.genesys.blocks.model.JsonViews;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.service.OAuthClientDetailsService;
import org.genesys.blocks.security.model.AclObjectIdentity;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.security.serialization.SidPermissions;
import org.genesys.blocks.security.service.CustomAclService;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonView;
/**
* The Class PermissionController.
*
* @author Andrey Lugovskoy
* @author Matija Obreza
*/
@RestController("permissionControllerV1")
@RequestMapping(value = { "/api/v1/permission" })
public class PermissionController {
private static final Logger LOG = LoggerFactory.getLogger(PermissionController.class);
/** The acl service. */
@Autowired
protected CustomAclService aclService;
@Autowired
private UserService userService;
@Autowired
private OAuthClientDetailsService clientDetailsService;
/**
* Adds the permission.
*
* @param className the class name
* @param id the id
* @param sidPermissions the sid permissions
* @return the acl object identity
*/
@Transactional
@PostMapping(value = "/permissions/{clazz}/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(JsonViews.Minimal.class)
public AclObjectIdentity addPermission(@PathVariable(value = "clazz") final String className, @PathVariable("id") final long id,
@RequestBody final SidPermissions sidPermissions) {
final AclObjectIdentity objectIdentity = aclService.ensureObjectIdentity(id, className);
LOG.info("Setting permissions {}", sidPermissions);
final AclSid sid = aclService.getSid(sidPermissions.sid.getId());
return lazyLoadForJson(aclService.setPermissions(objectIdentity, sid, sidPermissions));
}
/**
* Return all information related to the AclAwareModel.
*
* @param className the class name
* @param id the id
* @return the acl object identity
*/
@Transactional(readOnly = true)
@GetMapping(value = "/permissions/{clazz}/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(JsonViews.Minimal.class)
public AclObjectIdentity permissions(@PathVariable(value = "clazz") final String className, @PathVariable("id") final long id) {
final AclObjectIdentity objectIdentity = aclService.getObjectIdentity(id, className);
return lazyLoadForJson(objectIdentity);
}
/**
* Lazy load for json.
*
* @param objectIdentity the object identity
* @return the acl object identity
*/
protected AclObjectIdentity lazyLoadForJson(final AclObjectIdentity objectIdentity) {
if (objectIdentity != null && objectIdentity.getAclEntries() != null) {
objectIdentity.getAclEntries().size();
// lazy load for JSON
objectIdentity.getAclEntries().forEach(entry -> entry.getAclSid().getId());
}
return objectIdentity;
}
/**
* Return all information for {@link AclObjectIdentity} by its id.
*
* @param id the internal ID of aclObjectIdentity
* @return the acl object identity
*/
@GetMapping(value = "/permissions/{aclObjectIdentityId}", produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(JsonViews.Minimal.class)
public AclObjectIdentity permissions(@PathVariable(value = "aclObjectIdentityId") final long id) {
final AclObjectIdentity objectIdentity = aclService.getObjectIdentity(id);
return lazyLoadForJson(objectIdentity);
}
/**
* Auto-complete users, roles and clients.
*
* @param term the search term
* @return Map of SID labels and SID IDs
* @since 1.6
*/
@GetMapping(value = "/autocomplete", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Long> acSid(@RequestParam("term") final String term) {
final Map<String, Long> sidIds = new HashMap<>();
sidIds.putAll(acRole(term));
sidIds.putAll(acUser(term));
sidIds.putAll(acOauthClient(term));
return sidIds;
}
/**
* Ac user.
*
* @param term the term
* @return the map
* @deprecated Will be deprecated in 1.7
*/
@Deprecated
// TODO remove
@GetMapping(value = "/autocompleteuser", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Long> acUser(@RequestParam("term") final String term) {
final Map<String, Long> userIds = new HashMap<>();
for (final User user : userService.autocompleteUser(term, 10)) {
userIds.put(user.getEmail(), user.getId());
}
return userIds;
}
/**
* Ac role.
*
* @param term the term
* @return the map
* @deprecated Will be deprecated in 1.7
*/
@Deprecated
// TODO remove
@GetMapping(value = "/autocompleterole", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Long> acRole(@RequestParam("term") final String term) {
final Map<String, Long> roleSids = new HashMap<>();
final List<UserRole> matchingRoles = Arrays.stream(UserRole.values()).filter(role -> role.name().toLowerCase().startsWith(term.toLowerCase())).collect(Collectors.toList());
for (final UserRole role : matchingRoles) {
roleSids.put(role.name(), aclService.getAuthoritySid(role.getAuthority()).getId());
}
return roleSids;
}
/**
* Ac oauth client.
*
* @param term the term
* @return the map
* @deprecated Will be deprecated in 1.7
*/
@Deprecated
// TODO remove
@GetMapping(value = "/autocomplete-oauth-client", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Long> acOauthClient(@RequestParam("term") final String term) {
final Map<String, Long> oauthMap = new HashMap<>();
for (final OAuthClient client : clientDetailsService.autocompleteClients(term, 10)) {
oauthMap.put(client.getTitle(), client.getId());
}
return oauthMap;
}
}
......@@ -24,17 +24,14 @@ import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.genesys.blocks.security.model.BasicUser;
import org.genesys2.server.api.serialization.UserSerializer;
import org.genesys2.server.model.UserRole;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Cacheable
@Entity
@Table(name = "\"user\"")
@JsonSerialize(using = UserSerializer.class)
@DiscriminatorValue(value = "1")
public class User extends BasicUser<UserRole> {
......
......@@ -35,4 +35,14 @@ public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.email like ?1 and u.accountType != 'SYSTEM'")
List<User> autocompleteByEmail(String email, Pageable pageable);
/**
* Autocomplete user by email or fullName
*
* @param term the search term
* @param page the page request
* @return the list
*/
@Query("select u from User u where lower(u.email) like concat(lower(?1), '%') or lower(u.fullName) like concat(lower(?1), '%')")
List<User> autocomplete(String term, Pageable page);
}
/**
* Copyright 2014 Global Crop Diversity Trust
/*
* Copyright 2018 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
......@@ -12,7 +12,7 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
*/
package org.genesys2.server.service;
......@@ -81,4 +81,13 @@ public interface UserService extends BasicUserService<UserRole, User> {
*/
void archiveUser(User user) throws UserException;
/**
* Autocomplete user.
*
* @param email the email
* @param limit the limit
* @return the list of users
*/
List<User> autocompleteUser(String email, int limit);
}
......@@ -372,7 +372,6 @@ public class UserServiceImpl extends BasicUserServiceImpl<UserRole, User> implem
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@PreAuthorize("isAuthenticated()")
@Override
public List<User> autocompleteUser(String email) {
if (StringUtils.isBlank(email) || email.length() < 4)
......@@ -380,6 +379,16 @@ public class UserServiceImpl extends BasicUserServiceImpl<UserRole, User> implem
return userRepository.autocompleteByEmail(email + "%", new PageRequest(0, 10, new Sort("email")));
}
@Override
@PreAuthorize("isAuthenticated()")
public List<User> autocompleteUser(final String email, final int limit) {
if (StringUtils.isBlank(email) || email.length() < 1) {
return Collections.emptyList();
}
return userRepository.autocomplete(email, new PageRequest(0, Integer.min(100, limit), new Sort("email")));
}
@Override
@Transactional
public User setAccountType(User user, AccountType accountType) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment