public async Task <IActionResult> Get([FromQuery] string validatorId) { if (string.IsNullOrEmpty(validatorId)) { return(BadRequest("No validatorId provided")); } var validatorDefinition = validatorManager.GetValidatorDefinition(validatorId); if (validatorDefinition == null) { return(NotFound()); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync(new GetValidatorResourceDescription(validatorDefinition), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' " + $"accessed validator for type '{validatorDefinition.DataType}' " + $"with ID '{validatorDefinition.Id}'"); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(validatorDefinition), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> GetGlobalRoles([FromQuery] string username) { var normalizedUsername = UsernameNormalizer.Normalize(username); // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync(new GetGlobalRolesResourceDescription(normalizedUsername), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } if (!await authenticationModule.ExistsAsync(normalizedUsername)) { return(NotFound($"User '{normalizedUsername}' doesn't exist")); } var roles = await authenticationModule.GetGlobalRolesForUserAsync(normalizedUsername); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(roles), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> DeleteUser([FromQuery] string username) { var normalizedUsername = UsernameNormalizer.Normalize(username); // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new ManageUserResourceDescription(normalizedUsername, UserManagementActionType.Delete), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var wasDeleted = await authenticationModule.DeleteUserAsync(normalizedUsername); if (wasDeleted) { apiEventLogger.Log(LogLevel.Warning, $"User '{normalizedUsername}' has been deleted"); return(Ok()); } var userExists = await authenticationModule.FindUserAsync(normalizedUsername) != null; if (userExists) { return(StatusCode((int)HttpStatusCode.InternalServerError, "User exists but could not be deleted")); } return(Ok()); }
public async Task <IActionResult> Delete([FromQuery] string validatorId) { if (string.IsNullOrEmpty(validatorId)) { return(BadRequest("No validatorId provided")); } var validatorDefinition = validatorManager.GetValidatorDefinition(validatorId); if (validatorDefinition == null) { return(NotFound()); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new ManageValidatorsResourceDescription( ValidatorManagementAction.Delete, validatorDefinition.Submitter, validatorDefinition.DataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } if (!validatorManager.DeleteValidator(validatorId)) { return(StatusCode((int)HttpStatusCode.NotFound)); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' deleted validator with ID '{validatorId}'"); return(Ok()); }
public async Task <IActionResult> Unsubscribe([FromQuery] string id) { // Validate if (string.IsNullOrEmpty(id)) { return(BadRequest("Subscription ID missing")); } var matchingSubscription = await subscriptionManager.GetSubscriptionByIdAsync(id); if (matchingSubscription == null) { return(NotFound()); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new UnsubscribeResourceDescription(matchingSubscription.Username), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide await subscriptionManager.UnsubscribeAsync(authorizationResult.User.UserName, id); apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' unsubscribed from subscription '{id}'"); return(Ok()); }
public async Task <IActionResult> GetCollectionInformation([FromQuery] string collectionName) { // Validate if (string.IsNullOrEmpty(collectionName)) { return(BadRequest("Collection name not specified")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new GetCollectionInformationResourceDescription(collectionName); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var collectionInformation = await collectionInformationManager.GetCollectionInformationAsync(collectionName, authorizationResult.User); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(collectionInformation), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> ListCollections([FromQuery] bool includeHidden = false) { // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new ListCollectionsResourceDescription(); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var collectionNames = dataRouter.ListCollectionNamesAsync(); var collectionInformations = new List <CollectionInformation>(); await foreach (var collectionName in collectionNames) { var collectionInformation = await collectionInformationManager.GetCollectionInformationAsync(collectionName, authorizationResult.User); if (!includeHidden && collectionInformation.IsHidden) { continue; } collectionInformations.Add(collectionInformation); } return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(collectionInformations), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> Search([FromBody] SearchBody body) { if (body == null) { return(BadRequest("No search body submitted")); } var query = body.Query; DataApiSqlQuery parsedQuery; try { parsedQuery = DataApiSqlQueryParser.Parse(query); } catch (FormatException formatException) { return(BadRequest(formatException.Message)); } // Validate var dataType = parsedQuery.FromArguments; // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SearchResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' submitted query '{query.RemoveLineBreaks()}'"); return(await SearchExecutor.PerformSearch(dataRouter, query, body.Format)); }
public async Task <IActionResult> GetCollectionPermissions([FromQuery] string collectionName) { if (string.IsNullOrEmpty(collectionName)) { return(BadRequest("Invalid collection name")); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new GetCollectionPermissionsResourceDescription(), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var collectionUserPermissions = await authorizationModule.GetAllCollectionPermissionsAsync(collectionName); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(collectionUserPermissions), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordBody body) { if (string.IsNullOrEmpty(body.Username)) { return(BadRequest("Username not specified")); } if (string.IsNullOrEmpty(body.Password)) { return(BadRequest("Password not specified")); } var normalizedUsername = UsernameNormalizer.Normalize(body.Username); if (!await authenticationModule.ExistsAsync(normalizedUsername)) { return(NotFound($"User '{normalizedUsername}' not found")); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new ManageUserResourceDescription(normalizedUsername, UserManagementActionType.ChangePassword), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Execute if (!await authenticationModule.ChangePasswordAsync(normalizedUsername, body.Password)) { return(StatusCode((int)HttpStatusCode.InternalServerError, "Could not update password")); } return(Ok()); }
public async Task <IActionResult> Delete([FromQuery] string viewId) { // Validate if (string.IsNullOrEmpty(viewId)) { return(BadRequest("View-ID not specified")); } var view = await viewManager.GetView(viewId); if (view == null) { return(NotFound()); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var dataType = DetermineViewCollection(view.Query); var resourceDescription = new DeleteViewResourceDescription(view.Submitter, dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(new ContentResult { Content = "Not authorized", ContentType = "text/plain", StatusCode = (int)HttpStatusCode.Unauthorized }); } await viewManager.DeleteViewAsync(viewId); return(Ok()); }
public async Task <IActionResult> GetSubmissionMetadata([FromQuery] string dataType, [FromQuery] string id) { // Validate if (dataType == null) { return(BadRequest("Invalid dataType")); } if (id == null) { return(BadRequest("Invalid id")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new GetDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException) { return(BadRequest($"No data storage backend for data type '{dataType}'")); } if (!(rdDataStorage is IBinaryRdDataStorage binaryRdDataStorage)) { return(await Get(dataType, id)); } if (!await binaryRdDataStorage.ExistsAsync(dataType, id)) { return(NotFound()); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' has accessed metadata of type '{dataType}' with ID '{id}'"); var container = await binaryRdDataStorage.GetMetadataFromId(dataType, id); var json = DataEncoder.DecodeToJson(container.Data); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = json, StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> RemoveRole([FromQuery] string username, [FromQuery] string role, [FromQuery] string dataType) { if (string.IsNullOrEmpty(username)) { return(BadRequest("Username not specified")); } if (string.IsNullOrEmpty(role)) { return(BadRequest("Role not specified")); } if (!Enum.TryParse <Role>(role, out var roleEnumValue)) { return(BadRequest($"Unknown role '{role}'. Valid values are {Enum.GetNames(typeof(Role)).Aggregate((a,b) => $"{a}, {b}")}")); } var normalizedUsername = UsernameNormalizer.Normalize(username); if (!await authenticationModule.ExistsAsync(normalizedUsername)) { return(NotFound($"User '{normalizedUsername}' not found")); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new ManageUserResourceDescription(normalizedUsername, UserManagementActionType.AssignRole), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Execute var isGlobalPermission = string.IsNullOrEmpty(dataType); if (isGlobalPermission) { if (!await authorizationModule.RemoveGlobalRoleFromUser(normalizedUsername, roleEnumValue)) { return(StatusCode((int)HttpStatusCode.InternalServerError, "Could not update user roles")); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' removed global role '{roleEnumValue}' " + $"to user '{normalizedUsername}'"); } else { if (!await authorizationModule.RemoveCollectionRoleFromUser(normalizedUsername, roleEnumValue, dataType)) { return(StatusCode((int)HttpStatusCode.InternalServerError, "Could not update user roles")); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' removed role '{roleEnumValue}' " + $"for collection '{dataType}' to user '{normalizedUsername}'"); } return(Ok()); }
public async Task <IActionResult> Delete([FromQuery] string dataType, [FromQuery] string id) { // Validate if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type not specified")); } if (string.IsNullOrEmpty(id)) { return(BadRequest("ID not specified")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } // Check existance var metadata = await GetExistingMetadataAsync(rdDataStorage, dataType, id); if (metadata == null) // Object doesn't exist { return(Ok()); // SECURITY NOTE: Returning OK without authentication allows for brute-force scanning for valid IDs! } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var overwritingAllowed = await authorizationModule.IsOverwritingAllowedForCollectionAsync(dataType); var resourceDescription = new DeleteDataResourceDescription(dataType, metadata.Submitter, overwritingAllowed); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Delete if (await rdDataStorage.DeleteDataContainerAsync(dataType, id)) { await subscriptionManager.NotifyDataChangedAsync(dataType, id, DataModificationType.Deleted); apiEventLogger.Log(LogLevel.Warning, $"User '{authorizationResult.User.UserName}' has deleted data of type '{dataType}' with ID '{id}'"); return(Ok()); } return(NotFound()); }
public async Task <IActionResult> Get([FromQuery] string viewId, [FromQuery] string resultFormat) { // Validate if (string.IsNullOrEmpty(viewId)) { return(BadRequest("View-ID not specified")); } var resultFormatEnum = ResultFormat.Json; if (resultFormat != null && !Enum.TryParse(resultFormat, out resultFormatEnum)) { var validResultFormats = Enum.GetNames(typeof(ResultFormat)).Aggregate((a, b) => a + ", " + b); return(BadRequest($"Invalid output format '{resultFormat}'. Allowed values: {validResultFormats}")); } var view = await viewManager.GetView(viewId); if (view == null) { return(NotFound()); } string parameterInsertedQuery; try { parameterInsertedQuery = QueryParameterInserter.InsertParameters(view.Query, QueryCollectionToDictionary(Request.Query)); } catch (FormatException formatException) { return(BadRequest(formatException.Message)); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var dataType = DetermineViewCollection(parameterInsertedQuery); var resourceDescription = new GetViewResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(new ContentResult { Content = "Not authorized", ContentType = "text/plain", StatusCode = (int)HttpStatusCode.Unauthorized }); } return(await SearchExecutor.PerformSearch(dataRouter, parameterInsertedQuery, resultFormatEnum)); }
public async Task <IActionResult> SetCollectionOptions([FromBody] CollectionOptions collectionOptions) { if (collectionOptions == null) { return(BadRequest("Collection options not set")); } if (!NamingConventions.IsValidDataType(collectionOptions.CollectionName)) { return(BadRequest($"Data type '{collectionOptions.CollectionName}' is not a valid name for a collection")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(collectionOptions.CollectionName); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } if (collectionOptions.IdGeneratorType.HasValue && !rdDataStorage.IsIdGeneratorTypeSupported(collectionOptions.IdGeneratorType.Value)) { return(BadRequest($"The backing storage for collection '{collectionOptions.CollectionName}' doesn't support ID generator type '{collectionOptions.IdGeneratorType}'")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SetCollectionOptionsResourceDescription(); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide try { await authorizationModule.AddOrUpdateCollectionMetadata(collectionOptions); var logEntries = LoggingHelpers.WriteCollectionMetadataLog(collectionOptions, authorizationResult.User.UserName); logEntries.ForEach(apiEventLogger.Log); return(Ok()); } catch (Exception e) { return(StatusCode((int)HttpStatusCode.InternalServerError, e.InnermostException().Message)); } }
public async Task <IActionResult> Get([FromQuery] string dataType, [FromQuery] string id) { // Validate if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type not specified")); } if (string.IsNullOrEmpty(id)) { return(BadRequest("ID not specified")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new GetDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } // Provide if (!await rdDataStorage.ExistsAsync(dataType, id)) { return(NotFound()); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' has accessed data of type '{dataType}' with ID '{id}'"); var matchingContainer = await rdDataStorage.GetFromIdAsync(dataType, id); var json = DataEncoder.DecodeToJson(matchingContainer.Data); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = json, StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> GetUserProfiles() { // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync(new ViewUserProfilesResoruceDescription(), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var userProfiles = authenticationModule.GetAllUserProfilesAsync(); return(userProfiles.ToFileStreamResult()); }
public async Task <IActionResult> GetMany([FromQuery] string dataType, [FromQuery] string whereArguments, [FromQuery] string orderByArguments, [FromQuery] uint?limit = null) { // Validate if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type not specified")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new GetDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' requested objects of type '{dataType}' matching '{whereArguments?.RemoveLineBreaks()}' ordered by '{orderByArguments?.RemoveLineBreaks()}'"); try { var getManyResult = rdDataStorage.GetManyAsync(dataType, whereArguments, orderByArguments, limit); var stream = new SearchResultStream(getManyResult.Select(x => DataEncoder.DecodeToJson(x.Data))); return(new FileStreamResult(stream, Conventions.JsonContentType)); } catch (FormatException formatException) { return(BadRequest(formatException.Message)); } catch (Exception e) { return(StatusCode((int)HttpStatusCode.InternalServerError, e.InnermostException().Message)); } }
public async Task <IActionResult> Exists([FromQuery] string dataType, [FromQuery] string id) { // Validate if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type not specified")); } if (string.IsNullOrEmpty(id)) { return(BadRequest("ID not specified")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new GetDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } // Provide var exists = await rdDataStorage.ExistsAsync(dataType, id); if (exists) { return(Ok()); } else { return(NotFound()); } }
public async Task <IActionResult> GetSubscribedObjects([FromQuery] string dataType = null) { // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new SubscriptionResourceDescription(dataType), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide var subscribedObjects = subscriptionManager.GetSubscribedObjectsAsync(authorizationResult.User.UserName, dataType); return(subscribedObjects.ToFileStreamResult()); }
public async Task <IActionResult> Subscribe([FromBody] SubscriptionBody subscription) { if (subscription == null) { return(BadRequest("Subscription body was missing or malformatted")); } if (subscription.ModificationTypes.Count == 0) { return(BadRequest($"{nameof(SubscriptionBody.ModificationTypes)} was empty")); } if (subscription.ModificationTypes.Any(x => x == DataModificationType.Unknown)) { return(BadRequest($"{nameof(SubscriptionBody.ModificationTypes)} contained value '{DataModificationType.Unknown}'")); } // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new SubscriptionResourceDescription(subscription.DataType), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var username = authorizationResult.User.UserName; if (await subscriptionManager.HasExistingSubscriptionAsync(subscription, username)) { return(Conflict("A subscription with exact same parameters already exists")); } // Provide var subscriptionId = await subscriptionManager.SubscribeAsync(subscription, username); apiEventLogger.Log(LogLevel.Info, $"User '{username}' subscribed to '{subscription.DataType}' with filter '{subscription.Filter}'"); return(new ContentResult { ContentType = "text/plain", Content = subscriptionId, StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> UnsubscribeAll([FromQuery] string dataType) { // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new UnsubscribeAllResourceDescription(), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide await subscriptionManager.UnsubscribeAllAsync(authorizationResult.User.UserName, dataType); apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' unsubscribed from '{dataType ?? "Everything"}'"); return(Ok()); }
public async Task <IActionResult> GetNew(string dataType, int count = 1) { // Validate IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SubmitDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide var idReservationResult = await rdDataStorage.GetIdsAsync(dataType, loggedInUsername, count); if (idReservationResult.Any(reservationResult => !reservationResult.IsReserved)) { return(StatusCode((int)HttpStatusCode.InternalServerError, "Failed to reserve ID")); } if (idReservationResult.Any(x => x.IsNewCollection)) { newCollectionTasks.PerformTasks(dataType, authorizationResult.User); } return(new ContentResult { ContentType = "text/plain", Content = string.Join("\n", idReservationResult.Select(x => x.Id)), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> TransferSubmissionData([FromQuery] string dataType, [FromQuery] string submissionId) { if (submissionId == null) { return(BadRequest("Invalid submissionId")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SubmitDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException) { return(BadRequest($"No data storage backend for data type '{dataType}'")); } if (!(rdDataStorage is IBinaryRdDataStorage binaryRdDataStorage)) { return(BadRequest($"Transfer of data for data type '{dataType}' is not supported")); } if (!await binaryRdDataStorage.ExistsAsync(dataType, submissionId)) { return(NotFound()); } apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' has injected binary payload into '{dataType}' with ID '{submissionId}'"); await binaryRdDataStorage.InjectDataAsync(dataType, submissionId, Request.Body); return(Ok()); }
public async Task <IActionResult> ReportTo( [FromQuery] string recipient, [FromQuery] string dataType, [FromQuery] string id) { // Validate if (string.IsNullOrEmpty(recipient)) { return(BadRequest("Recipient missing")); } if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type missing")); } if (string.IsNullOrEmpty(id)) { return(BadRequest("ID missing")); } var recipientExists = await authenticationModule.ExistsAsync(recipient); if (!recipientExists) { return(BadRequest("Unknown recipient")); } // Authenticate var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var authorizationResult = await authorizationModule.AuthorizeAsync( new ReportDataResourceDescription(), loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide await subscriptionManager.NotifyUserAboutNewDataAsync(recipient, dataType, id); apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' reported '{dataType}' with ID '{id}' to '{recipient}'"); return(Ok()); }
public async Task <IActionResult> Reserve(string dataType, string id) { // Validate IRdDataStorage rdDataStorage; try { rdDataStorage = await dataRouter.GetSourceSystemAsync(dataType); } catch (KeyNotFoundException e) { return(BadRequest(e.Message)); } if (!rdDataStorage.IsValidId(id)) { return(BadRequest($"The ID '{id}' for object of type '{dataType}' is not valid")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SubmitDataResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide var idReservationResult = await rdDataStorage.ReserveIdAsync(dataType, id, loggedInUsername); if (!idReservationResult.IsReserved) { return(StatusCode((int)HttpStatusCode.Forbidden, "Failed to reserve ID")); } if (idReservationResult.IsNewCollection) { newCollectionTasks.PerformTasks(dataType, authorizationResult.User); } return(Ok()); }
public async Task <IActionResult> GetAll([FromQuery] string dataType = null) { // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new ManageValidatorsResourceDescription(ValidatorManagementAction.ListAll, null, null); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } var validatorDefinitions = await validatorManager.GetAllValidatorDefinitions(dataType); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(validatorDefinitions), StatusCode = (int)HttpStatusCode.OK }); }
public async Task <IActionResult> Create([FromBody] CreateViewBody body) { if (FromArgumentIsNullOrContainsPlaceholder(body.Query)) { return(BadRequest("Data type (FROM-argument) must be specified in query and cannot be a placeholder")); } var dataType = DetermineViewCollection(body.Query); // Authroize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new CreateViewResourceDescription(dataType); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } try { var viewInformation = await viewManager.CreateViewAsync(body, authorizationResult.User.UserName); apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' added view with ID '{viewInformation.ViewId}'"); return(new ContentResult { ContentType = Conventions.JsonContentType, Content = JsonConvert.SerializeObject(viewInformation), StatusCode = (int)HttpStatusCode.OK }); } catch (DocumentAlreadyExistsException) { return(Conflict($"View with name '{body.ViewId}' already exists")); } catch (Exception e) { return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message)); } }
public async Task <IActionResult> SetRedirection( [FromQuery] string dataType, [FromQuery] string dataSourceSystem) { // Validate if (string.IsNullOrEmpty(dataType)) { return(BadRequest("Data type not specified")); } if (!NamingConventions.IsValidDataType(dataType)) { return(BadRequest($"Data type '{dataType}' is not a valid name for a collection")); } if (!dataRouter.IsAvailable(dataSourceSystem)) { return(StatusCode((int)HttpStatusCode.ServiceUnavailable, $"Data source system '{dataSourceSystem}' is currently unavailable")); } if (!dataRouter.IsDataTypeSupported(dataType, dataSourceSystem)) { return(BadRequest($"Data source system '{dataSourceSystem}' doesn't support data type '{dataType}'")); } // Authorize var loggedInUsername = UsernameNormalizer.Normalize(HttpContext.User.Identity.Name); var resourceDescription = new SetDataRedirectionResourceDescription(); var authorizationResult = await authorizationModule.AuthorizeAsync(resourceDescription, loggedInUsername); if (!authorizationResult.IsAuthorized) { return(StatusCode((int)HttpStatusCode.Unauthorized, "Not authorized")); } // Provide apiEventLogger.Log(LogLevel.Info, $"User '{authorizationResult.User.UserName}' redirected '{dataType}' to '{dataSourceSystem}'"); await dataRouter.SetRedirectionAsync(new DataRedirection(dataType, dataSourceSystem)); return(Ok()); }