use of org.eclipse.vorto.repository.domain.User in project vorto by eclipse.
the class ModelRepositoryController method getUserPolicy.
@PreAuthorize("isAuthenticated() or hasAuthority('model_viewer')")
@GetMapping("/{modelId:.+}/policy")
public ResponseEntity<PolicyEntry> getUserPolicy(@PathVariable final String modelId) {
Objects.requireNonNull(modelId, "model ID must not be null");
Authentication user = SecurityContextHolder.getContext().getAuthentication();
ModelId modelID = ModelId.fromPrettyFormat(modelId);
String tenantId = getWorkspaceId(modelId);
try {
List<PolicyEntry> policyEntries = getPolicyManager(tenantId).getPolicyEntries(modelID).stream().filter(p -> userHasPolicyEntry(p, user, tenantId)).collect(Collectors.toList());
return getBestPolicyEntryForUser(policyEntries).map(p -> new ResponseEntity<>(p, HttpStatus.OK)).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
} catch (NotAuthorizedException ex) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
use of org.eclipse.vorto.repository.domain.User in project vorto by eclipse.
the class NamespaceController method createTechnicalUserForNamespace.
/**
* Creates a technical user with the given {@link Collaborator} and associates them to the given
* namespace, with the desired roles held by the collaborator.
*
* @param namespace
* @param collaborator
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/{namespace:.+}/users")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Boolean> createTechnicalUserForNamespace(@ApiParam(value = "namespace", required = true) @PathVariable String namespace, @RequestBody @ApiParam(value = "The user to be associated with the namespace", required = true) final Collaborator collaborator) {
try {
IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
User user = EntityDTOConverter.createUser(userUtil, collaborator);
userNamespaceRoleService.createTechnicalUserAndAddAsCollaborator(userContext.getUsername(), user, namespace, collaborator.getRoles());
return new ResponseEntity<>(true, HttpStatus.CREATED);
} catch (InvalidUserException ie) {
return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
} catch (OperationForbiddenException ofe) {
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
} catch (DoesNotExistException d) {
return new ResponseEntity<>(false, HttpStatus.NOT_FOUND);
}
}
use of org.eclipse.vorto.repository.domain.User in project vorto by eclipse.
the class NamespaceController method findAllAccessibleNamespacesByPartial.
/**
* Finds all namespaces accessible to the authenticated user, by a partial name. <br/>
* This is used in the UI to search for namespaces the user can view, aka all the public ones and
* the private ones the user has at least one role in.
*
* @param partial
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/search/{partial:.+}")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Collection<NamespaceDto>> findAllAccessibleNamespacesByPartial(@ApiParam(value = "The partial name of the namespaces to be searched with", required = true) @PathVariable String partial) {
if (Strings.nullToEmpty(partial).trim().isEmpty()) {
return new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
}
IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
Collection<NamespaceDto> result = namespaceRepository.findNamespaceByPartial(partial.toLowerCase()).stream().filter(n -> {
try {
return // all public namespaces
!n.getName().startsWith(NamespaceValidator.PRIVATE_NAMESPACE_PREFIX) || // or namespaces where user has a role
userNamespaceRoleService.hasAnyRole(userContext.getUsername(), n.getName());
// should never occur here
} catch (DoesNotExistException dnee) {
return false;
}
}).map(EntityDTOConverter::createNamespaceDTO).sorted(Comparator.comparing(NamespaceDto::getName)).collect(Collectors.toList());
return new ResponseEntity<>(result, HttpStatus.OK);
}
use of org.eclipse.vorto.repository.domain.User in project vorto by eclipse.
the class NamespaceController method addOrUpdateCollaboratorForNamespace.
/**
* Sets the roles of the given user on the given namespace.
*
* @param namespace
* @param collaborator
* @return
*/
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.PUT, value = "/{namespace:.+}/users")
public ResponseEntity<Boolean> addOrUpdateCollaboratorForNamespace(@ApiParam(value = "namespace", required = true) @PathVariable String namespace, @RequestBody @ApiParam(value = "The user to be associated with the namespace", required = true) final Collaborator collaborator) {
try {
// no validation here save for essentials: we are pointing to an existing user
User user = EntityDTOConverter.createUser(null, collaborator);
IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
return new ResponseEntity<>(userNamespaceRoleService.setRoles(userContext.getUsername(), user.getUsername(), namespace, collaborator.getRoles(), false), HttpStatus.OK);
} catch (InvalidUserException iue) {
return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
} catch (OperationForbiddenException ofe) {
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
} catch (DoesNotExistException d) {
return new ResponseEntity<>(false, HttpStatus.NOT_FOUND);
}
}
use of org.eclipse.vorto.repository.domain.User in project vorto by eclipse.
the class NamespaceController method requestAccessToNamespace.
@PostMapping("/requestAccess")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<OperationResult> requestAccessToNamespace(@RequestBody @ApiParam(value = "The request body specifying who initiates the request, the namespace, whom the request is intended for, and an optional collection of suggested roles", required = true) NamespaceAccessRequestDTO request) {
Optional<OperationResult> validationError = NamespaceValidator.validateAccessRequest(request);
if (validationError.isPresent()) {
return new ResponseEntity<>(validationError.get(), HttpStatus.BAD_REQUEST);
}
// checks namespace exists
// should only occur if namespace was deleted after user search, but before sending request
Namespace target;
try {
target = namespaceService.getByName(request.getNamespaceName());
} catch (DoesNotExistException dnee) {
return new ResponseEntity<>(OperationResult.failure("Namespace not found."), HttpStatus.NOT_FOUND);
}
// checks any admin with an e-mail address set
Set<User> adminsWithEmail = userNamespaceRoleRepository.findAllByNamespace(target).stream().map(UserNamespaceRoles::getUser).filter(u -> !Strings.nullToEmpty(u.getEmailAddress()).trim().isEmpty()).collect(Collectors.toSet());
if (adminsWithEmail.isEmpty()) {
return new ResponseEntity<>(OperationResult.failure(String.format("None of the users administrating namespace %s has set their own e-mail. Please contact them directly. ", request.getNamespaceName())), HttpStatus.PRECONDITION_FAILED);
}
int successCount = adminsWithEmail.size();
// attempts to send the e-mails
// ugly exception handling here, due to the way this was designed in the service
Collection<IMessage> messages = adminsWithEmail.stream().map(u -> new RequestAccessToNamespaceMessage(request, u, host)).collect(Collectors.toList());
for (IMessage message : messages) {
try {
emailNotificationService.sendNotification(message);
} catch (NotificationProblem np) {
successCount--;
}
}
// worked for all recipients
if (successCount == adminsWithEmail.size()) {
return new ResponseEntity<>(OperationResult.success(), HttpStatus.OK);
} else // worked for some recipients
if (successCount > 0) {
return new ResponseEntity<>(OperationResult.success("The message could not be sent to all administrators."), HttpStatus.OK);
} else // did not work for any recipient
{
return new ResponseEntity<>(OperationResult.failure("The message could not be sent to any administrator."), HttpStatus.SERVICE_UNAVAILABLE);
}
}
Aggregations