use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class DataRetrieverAPI method retrieveMyDataAsJsonString.
/**
* @todo This should support the "X-Dataverse-key" header like the other
* APIs.
*/
@Path(retrieveDataPartialAPIPath)
@GET
@Produces({ "application/json" })
public String retrieveMyDataAsJsonString(@QueryParam("dvobject_types") List<String> dvobject_types, @QueryParam("published_states") List<String> published_states, @QueryParam("selected_page") Integer selectedPage, @QueryParam("mydata_search_term") String searchTerm, @QueryParam("role_ids") List<Long> roleIds, @QueryParam("userIdentifier") String userIdentifier, @QueryParam("key") String apiToken) {
// String myDataParams) {
// System.out.println("_YE_OLDE_QUERY_COUNTER_");
// msgt("_YE_OLDE_QUERY_COUNTER_"); // for debug purposes
boolean DEBUG_MODE = false;
boolean OTHER_USER = false;
// For, superusers, the searchUser may differ from the authUser
//
AuthenticatedUser searchUser = null;
if (DEBUG_MODE == true) {
// DEBUG: use userIdentifier
authUser = getUserFromIdentifier(userIdentifier);
if (authUser == null) {
return this.getJSONErrorString("Requires authentication", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
}
} else if ((session.getUser() != null) && (session.getUser().isAuthenticated())) {
authUser = (AuthenticatedUser) session.getUser();
// and use that instead
if ((authUser.isSuperuser()) && (userIdentifier != null) && (!userIdentifier.isEmpty())) {
searchUser = getUserFromIdentifier(userIdentifier);
if (searchUser != null) {
authUser = searchUser;
OTHER_USER = true;
} else {
return this.getJSONErrorString("No user found for: \"" + userIdentifier + "\"", null);
}
}
} else if (apiToken != null) {
// Is this being accessed by an API Token?
authUser = findUserByApiToken(apiToken);
if (authUser == null) {
return this.getJSONErrorString("Requires authentication. Please login.", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
} else {
// and use that instead
if ((authUser.isSuperuser()) && (userIdentifier != null) && (!userIdentifier.isEmpty())) {
searchUser = getUserFromIdentifier(userIdentifier);
if (searchUser != null) {
authUser = searchUser;
OTHER_USER = true;
} else {
return this.getJSONErrorString("No user found for: \"" + userIdentifier + "\"", null);
}
}
}
} else {
return this.getJSONErrorString("Requires authentication. Please login.", "retrieveMyDataAsJsonString. User not found! Shouldn't be using this anyway");
}
roleList = dataverseRoleService.findAll();
rolePermissionHelper = new DataverseRolePermissionHelper(roleList);
List<String> dtypes;
if (dvobject_types != null) {
dtypes = dvobject_types;
} else {
dtypes = MyDataFilterParams.defaultDvObjectTypes;
}
List<String> pub_states = null;
if (published_states != null) {
pub_states = published_states;
}
// ---------------------------------
// (1) Initialize filterParams and check for Errors
// ---------------------------------
DataverseRequest dataverseRequest = createDataverseRequest(authUser);
MyDataFilterParams filterParams = new MyDataFilterParams(dataverseRequest, dtypes, pub_states, roleIds, searchTerm);
if (filterParams.hasError()) {
return this.getJSONErrorString(filterParams.getErrorMessage(), filterParams.getErrorMessage());
}
// ---------------------------------
// (2) Initialize MyDataFinder and check for Errors
// ---------------------------------
myDataFinder = new MyDataFinder(rolePermissionHelper, roleAssigneeService, dvObjectServiceBean, groupService);
this.myDataFinder.runFindDataSteps(filterParams);
if (myDataFinder.hasError()) {
return this.getJSONErrorString(myDataFinder.getErrorMessage(), myDataFinder.getErrorMessage());
}
// ---------------------------------
// (3) Make Solr Query
// ---------------------------------
int paginationStart = 1;
if (selectedPage != null) {
paginationStart = selectedPage;
}
int solrCardStart = (paginationStart - 1) * SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE;
//
if (searchUser == null) {
searchUser = authUser;
}
// msg("search with user: " + searchUser.getIdentifier());
List<String> filterQueries = this.myDataFinder.getSolrFilterQueries();
if (filterQueries == null) {
logger.fine("No ids found for this search");
return this.getJSONErrorString(DataRetrieverAPI.MSG_NO_RESULTS_FOUND, null);
}
try {
solrQueryResponse = searchService.search(dataverseRequest, // subtree, default it to Dataverse for now
null, // "*", //
filterParams.getSearchTerm(), // filterQueries,
filterQueries, // SearchFields.NAME_SORT, SortBy.ASCENDING,
SearchFields.RELEASE_OR_CREATE_DATE, SortBy.DESCENDING, // paginationStart,
solrCardStart, // dataRelatedToMe
true, // 10 // SearchFields.NUM_SOLR_DOCS_TO_RETRIEVE
SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE);
// msgt("getSolrSearchResults: " + this.solrQueryResponse.getSolrSearchResults().toString());
if (this.solrQueryResponse.getNumResultsFound() == 0) {
return this.getJSONErrorString(DataRetrieverAPI.MSG_NO_RESULTS_FOUND, null);
}
} catch (SearchException ex) {
solrQueryResponse = null;
this.logger.severe("Solr SearchException: " + ex.getMessage());
}
if (solrQueryResponse == null) {
return this.getJSONErrorString("Sorry! There was an error with the search service.", "Sorry! There was a SOLR Error");
}
// ---------------------------------
// (4) Build JSON document including:
// - Pager
// - Formatted solr docs
// - Num results found
// - Search term
// - DvObject counts
// ---------------------------------
// Initialize JSON response
JsonObjectBuilder jsonData = Json.createObjectBuilder();
Pager pager = new Pager(solrQueryResponse.getNumResultsFound().intValue(), SearchConstants.NUM_SOLR_DOCS_TO_RETRIEVE, paginationStart);
RoleTagRetriever roleTagRetriever = new RoleTagRetriever(this.rolePermissionHelper, this.roleAssigneeSvc, this.dvObjectServiceBean);
roleTagRetriever.loadRoles(dataverseRequest, solrQueryResponse);
jsonData.add(DataRetrieverAPI.JSON_SUCCESS_FIELD_NAME, true).add(DataRetrieverAPI.JSON_DATA_FIELD_NAME, Json.createObjectBuilder().add("pagination", pager.asJsonObjectBuilderUsingCardTerms()).add(SearchConstants.SEARCH_API_ITEMS, this.formatSolrDocs(solrQueryResponse, roleTagRetriever)).add(SearchConstants.SEARCH_API_TOTAL_COUNT, solrQueryResponse.getNumResultsFound()).add(SearchConstants.SEARCH_API_START, solrQueryResponse.getResultsStart()).add("search_term", filterParams.getSearchTerm()).add("dvobject_counts", this.getDvObjectTypeCounts(solrQueryResponse)).add("pubstatus_counts", this.getPublicationStatusCounts(solrQueryResponse)).add("selected_filters", this.myDataFinder.getSelectedFilterParamsAsJSON()));
if (OTHER_USER == true) {
jsonData.add("other_user", searchUser.getIdentifier());
}
return jsonData.build().toString();
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class RoleTagRetriever method loadRoles.
public void loadRoles(DataverseRequest dataverseRequest, SolrQueryResponse solrQueryResponse) {
if (dataverseRequest == null) {
throw new NullPointerException("RoleTagRetriever.constructor. dataverseRequest cannot be null");
}
AuthenticatedUser au = dataverseRequest.getAuthenticatedUser();
if (au == null) {
throw new NullPointerException("RoleTagRetriever.constructor. au cannot be null");
}
String userIdentifier = au.getUserIdentifier();
if (userIdentifier == null) {
throw new NullPointerException("RoleTagRetriever.constructor. userIdentifier cannot be null");
}
if (solrQueryResponse == null) {
throw new NullPointerException("RoleTagRetriever.constructor. solrQueryResponse cannot be null");
}
// (1) Reset variables
initLookups();
// (2) Load roles from solr docs
loadInfoFromSolrResponseDocs(solrQueryResponse);
// (3) Load grandparent ids, if needed
findDataverseIdsForFiles();
// (4) Retrieve the role ids
retrieveRoleIdsForDvObjects(dataverseRequest, au);
// (5) Prepare final role lists
prepareFinalRoleLists();
// showRoleListHash();
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Index method filesearch.
@GET
@Path("filesearch")
public Response filesearch(@QueryParam("persistentId") String persistentId, @QueryParam("semanticVersion") String semanticVersion, @QueryParam("q") String userSuppliedQuery) {
Dataset dataset = datasetService.findByGlobalId(persistentId);
if (dataset == null) {
return error(Status.BAD_REQUEST, "Could not find dataset with persistent id " + persistentId);
}
User user = GuestUser.get();
try {
AuthenticatedUser authenticatedUser = findAuthenticatedUserOrDie();
if (authenticatedUser != null) {
user = authenticatedUser;
}
} catch (WrappedResponse ex) {
}
RetrieveDatasetVersionResponse datasetVersionResponse = datasetVersionService.retrieveDatasetVersionByPersistentId(persistentId, semanticVersion);
if (datasetVersionResponse == null) {
return error(Status.BAD_REQUEST, "Problem searching for files. Could not find dataset version based on " + persistentId + " and " + semanticVersion);
}
DatasetVersion datasetVersion = datasetVersionResponse.getDatasetVersion();
FileView fileView = searchFilesService.getFileView(datasetVersion, user, userSuppliedQuery);
if (fileView == null) {
return error(Status.BAD_REQUEST, "Problem searching for files. Null returned from getFileView.");
}
JsonArrayBuilder filesFound = Json.createArrayBuilder();
JsonArrayBuilder cards = Json.createArrayBuilder();
JsonArrayBuilder fileIds = Json.createArrayBuilder();
for (SolrSearchResult result : fileView.getSolrSearchResults()) {
cards.add(result.getNameSort());
fileIds.add(result.getEntityId());
JsonObjectBuilder fileFound = Json.createObjectBuilder();
fileFound.add("name", result.getNameSort());
fileFound.add("entityId", result.getEntityId().toString());
fileFound.add("datasetVersionId", result.getDatasetVersionId());
fileFound.add("datasetId", result.getParent().get(SearchFields.ID));
filesFound.add(fileFound);
}
JsonArrayBuilder facets = Json.createArrayBuilder();
for (FacetCategory facetCategory : fileView.getFacetCategoryList()) {
facets.add(facetCategory.getFriendlyName());
}
JsonArrayBuilder filterQueries = Json.createArrayBuilder();
for (String filterQuery : fileView.getFilterQueries()) {
filterQueries.add(filterQuery);
}
JsonArrayBuilder allDatasetVersionIds = Json.createArrayBuilder();
for (DatasetVersion dsVersion : dataset.getVersions()) {
allDatasetVersionIds.add(dsVersion.getId());
}
JsonObjectBuilder data = Json.createObjectBuilder();
data.add("filesFound", filesFound);
data.add("cards", cards);
data.add("fileIds", fileIds);
data.add("facets", facets);
data.add("user", user.getIdentifier());
data.add("persistentID", persistentId);
data.add("query", fileView.getQuery());
data.add("filterQueries", filterQueries);
data.add("allDataverVersionIds", allDatasetVersionIds);
data.add("semanticVersion", datasetVersion.getSemanticVersion());
return ok(data);
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Notifications method getAllNotificationsForUser.
@GET
@Path("all")
public Response getAllNotificationsForUser() {
User user;
try {
user = findUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.UNAUTHORIZED, "You must supply an API token.");
}
if (user == null) {
return error(Response.Status.BAD_REQUEST, "A user could not be found based on the API token.");
}
if (!(user instanceof AuthenticatedUser)) {
// It's unlikely we'll reach this error. A Guest doesn't have an API token and would have been blocked above.
return error(Response.Status.BAD_REQUEST, "Only an AuthenticatedUser can have notifications.");
}
AuthenticatedUser authenticatedUser = (AuthenticatedUser) user;
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
List<UserNotification> notifications = userNotificationSvc.findByUser(authenticatedUser.getId());
for (UserNotification notification : notifications) {
NullSafeJsonBuilder notificationObjectBuilder = jsonObjectBuilder();
JsonArrayBuilder reasonsForReturn = Json.createArrayBuilder();
Type type = notification.getType();
notificationObjectBuilder.add("id", notification.getId());
notificationObjectBuilder.add("type", type.toString());
/* FIXME - Re-add reasons for return if/when they are added to the notifications page.
if (Type.RETURNEDDS.equals(type) || Type.SUBMITTEDDS.equals(type)) {
JsonArrayBuilder reasons = getReasonsForReturn(notification);
for (JsonValue reason : reasons.build()) {
reasonsForReturn.add(reason);
}
notificationObjectBuilder.add("reasonsForReturn", reasonsForReturn);
}
*/
jsonArrayBuilder.add(notificationObjectBuilder);
}
JsonObjectBuilder result = Json.createObjectBuilder().add("notifications", jsonArrayBuilder);
return ok(result);
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Datasets method receiveChecksumValidationResults.
@POST
@Path("{identifier}/dataCaptureModule/checksumValidation")
public Response receiveChecksumValidationResults(@PathParam("identifier") String id, JsonObject jsonFromDcm) {
logger.log(Level.FINE, "jsonFromDcm: {0}", jsonFromDcm);
AuthenticatedUser authenticatedUser = null;
try {
authenticatedUser = findAuthenticatedUserOrDie();
} catch (WrappedResponse ex) {
return error(Response.Status.BAD_REQUEST, "Authentication is required.");
}
if (!authenticatedUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
String statusMessageFromDcm = jsonFromDcm.getString("status");
try {
Dataset dataset = findDatasetOrDie(id);
if ("validation passed".equals(statusMessageFromDcm)) {
String uploadFolder = jsonFromDcm.getString("uploadFolder");
int totalSize = jsonFromDcm.getInt("totalSize");
ImportMode importMode = ImportMode.MERGE;
try {
JsonObject jsonFromImportJobKickoff = execCommand(new ImportFromFileSystemCommand(createDataverseRequest(findUserOrDie()), dataset, uploadFolder, new Long(totalSize), importMode));
long jobId = jsonFromImportJobKickoff.getInt("executionId");
String message = jsonFromImportJobKickoff.getString("message");
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("jobId", jobId);
job.add("message", message);
return ok(job);
} catch (WrappedResponse wr) {
String message = wr.getMessage();
return error(Response.Status.INTERNAL_SERVER_ERROR, "Uploaded files have passed checksum validation but something went wrong while attempting to put the files into Dataverse. Message was '" + message + "'.");
}
} else if ("validation failed".equals(statusMessageFromDcm)) {
Map<String, AuthenticatedUser> distinctAuthors = permissionService.getDistinctUsersWithPermissionOn(Permission.EditDataset, dataset);
distinctAuthors.values().forEach((value) -> {
userNotificationService.sendNotification((AuthenticatedUser) value, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
List<AuthenticatedUser> superUsers = authenticationServiceBean.findSuperUsers();
if (superUsers != null && !superUsers.isEmpty()) {
superUsers.forEach((au) -> {
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CHECKSUMFAIL, dataset.getId());
});
}
return ok("User notified about checksum validation failure.");
} else {
return error(Response.Status.BAD_REQUEST, "Unexpected status cannot be processed: " + statusMessageFromDcm);
}
} catch (WrappedResponse ex) {
return ex.getResponse();
}
}
Aggregations