public async Task <IActionResult> RemoveUserClaim([FromQuery] string userPrincipalName, [FromQuery] string categoryName) { try { /* Validate whether authenticated user is samples administrator */ string authenticatedUserPrincipalName = User.Identity.Name; bool isAdmin = _administrators.Administrators.Contains(authenticatedUserPrincipalName); if (!isAdmin) { return(new JsonResult( $"{userPrincipalName} is not authorized to remove the user claim.") { StatusCode = StatusCodes.Status401Unauthorized }); } if (string.IsNullOrEmpty(userPrincipalName) || string.IsNullOrEmpty(categoryName)) { return(new JsonResult($"Provide both the user principal name and category name in the search parameters. " + $"e.g. /api/GraphExplorerSamplesAdmin?userprincipalname=john.doe@microsoft.com&categoryname=users") { StatusCode = StatusCodes.Status400BadRequest }); } // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Remove the user claim in the given category policy SampleQueriesPolicies updatedPoliciesList = SamplesPolicyService.RemoveUserClaim(policies, categoryName, userPrincipalName); string updatedPoliciesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(updatedPoliciesList); await _fileUtility.WriteToFile(updatedPoliciesJson, _policiesFilePathSource); // Get the category policy that has just been updated CategoryPolicy categoryPolicy = updatedPoliciesList.CategoryPolicies.FirstOrDefault(x => x.CategoryName.Equals(categoryName, StringComparison.OrdinalIgnoreCase)); return(Ok(categoryPolicy)); } catch (InvalidOperationException invalidOpsException) { // One or more parameters values do not exist in the list of category policies return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> UpdateUserClaimAsync([FromBody] CategoryPolicy categoryPolicy) { try { /* Validate whether authenticated user is samples administrator */ string userPrincipalName = User.Identity.Name; bool isAdmin = _administrators.Administrators.Contains(userPrincipalName); if (!isAdmin) { return(new JsonResult($"{userPrincipalName} is not authorized to update the user claim.") { StatusCode = StatusCodes.Status403Forbidden }); } // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Update the user claim in the given category policy SampleQueriesPolicies updatedPoliciesList = SamplesPolicyService.ModifyUserClaim(policies, categoryPolicy); string updatedPoliciesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(updatedPoliciesList); await _fileUtility.WriteToFile(updatedPoliciesJson, _policiesFilePathSource); // Fetch the category policy with the updated user claim categoryPolicy = updatedPoliciesList.CategoryPolicies.Find(x => x.CategoryName == categoryPolicy.CategoryName); // Success; return the user claim in the category policy that was just updated return(Ok(categoryPolicy)); } catch (InvalidOperationException invalidOpsException) { // Category policy provided doesn't exist return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (ArgumentNullException argNullException) { // Missing required parameter return(new JsonResult(argNullException.Message) { StatusCode = StatusCodes.Status400BadRequest }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> CreateSampleQueryAsync([FromBody] SampleQueryModel sampleQueryModel) { try { // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); string categoryName = sampleQueryModel.Category; ClaimsIdentity identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; string userPrincipalName = (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ?? claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Post); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to create the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status403Forbidden }); } // Get the list of sample queries SampleQueriesList sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US"); // Assign a new Id to the new sample query sampleQueryModel.Id = Guid.NewGuid(); // Add the new sample query to the list of sample queries SampleQueriesList newSampleQueriesList = SamplesService.AddToSampleQueriesList(sampleQueriesList, sampleQueryModel); // Get the serialized JSON string of the sample query string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(newSampleQueriesList); // Disabled functionality // await _fileUtility.WriteToFile(updatedSampleQueriesJson, _queriesFilePathSource); // Create the query Uri for the newly created sample query string newSampleQueryUri = string.Format("{0}://{1}{2}/{3}", Request.Scheme, Request.Host, Request.Path.Value, sampleQueryModel.Id.ToString()); // Success; return the new sample query that was added along with its Uri return(Created(newSampleQueryUri, sampleQueryModel)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> CreateUserClaimAsync([FromBody] CategoryPolicy categoryPolicy) { try { /* Validate whether authenticated user is samples administrator */ ClaimsIdentity identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; string userPrincipalName = (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ?? claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value; bool isAdmin = _administrators.Administrators.Contains(userPrincipalName); if (!isAdmin) { return(new JsonResult($"{userPrincipalName} is not authorized to create the user claim.") { StatusCode = StatusCodes.Status403Forbidden }); } // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Add the new user claim in the given category policy SampleQueriesPolicies updatedPoliciesList = SamplesPolicyService.ModifyUserClaim(policies, categoryPolicy); string updatedPoliciesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(updatedPoliciesList); await _fileUtility.WriteToFile(updatedPoliciesJson, _policiesFilePathSource); // Extract the first user claim from the given categoryPolicy; this is what was added UserClaim userClaim = categoryPolicy.UserClaims.First(); // Fetch the category policy with the newly created user claim categoryPolicy = updatedPoliciesList.CategoryPolicies.Find(x => x.CategoryName == categoryPolicy.CategoryName); // Create the query Uri for the newly created user claim string newUserClaimUri = string.Format("{0}://{1}{2}?userprincipalname={3}&categoryname={4}", Request.Scheme, Request.Host, Request.Path.Value, userClaim.UserPrincipalName, categoryPolicy.CategoryName); return(Created(newUserClaimUri, categoryPolicy)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> CreateSampleQueryAsync([FromBody] SampleQueryModel sampleQueryModel) { try { // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); string categoryName = sampleQueryModel.Category; string userPrincipalName = User.Identity.Name; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Post); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to create the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status401Unauthorized }); } // Get the list of sample queries SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync(); // Assign a new Id to the new sample query sampleQueryModel.Id = Guid.NewGuid(); // Add the new sample query to the list of sample queries SampleQueriesList newSampleQueriesList = SamplesService.AddToSampleQueriesList(sampleQueriesList, sampleQueryModel); // Get the serialized JSON string of the sample query string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(newSampleQueriesList); // Save the document-readable JSON-styled string to the source file await _fileUtility.WriteToFile(newSampleQueriesJson, _queriesFilePathSource); // Create the query Uri for the newly created sample query string newSampleQueryUri = string.Format("{0}://{1}{2}/{3}", Request.Scheme, Request.Host, Request.Path.Value, sampleQueryModel.Id.ToString()); // Success; return the new sample query that was added along with its Uri return(Created(newSampleQueryUri, sampleQueryModel)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> CreateUserClaimAsync([FromBody] CategoryPolicy categoryPolicy) { try { /* Validate whether authenticated user is samples administrator */ string userPrincipalName = User.Identity.Name; bool isAdmin = _administrators.Administrators.Contains(userPrincipalName); if (!isAdmin) { return(new JsonResult($"{userPrincipalName} is not authorized to create the user claim.") { StatusCode = StatusCodes.Status401Unauthorized }); } // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Add the new user claim in the given category policy SampleQueriesPolicies updatedPoliciesList = SamplesPolicyService.ModifyUserClaim(policies, categoryPolicy); string updatedPoliciesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(updatedPoliciesList); await _fileUtility.WriteToFile(updatedPoliciesJson, _policiesFilePathSource); // Extract the first user claim from the given categoryPolicy; this is what was added UserClaim userClaim = categoryPolicy.UserClaims.First(); // Create the query Uri for the newly created sample query string newUserClaimUri = string.Format("{0}://{1}{2}?userprincipalname={3}&categoryname={4}", Request.Scheme, Request.Host, Request.Path.Value, userClaim.UserPrincipalName, categoryPolicy.CategoryName); return(Created(newUserClaimUri, categoryPolicy)); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
/// <summary> /// Gets the JSON file contents of the policies and returns a deserialized instance of a <see cref="SampleQueriesPolicies"/> from this. /// </summary> /// <returns>A list of category policies.</returns> private async Task <SampleQueriesPolicies> GetSampleQueriesPoliciesAsync() { // Get the file contents from source string jsonFileContents = await _fileUtility.ReadFromFile(_policiesFilePathSource); if (string.IsNullOrEmpty(jsonFileContents)) { // Create default policies template SampleQueriesPolicies policies = SamplesPolicyService.CreateDefaultPoliciesTemplate(); // Get the serialized JSON string of the list of policies string policiesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(policies); // Save the document-readable JSON-styled string to the source file await _fileUtility.WriteToFile(policiesJson, _policiesFilePathSource); // Return the list of policies return(policies); } // Return the list of policies return(SamplesPolicyService.DeserializeSampleQueriesPolicies(jsonFileContents)); }
public async Task <IActionResult> DeleteSampleQueryAsync(string id) { try { // Get the list of sample queries SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync(); // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Check if the sample query model exists in the list of sample queries bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id)); if (!sampleQueryExists) { throw new InvalidOperationException($"No sample query found with id: {id}"); } string categoryName = sampleQueriesList.SampleQueries.Find(x => x.Id == Guid.Parse(id)).Category; string userPrincipalName = User.Identity.Name; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Delete); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to delete the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status401Unauthorized }); } if (sampleQueriesList.SampleQueries.Count == 0) { return(NotFound()); // list is empty; the sample query being searched is definitely not in an empty list } // Remove the sample query with given id from the list of sample queries sampleQueriesList = SamplesService.RemoveSampleQuery(sampleQueriesList, Guid.Parse(id)); // Get the serialized JSON string of the list of sample queries string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(sampleQueriesList); // Save the document-readable JSON-styled string to the source file await _fileUtility.WriteToFile(newSampleQueriesJson, _queriesFilePathSource); // Success; no content to return return(new JsonResult("Deleted successfully.") { StatusCode = StatusCodes.Status204NoContent }); } catch (InvalidOperationException invalidOpsException) { // Sample query with provided id not found return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> DeleteSampleQueryAsync(string id) { try { // Get the list of sample queries SampleQueriesList sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US"); // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); // Check if the sample query model exists in the list of sample queries bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id)); if (!sampleQueryExists) { throw new InvalidOperationException($"No sample query found with id: {id}"); } string categoryName = sampleQueriesList.SampleQueries.Find(x => x.Id == Guid.Parse(id)).Category; ClaimsIdentity identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; string userPrincipalName = (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ?? claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Delete); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to delete the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status403Forbidden }); } if (sampleQueriesList.SampleQueries.Count == 0) { return(NotFound()); // list is empty; the sample query being searched is definitely not in an empty list } // Remove the sample query with given id from the list of sample queries sampleQueriesList = SamplesService.RemoveSampleQuery(sampleQueriesList, Guid.Parse(id)); // Get the serialized JSON string of the list of sample queries string newSampleQueriesJson = SamplesService.SerializeSampleQueriesList(sampleQueriesList); // Disabled functionality // await _fileUtility.WriteToFile(updatedSampleQueriesJson, _queriesFilePathSource); // Success; no content to return return(new JsonResult("Deleted successfully.") { StatusCode = StatusCodes.Status204NoContent }); } catch (InvalidOperationException invalidOpsException) { // Sample query with provided id not found return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> UpdateSampleQueryAsync(string id, [FromBody] SampleQueryModel sampleQueryModel) { try { // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); string categoryName = sampleQueryModel.Category; ClaimsIdentity identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; string userPrincipalName = (claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnJwt, StringComparison.OrdinalIgnoreCase)) ?? claims?.FirstOrDefault(x => x.Type.Equals(Constants.ClaimTypes.UpnUriSchema, StringComparison.OrdinalIgnoreCase)))?.Value; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Put); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to update the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status403Forbidden }); } // Get the list of sample queries SampleQueriesList sampleQueriesList = await _samplesStore.FetchSampleQueriesListAsync("en-US"); if (sampleQueriesList.SampleQueries.Count == 0) { return(NotFound()); // List is empty; the sample query being searched is definitely not in an empty list } // Check if the sample query model exists in the list of sample queries bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id)); if (!sampleQueryExists) { throw new InvalidOperationException($"No sample query found with id: {id}"); } // Update the provided sample query model into the list of sample queries SampleQueriesList updatedSampleQueriesList = SamplesService.UpdateSampleQueriesList(sampleQueriesList, sampleQueryModel, Guid.Parse(id)); // Get the serialized JSON string of this sample query string updatedSampleQueriesJson = SamplesService.SerializeSampleQueriesList(updatedSampleQueriesList); // Success; return the sample query model object that was just updated return(Ok(sampleQueryModel)); } catch (InvalidOperationException invalidOpsException) { // sample query with provided id not found return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }
public async Task <IActionResult> UpdateSampleQueryAsync(string id, [FromBody] SampleQueryModel sampleQueryModel) { try { // Get the list of policies SampleQueriesPolicies policies = await GetSampleQueriesPoliciesAsync(); string categoryName = sampleQueryModel.Category; string userPrincipalName = User.Identity.Name; // Check if authenticated user is authorized for this action bool isAuthorized = SamplesPolicyService.IsUserAuthorized(policies, userPrincipalName, categoryName, HttpMethods.Put); if (!isAuthorized) { return(new JsonResult( $"{userPrincipalName} is not authorized to update the sample query. Category: '{categoryName}'") { StatusCode = StatusCodes.Status403Forbidden }); } // Get the list of sample queries SampleQueriesList sampleQueriesList = await GetSampleQueriesListAsync(); if (sampleQueriesList.SampleQueries.Count == 0) { return(NotFound()); // List is empty; the sample query being searched is definitely not in an empty list } // Check if the sample query model exists in the list of sample queries bool sampleQueryExists = sampleQueriesList.SampleQueries.Exists(x => x.Id == Guid.Parse(id)); if (!sampleQueryExists) { throw new InvalidOperationException($"No sample query found with id: {id}"); } // Update the provided sample query model into the list of sample queries SampleQueriesList updatedSampleQueriesList = SamplesService.UpdateSampleQueriesList(sampleQueriesList, sampleQueryModel, Guid.Parse(id)); // Get the serialized JSON string of this sample query string updatedSampleQueriesJson = SamplesService.SerializeSampleQueriesList(updatedSampleQueriesList); // Save the JSON string to the source file await _fileUtility.WriteToFile(updatedSampleQueriesJson, _queriesFilePathSource); // Success; return the sample query model object that was just updated return(Ok(sampleQueryModel)); } catch (InvalidOperationException invalidOpsException) { // sample query with provided id not found return(new JsonResult(invalidOpsException.Message) { StatusCode = StatusCodes.Status404NotFound }); } catch (Exception exception) { return(new JsonResult(exception.Message) { StatusCode = StatusCodes.Status500InternalServerError }); } }