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> 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 }); } }
private async Task <DialogTurnResult> MainMenuStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var userProfilesFilePath = _configuration["UsersFilePathSource"]; // Fetch list of all user profile string userProfileJson = await _fileUtility.ReadFromFile(userProfilesFilePath); List <UserProfile> userProfiles = JsonConvert.DeserializeObject <List <UserProfile> >(userProfileJson); stepContext.Values["password"] = (string)stepContext.Result; if (stepContext.Values["Language"] == "KISWAHILI") { //Get the current profile object from user state var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken); //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken); //save all of the data inside the user profile userProfile.Name = (string)stepContext.Values["Name"]; userProfile.County = (string)stepContext.Values["county"]; userProfile.SubCounty = (string)stepContext.Values["subCounty"]; userProfile.Ward = (string)stepContext.Values["ward"]; userProfile.UserName = (string)stepContext.Values["userName"]; userProfile.Password = (string)stepContext.Values["password"]; //show Summary to the user await stepContext.Context.SendActivityAsync(MessageFactory.Text($" Huu Hapa muhtasari wa Profaili yako: "), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Jina:{0}", userProfile.Name)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti:{0}", userProfile.County)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti ndogo:{0}", userProfile.SubCounty)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Wadi:{0}", userProfile.Ward)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken); //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format(" Hongera {0}!Umesajiliwa kutumia huduma yetu.Tafadhali chagua(1.MAIN MENU) kuendelea kutumia huduma", userProfile.Name)), cancellationToken); // Save data in userstate await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile); userProfiles.Add(userProfile); // Save user profiles var userProfilesString = JsonConvert.SerializeObject(userProfiles, Formatting.Indented); await _fileUtility.WriteToFile(userProfilesString, userProfilesFilePath); //display main menu return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu", new PromptOptions { Prompt = MessageFactory.Text("MAIN MENU"), Choices = ChoiceFactory.ToChoices(new List <string> { "TAARIFA ", "HABARI", "RUFAA", "UTAFITI", "SASISHA PROFAILI", "SHARE" }), }, cancellationToken)); stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result; //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken)); } else { //Get the current profile object from user state var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken); //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken); //save all of the data inside the user profile userProfile.Name = (string)stepContext.Values["Name"]; userProfile.County = (string)stepContext.Values["county"]; userProfile.SubCounty = (string)stepContext.Values["subCounty"]; userProfile.Ward = (string)stepContext.Values["ward"]; userProfile.UserName = (string)stepContext.Values["userName"]; userProfile.Password = (string)stepContext.Values["password"]; //show Summary to the user await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Here is a summary of your Profile:"), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Name:{0}", userProfile.Name)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("County:{0}", userProfile.County)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("SubCounty:{0}", userProfile.SubCounty)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Ward:{0}", userProfile.Ward)), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken); //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Congratulations {0}! You are now registered to use our service. Please choose (1.MAIN MENU ) to continue using the service.", userProfile.Name)), cancellationToken); //save data in userstate await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile); //Write user details to a json file var userDetails = JsonConvert.SerializeObject(userProfile, Formatting.Indented); var filePath = @"C:\Users\Tech Jargon\source\repos\FeedBackLegalBot\FeedBackLegalBot\Data\UserDetails.json"; if (!File.Exists(filePath)) { File.WriteAllText(filePath, userDetails); } else { File.AppendAllText(filePath, userDetails); } //display main menu return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu", new PromptOptions { Prompt = MessageFactory.Text("MAIN MENU"), Choices = ChoiceFactory.ToChoices(new List <string> { "INFORMATION", "NEWS", "REFERAL", "SURVEY", "UPDATE PROFILE", "SHARE" }), }, cancellationToken)); stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result; //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken)); } }
public void DoWork() { var fileName = $"{DateTime.Now:yyyyMMddHHmmss}.log"; _fileUtility.WriteToFile(fileName, "LOOSELY COUPLED - This is a test"); }
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.Status401Unauthorized }); } // 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 document-readable JSON-styled 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 }); } }