public void Parse_Parameter() { // ARRANGE var message = "Please update the password by clicking on the website {{configuration.Get('humanTaskUrl')}}/humantasks/{{messages.Get('humanTaskCreated', 'humanTaskInstance.fileId')}}/instances/{{messages.Get('humanTaskCreated', 'humanTaskInstance.id')}}?auth=email"; var incomingTokens = new List <MessageToken> { MessageToken.NewMessage(Guid.NewGuid().ToString(), "humanTaskCreated", new JObject { { "humanTaskInstance", new JObject { { "id", "id" }, { "fileId", "fileId" } } } }.ToString()) }; var configuration = new DelegateConfigurationAggregate(); configuration.AddRecord("humanTaskUrl", "http://localhost:4200"); // ACT var result = DelegateHelper.Parse(configuration, incomingTokens, message); // ASSERT Assert.Equal("Please update the password by clicking on the website http://localhost:4200/humantasks/fileId/instances/id?auth=email", result); }
private void InitializeDatabase(IApplicationBuilder app) { using (var scope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { using (var context = scope.ServiceProvider.GetService <BPMNDbContext>()) { context.Database.Migrate(); if (context.ProcessFiles.Any()) { return; } var pathLst = Directory.EnumerateFiles(Path.Combine(_env.ContentRootPath, "Bpmns"), "*.bpmn").ToList(); foreach (var path in pathLst) { var bpmnTxt = File.ReadAllText(path); var name = Path.GetFileName(path); var processFile = ProcessFileAggregate.New(name, name, name, 0, bpmnTxt); context.ProcessFiles.Add(processFile); } context.DelegateConfigurations.Add(DelegateConfigurationAggregate.Create("GetWeatherInformationDelegate", typeof(GetWeatherInformationDelegate).FullName)); context.SaveChanges(); } } }
public Task <bool> Update(DelegateConfigurationAggregate configuration, CancellationToken cancellationToken) { var record = _delegateConfigurationAggregates.First(_ => _.AggregateId == configuration.AggregateId); _delegateConfigurationAggregates.Remove(record); _delegateConfigurationAggregates.Add((DelegateConfigurationAggregate)record.Clone()); return(Task.FromResult(true)); }
private static ConcurrentBag <DelegateConfigurationAggregate> GetDelegateConfigurations() { var credential = JsonConvert.DeserializeObject <CredentialsParameter>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "credentials.json"))); var sendEmailDelegate = DelegateConfigurationAggregate.Create("SendEmailDelegate", typeof(SendEmailDelegate).FullName); sendEmailDelegate.AddDisplayName("fr", "Envoyer un email"); sendEmailDelegate.AddDisplayName("en", "Send email"); sendEmailDelegate.AddRecord("httpBody", "Please update the password by clicking on the website {{configuration.Get('humanTaskUrl')}}/humantaskinstances/{{messages.Get('humanTaskCreated', 'humanTaskInstance.id')}}?auth=email, the OTP code is {{messages.Get('otp', 'otpCode')}}"); sendEmailDelegate.AddRecord("subject", "Update password"); sendEmailDelegate.AddRecord("fromEmail", credential.Login); sendEmailDelegate.AddRecord("smtpHost", "smtp.gmail.com"); sendEmailDelegate.AddRecord("smtpPort", "587"); sendEmailDelegate.AddRecord("smtpUserName", credential.Login); sendEmailDelegate.AddRecord("smtpPassword", credential.Password); sendEmailDelegate.AddRecord("humanTaskUrl", "http://localhost:4200"); sendEmailDelegate.AddRecord("smtpEnableSsl", "true"); var updateUserPasswordDelegate = DelegateConfigurationAggregate.Create("UpdateUserPasswordDelegate", typeof(UpdateUserPasswordDelegate).FullName); updateUserPasswordDelegate.AddDisplayName("fr", "Mettre à jour le mot de passe"); updateUserPasswordDelegate.AddDisplayName("en", "Update password"); updateUserPasswordDelegate.AddRecord("clientId", "humanTaskClient"); updateUserPasswordDelegate.AddRecord("clientSecret", "humanTaskClientSecret"); updateUserPasswordDelegate.AddRecord("tokenUrl", "https://localhost:60000/token"); updateUserPasswordDelegate.AddRecord("userUrl", "https://localhost:60000/management/users/{id}/password"); updateUserPasswordDelegate.AddRecord("scope", "manage_users"); var generateOTPDelegate = DelegateConfigurationAggregate.Create("GenerateOTPDelegate", typeof(GenerateOTPDelegate).FullName); generateOTPDelegate.AddDisplayName("fr", "Générer le code OTP"); generateOTPDelegate.AddDisplayName("en", "Generate OTP code"); generateOTPDelegate.AddRecord("clientId", "humanTaskClient"); generateOTPDelegate.AddRecord("clientSecret", "humanTaskClientSecret"); generateOTPDelegate.AddRecord("tokenUrl", "https://localhost:60000/token"); generateOTPDelegate.AddRecord("userUrl", "https://localhost:60000/management/users/{id}/otp"); generateOTPDelegate.AddRecord("scope", "manage_users"); var assignHumanTaskInstanceDelegate = DelegateConfigurationAggregate.Create("assignHumanTask", typeof(AssignHumanTaskInstanceDelegate).FullName); assignHumanTaskInstanceDelegate.AddDisplayName("fr", "Assigner la tâche humaine"); assignHumanTaskInstanceDelegate.AddDisplayName("en", "Assign human task"); assignHumanTaskInstanceDelegate.AddRecord("clientId", "humanTaskClient"); assignHumanTaskInstanceDelegate.AddRecord("clientSecret", "humanTaskClientSecret"); assignHumanTaskInstanceDelegate.AddRecord("tokenUrl", "https://localhost:60000/token"); assignHumanTaskInstanceDelegate.AddRecord("humanTaskInstanceClaimUrl", "http://localhost:60006/humantaskinstances/{id}/force/claim"); assignHumanTaskInstanceDelegate.AddRecord("humanTaskInstanceStartUrl", "http://localhost:60006/humantaskinstances/{id}/force/start"); return(new ConcurrentBag <DelegateConfigurationAggregate> { sendEmailDelegate, updateUserPasswordDelegate, generateOTPDelegate, assignHumanTaskInstanceDelegate }); }
public static GenerateOTPPasswordParameter Create(DelegateConfigurationAggregate delegateConfiguration) { return(new GenerateOTPPasswordParameter { ClientId = delegateConfiguration.GetValue("clientId"), ClientSecret = delegateConfiguration.GetValue("clientSecret"), TokenUrl = delegateConfiguration.GetValue("tokenUrl"), UserUrl = delegateConfiguration.GetValue("userUrl"), Scope = delegateConfiguration.GetValue("scope") }); }
public static AssignHumanTaskInstanceParameter Create(DelegateConfigurationAggregate delegateConfiguration) { return(new AssignHumanTaskInstanceParameter { ClientId = delegateConfiguration.GetValue("clientId"), ClientSecret = delegateConfiguration.GetValue("clientSecret"), TokenUrl = delegateConfiguration.GetValue("tokenUrl"), HumanTaskInstanceClaimUrl = delegateConfiguration.GetValue("humanTaskInstanceClaimUrl"), HumanTaskInstanceStartUrl = delegateConfiguration.GetValue("humanTaskInstanceStartUrl") }); }
public static DelegateConfigurationResult ToDto(DelegateConfigurationAggregate configuration) { return(new DelegateConfigurationResult { Id = configuration.AggregateId, FullQualifiedName = configuration.FullQualifiedName, CreateDateTime = configuration.CreateDateTime, UpdateDateTime = configuration.UpdateDateTime, Descriptions = configuration.Descriptions.ToDictionary(d => d.Language, d => d.Value), DisplayNames = configuration.DisplayNames.ToDictionary(d => d.Language, d => d.Value), Records = configuration.Records.ToDictionary(d => d.Key, d => d.Value) }); }
public static SendDelegateParameter Build(DelegateConfigurationAggregate delegateConfiguration) { return(new SendDelegateParameter { HttpBody = delegateConfiguration.GetValue("httpBody"), Subject = delegateConfiguration.GetValue("subject"), FromEmail = delegateConfiguration.GetValue("fromEmail"), SmtpHost = delegateConfiguration.GetValue("smtpHost"), SmtpPort = delegateConfiguration.GetValueNumber("smtpPort"), SmtpUserName = delegateConfiguration.GetValue("smtpUserName"), SmtpPassword = delegateConfiguration.GetValue("smtpPassword"), SmtpEnableSsl = delegateConfiguration.GetValueBoolean("smtpEnableSsl") }); }
private FakeCaseJobServer() { _factory = new FakeHttpClientFactory(); var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(); serviceCollection.AddProcessJobServer(callbackServerOpts: o => { o.WSHumanTaskAPI = "http://localhost"; o.CallbackUrl = "http://localhost/{id}/{eltId}"; }).AddDelegateConfigurations(new ConcurrentBag <DelegateConfigurationAggregate> { DelegateConfigurationAggregate.Create("GetWeatherInformationDelegate", typeof(GetWeatherInformationDelegate).FullName) }); serviceCollection.AddSingleton <IHttpClientFactory>(_factory); _serviceProvider = serviceCollection.BuildServiceProvider(); _processInstanceCommandRepository = _serviceProvider.GetRequiredService <IProcessInstanceCommandRepository>(); _busControl = _serviceProvider.GetRequiredService <IBusControl>(); _mediator = _serviceProvider.GetRequiredService <IMediator>(); }
public void ConfigureServices(IServiceCollection services) { var files = Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "Bpmns"), "*.bpmn").ToList(); var sp = services.BuildServiceProvider(); var httpClientFactory = sp.GetRequiredService <CaseManagement.Common.Factories.IHttpClientFactory>(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCustomAuthentication(opts => { }); services.AddAuthorization(_ => { _.AddPolicy("Authenticated", p => p.RequireAuthenticatedUser()); _.AddPolicy(HumanTaskConstants.ScopeNames.ManageHumanTaskInstance, p => p.RequireAssertion(__ => true)); }); services .AddMvc(opts => opts.EnableEndpointRouting = false) .AddApplicationPart(typeof(ProcessFilesController).Assembly) .AddApplicationPart(typeof(HumanTaskDefsController).Assembly) .AddNewtonsoftJson(); services.AddLogging(); var emptyTask = HumanTaskDefBuilder.New("emptyTask") .SetTaskInitiatorUserIdentifiers(new List <string> { "thabart" }) .SetPotentialOwnerUserIdentifiers(new List <string> { "thabart" }) .Build(); var dressAppropriateForm = HumanTaskDefBuilder.New("dressAppropriateForm") .SetTaskInitiatorUserIdentifiers(new List <string> { "thabart" }) .SetPotentialOwnerUserIdentifiers(new List <string> { "thabart" }) .AddInputOperationParameter("degree", ParameterTypes.STRING, true) .AddInputOperationParameter("city", ParameterTypes.STRING, true) .Build(); var takeTemperatureForm = HumanTaskDefBuilder.New("temperatureForm") .SetTaskInitiatorUserIdentifiers(new List <string> { "thabart" }) .SetPotentialOwnerUserIdentifiers(new List <string> { "thabart" }) .AddOutputOperationParameter("degree", ParameterTypes.INT, true) .Build(); services.AddHumanTasksApi(); services.AddHumanTaskServer() .AddHumanTaskDefs(new List <HumanTaskDefinitionAggregate> { emptyTask, dressAppropriateForm, takeTemperatureForm }) .AddScheduledJobs(new List <ScheduleJob> { ScheduleJob.New <ProcessActivationTimerJob>(1 * 1000), ScheduleJob.New <ProcessDeadLinesJob>(1 * 1000) }); services.AddProcessJobServer(callbackOpts: o => { o.ApplicationAssembly = typeof(ProcessInstanceAggregate).Assembly; }, callbackServerOpts: o => { o.WSHumanTaskAPI = "http://localhost"; o.OAuthTokenEndpoint = "http://localhost/token"; o.CallbackUrl = "http://localhost/processinstances/{id}/complete/{eltId}"; }) .AddProcessFiles(files) .AddDelegateConfigurations(new ConcurrentBag <DelegateConfigurationAggregate> { DelegateConfigurationAggregate.Create("GetWeatherInformationDelegate", typeof(GetWeatherInformationDelegate).FullName) }); services.AddHostedService <HumanTaskJobServerHostedService>(); services.AddSingleton <CaseManagement.Common.Factories.IHttpClientFactory>(httpClientFactory); }
public static string Parse(DelegateConfigurationAggregate configuration, ICollection <MessageToken> incoming, string message) { var regularExpression = new Regex(@"{{([a-zA-Z]|_|\.|\(|\)|\'|\ |\,)*\}}"); var isMessageRegularExpression = new Regex(@"messages.Get\((\'([a-zA-Z]|\.|\ |\,)*\')"); var isConfigurationRegularExpression = new Regex(@"configuration.Get\((\'([a-zA-Z])*\')"); return(regularExpression.Replace(message, (m) => { if (string.IsNullOrWhiteSpace(m.Value)) { return string.Empty; } var str = m.Value.Replace("{{", ""); str = str.Replace("}}", ""); if (isMessageRegularExpression.IsMatch(str)) { str = str.Replace("messages.Get('", ""); str = str.TrimEnd(')'); str = str.Replace("'", ""); if (string.IsNullOrWhiteSpace(str)) { return null; } var parameters = str.Split(','); if (parameters.Count() != 2) { return null; } var firstParameter = parameters.First().Replace(" ", ""); var secondParameter = parameters.Last().Replace(" ", ""); var token = incoming.FirstOrDefault(i => i.Name == firstParameter); if (token == null) { return null; } if (string.IsNullOrWhiteSpace(secondParameter)) { return null; } var jsonToken = token.JObjMessageContent.SelectToken(secondParameter); if (jsonToken == null) { return null; } return jsonToken.ToString(); } if (isConfigurationRegularExpression.IsMatch(str)) { str = str.Replace("configuration.Get('", ""); str = str.TrimEnd(')'); str = str.Replace("'", ""); return configuration.GetValue(str); } return null; })); }
public async Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { var user = incoming.FirstOrDefault(i => i.Name == "user"); if (user == null) { throw new BPMNProcessorException("user must be passed in the request"); } var userId = user.GetProperty("userId"); if (string.IsNullOrWhiteSpace(userId)) { throw new BPMNProcessorException("userId is not passed in the request"); } var parameter = GenerateOTPPasswordParameter.Create(delegateConfiguration); using (var httpClient = new HttpClient()) { var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = parameter.TokenUrl, ClientId = parameter.ClientId, ClientSecret = parameter.ClientSecret, Scope = parameter.Scope }, cancellationToken); if (tokenResponse.IsError) { throw new BPMNProcessorException(tokenResponse.Error); } var url = parameter.UserUrl.Replace("{id}", userId); var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(url) }; request.Headers.Add("Authorization", $"Bearer {tokenResponse.AccessToken}"); var httpResponse = await httpClient.SendAsync(request, cancellationToken); httpResponse.EnsureSuccessStatusCode(); var content = await httpResponse.Content.ReadAsStringAsync(); var otp = long.Parse(content); ICollection <MessageToken> result = new List <MessageToken> { MessageToken.NewMessage(context.Pointer.InstanceFlowNodeId, "otp", new JObject { { "otpCode", otp } }.ToString()) }; return(result); } }
public async Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { var user = incoming.FirstOrDefault(i => i.Name == "user"); if (user == null) { throw new BPMNProcessorException("user must be passed in the request"); } var userId = user.GetProperty("userId"); if (string.IsNullOrWhiteSpace(userId)) { throw new BPMNProcessorException("userId is not passed in the request"); } var humanTaskInstanceId = incoming.First(i => i.Name == "humanTaskCreated").JObjMessageContent.SelectToken("humanTaskInstance.id").ToString(); using (var httpClient = new HttpClient()) { var parameter = AssignHumanTaskInstanceParameter.Create(delegateConfiguration); var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = parameter.TokenUrl, ClientId = parameter.ClientId, ClientSecret = parameter.ClientSecret, Scope = "manage_humantaskinstance" }, cancellationToken); await Claim(httpClient, parameter, humanTaskInstanceId, userId, tokenResponse.AccessToken, cancellationToken); await Start(httpClient, parameter, humanTaskInstanceId, userId, tokenResponse.AccessToken, cancellationToken); } ICollection <MessageToken> result = new List <MessageToken> { MessageToken.EmptyMessage(context.Pointer.InstanceFlowNodeId, "assignHumanTaskInstance") }; return(result); }
public async Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { var user = incoming.FirstOrDefault(i => i.Name == "user"); if (user == null) { throw new BPMNProcessorException("userMessage must be passed in the request"); } var userId = user.GetProperty("userId"); if (string.IsNullOrWhiteSpace(userId)) { throw new BPMNProcessorException("userId is not passed in the request"); } var messageToken = incoming.FirstOrDefault(m => m.Name == ActivityName); if (messageToken == null) { throw new BPMNProcessorException($"incoming token '{ActivityName}' doesn't exist"); } var password = messageToken.GetProperty("pwd"); var parameter = UpdateUserPasswordParameter.Create(delegateConfiguration); using (var httpClient = new HttpClient()) { var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = parameter.TokenUrl, ClientId = parameter.ClientId, ClientSecret = parameter.ClientSecret, Scope = parameter.Scope }, cancellationToken); if (tokenResponse.IsError) { throw new BPMNProcessorException(tokenResponse.Error); } var obj = new JObject { { "password", password } }; var content = new StringContent(obj.ToString(), Encoding.UTF8, "application/json"); var url = parameter.UserUrl.Replace("{id}", userId); var request = new HttpRequestMessage { Method = HttpMethod.Put, Content = content, RequestUri = new Uri(url) }; request.Headers.Add("Authorization", $"Bearer {tokenResponse.AccessToken}"); var httpResponse = await httpClient.SendAsync(request, cancellationToken); httpResponse.EnsureSuccessStatusCode(); } ICollection <MessageToken> result = new List <MessageToken> { MessageToken.EmptyMessage(context.Pointer.InstanceFlowNodeId, "updatePassword") }; return(result); }
public Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { var user = incoming.FirstOrDefault(i => i.Name == "user"); if (user == null) { throw new BPMNProcessorException("user must be passed in the request"); } var email = user.GetProperty("email"); if (string.IsNullOrWhiteSpace(email)) { throw new BPMNProcessorException("email is not passed in the request"); } var parameter = SendDelegateParameter.Build(delegateConfiguration); using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = parameter.SmtpEnableSsl; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(parameter.SmtpUserName, parameter.SmtpPassword); smtpClient.Host = parameter.SmtpHost; smtpClient.Port = parameter.SmtpPort; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; var mailMessage = new MailMessage { From = new MailAddress(parameter.FromEmail), Subject = parameter.Subject, Body = DelegateHelper.Parse(delegateConfiguration, incoming, parameter.HttpBody), IsBodyHtml = true }; mailMessage.To.Add(email.ToString()); smtpClient.Send(mailMessage); } ICollection <MessageToken> result = new List <MessageToken> { MessageToken.EmptyMessage(context.Pointer.InstanceFlowNodeId, "sendEmail") }; return(Task.FromResult(result)); }
public Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { ICollection <MessageToken> result = new List <MessageToken>(); result.Add(MessageToken.NewMessage(context.Pointer.InstanceFlowNodeId, "weatherInformation", new JObject { { "city", "Bruxelles" }, { "degree", "31" } }.ToString())); return(Task.FromResult(result)); }
public Task <bool> Update(DelegateConfigurationAggregate configuration, CancellationToken cancellationToken) { _dbContext.DelegateConfigurations.Update(configuration); return(Task.FromResult(true)); }