public static Task <HttpResponseMessage> InvokeAsync(IRef <InvocationMessage> invocationMessageRef,
                                                             IInvokeApplication invokeApplication,
                                                             ILogger logging = default)
        {
            logging.Trace($"Processing message [{invocationMessageRef.id}].");
            return(invocationMessageRef.StorageUpdateAsync(
                       async(invocationMessage, saveAsync) =>
            {
                var httpRequest = new HttpRequestMessage(
                    new HttpMethod(invocationMessage.method),
                    invocationMessage.requestUri);
                var config = new HttpConfiguration();
                httpRequest.SetConfiguration(config);

                foreach (var headerKVP in invocationMessage.headers)
                {
                    httpRequest.Headers.Add(headerKVP.Key, headerKVP.Value);
                }

                if (!invocationMessage.content.IsDefaultOrNull())
                {
                    httpRequest.Content = new ByteArrayContent(invocationMessage.content);
                    httpRequest.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                }

                invocationMessage.lastExecuted = DateTime.UtcNow;
                var result = await invokeApplication.SendAsync(httpRequest);
                await saveAsync(invocationMessage);
                return result;
            },
                       ResourceNotFoundException.StorageGetAsync <HttpResponseMessage>));
        }
Пример #2
0
 public async static Task <IHttpResponse> UpdateAsync(
     [UpdateId(Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
     [Property(Name = LocationLogoutReturnPropertyName)] Uri locationLogoutReturn,
     EastFive.Api.SessionToken?securityMaybe,
     NoContentResponse onUpdated,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized)
 {
     return(await authorizationRef.StorageUpdateAsync(
                async (authorization, saveAsync) =>
     {
         if (authorization.deleted.HasValue)
         {
             return onNotFound();
         }
         if (authorization.authorized)
         {
             authorization.LocationAuthentication = default(Uri);
             if (!securityMaybe.HasValue)
             {
                 return onUnauthorized();
             }
         }
         authorization.LocationLogoutReturn = locationLogoutReturn;
         await saveAsync(authorization);
         return onUpdated();
     },
                () => onNotFound()));
 }
Пример #3
0
        [Api.HttpPatch] //(MatchAllBodyParameters = false)]
        public async static Task <IHttpResponse> UpdateAsync(
            [Property(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef,
            [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef,
            Api.Azure.AzureApplication application, EastFive.Api.SessionToken security,
            ContentTypeResponse <XIntegration> onUpdated,
            NotFoundResponse onNotFound,
            ForbiddenResponse onForbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthorizationDoesNotExist,
            UnauthorizedResponse onUnauthorized)
        {
            return(await integrationRef.StorageUpdateAsync(
                       async (integration, saveAsync) =>
            {
                var accountId = integration.accountId;
                if (!await application.CanAdministerCredentialAsync(accountId, security))
                {
                    return onUnauthorized();
                }

                return await await authorizationRef.StorageGetAsync(
                    async authorization =>
                {
                    if (!await application.ShouldAuthorizeIntegrationAsync(integration, authorization))
                    {
                        return onForbidden().AddReason("Authorization is not accessable to this account.");
                    }

                    integration.Method = authorization.Method;         // method is used in the .mappingId
                    integration.authorization = authorizationRef.Optional();
                    integration.methodName = await Auth.Method.ById(authorization.Method,
                                                                    application,
                                                                    method => method.name,
                                                                    () => string.Empty);

                    await saveAsync(integration);
                    return onUpdated(integration);
                },
                    () => onAuthorizationDoesNotExist().AsTask());
            },
                       () => onNotFound(),
                       onModificationFailures:
                       StorageConstraintUniqueAttribute.ModificationFailure(
                           (XIntegration x) => x.authorization,
                           () =>
            {
                // TODO: Check if mapping is to this integration and reply already created.
                return onForbidden().AddReason("Authorization is already in use.");
            }).AsArray()));
        }
Пример #4
0
 public static Task <IHttpResponse> Update(
     [UpdateId] IRef <Account> accountRef,
     [Property(Name = PasswordPropertyName)] string password,
     NoContentResponse onUpdated,
     NotFoundResponse onNotFound)
 {
     return(accountRef.StorageUpdateAsync(
                async(account, saveAsync) =>
     {
         account.password = Account.GeneratePasswordHash(
             account.userIdentification, password);
         await saveAsync(account);
         return onUpdated();
     },
                () => onNotFound()));
 }
 public static Task <IHttpResponse> UpdateByIdAsync(
     [UpdateId] IRef <InvocationMessage> invocationMessageRef,
     [Property(Name = ExecutionLimitPropertyName)] int executionLimit,
     // [Resource]InvocationMessage invocationMessage,
     ContentTypeResponse <InvocationMessage> onFound,
     NotFoundResponse onNotFound)
 {
     return(invocationMessageRef.StorageUpdateAsync(
                async(invocationMessage, saveAsync) =>
     {
         invocationMessage.executionLimit = executionLimit;
         await saveAsync(invocationMessage);
         return onFound(invocationMessage);
     },
                () => onNotFound()));
 }
        [Api.HttpPatch] //(MatchAllBodyParameters = false)]
        public async static Task <HttpResponseMessage> UpdateAsync(
            [Property(Name = IntegrationIdPropertyName)] IRef <Integration> integrationRef,
            [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef,
            Api.Azure.AzureApplication application, EastFive.Api.SessionToken security,
            ContentTypeResponse <Integration> onUpdated,
            NotFoundResponse onNotFound,
            NotModifiedResponse onNotModified,
            ForbiddenResponse onForbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthenticationDoesNotExist,
            UnauthorizedResponse onUnauthorized)
        {
            return(await integrationRef.StorageUpdateAsync(
                       async (integration, saveAsync) =>
            {
                var accountId = integration.accountId;
                if (!await application.CanAdministerCredentialAsync(accountId, security))
                {
                    return onUnauthorized();
                }

                return await await authorizationRef.StorageGetAsync(
                    async authorization =>
                {
                    // TODO? This
                    // var accountIdDidMatch = await await authorization.ParseCredentailParameters(
                    integration.Method = authorization.Method;         // method is used in the .mappingId
                    integration.authorization = authorizationRef.Optional();
                    return await await SaveAuthorizationLookupAsync(integration.integrationRef, authorization.authorizationRef,
                                                                    async() =>
                    {
                        await saveAsync(integration);
                        return await SaveAccountLookupAsync(accountId, integration,
                                                            () => onUpdated(integration));
                    },
                                                                    () =>
                    {
                        // TODO: Check if mapping is to this integration and reply already created.
                        return onForbidden().AddReason("Authorization is already in use.").AsTask();
                    });
                },
                    () =>
                {
                    return onNotModified().AsTask();
                });
            },
                       () => onNotFound()));
        }
Пример #7
0
        public static async Task <HttpResponseMessage> UpdateAsync(
            [UpdateId(Name = AuthenticationPropertyName)] IRef <Authentication> authenticationRef,
            [OptionalQueryParameter(Name = "hold")] bool?hold,
            [Property(Name = UserIdentificationPropertyName)] string userIdentification,
            [Property(Name = PasswordPropertyName)] string password,
            HttpRequestMessage httpRequest,
            RedirectResponse onUpdated,
            ContentTypeResponse <string> onHeldup,
            NotFoundResponse onNotFound,
            GeneralConflictResponse onInvalidPassword)
        {
            return(await await authenticationRef.StorageUpdateAsync(
                       (authentication, saveAsync) =>
            {
                return userIdentification
                .MD5HashGuid()
                .AsRef <Account>()
                .StorageGetAsync(
                    async account =>
                {
                    var passwordHash = Account.GeneratePasswordHash(userIdentification, password);
                    if (passwordHash != account.password)
                    {
                        return onInvalidPassword("Incorrect username or password.");
                    }
                    authentication.userIdentification = userIdentification;
                    authentication.authenticated = DateTime.UtcNow;
                    await saveAsync(authentication);
                    //var related = request
                    //    .Related<Login.Redirection>();
                    //var whered = related
                    //    .Where(redir => redir.state == authentication.state);
                    //var authorizationUrl = whered
                    //    // .ById(authentication.st)
                    //    .RenderLocation();
                    var authorizationUrl = new Uri(httpRequest.RequestUri, $"/api/LoginRedirection?state={authentication.authenticationRef.id}&token={authentication.state}");

                    if (hold.HasValue && hold.Value)
                    {
                        return onHeldup(authorizationUrl.AbsoluteUri);
                    }
                    return onUpdated(authorizationUrl);
                },
                    () => onInvalidPassword("Incorrect username or password.").AsTask());
            },
                       () => onNotFound().AsTask()));
        }
Пример #8
0
 public static Task <HttpResponseMessage> UpdateBodyAsync(
     [UpdateId(Name = SessionIdPropertyName)] IRef <Session> sessionRef,
     [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
     Api.Azure.AzureApplication application,
     ContentTypeResponse <Session> onUpdated,
     NotFoundResponse onNotFound,
     ForbiddenResponse forbidden,
     ConfigurationFailureResponse onConfigurationFailure,
     GeneralConflictResponse onFailure)
 {
     return(sessionRef.StorageUpdateAsync(
                (sessionStorage, saveSessionAsync) =>
     {
         return Security.AppSettings.TokenScope.ConfigurationUri(
             scope =>
         {
             return Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes.ConfigurationDouble(
                 async(tokenExpirationInMinutes) =>
             {
                 return await await GetClaimsAsync(application, authorizationRefMaybe,
                                                   async(claims, accountIdMaybe, authorized) =>
                 {
                     sessionStorage.authorization = authorizationRefMaybe;
                     sessionStorage.authorized = authorized;
                     sessionStorage.account = accountIdMaybe;
                     return await BlackBarLabs.Security.Tokens.JwtTools.CreateToken(sessionRef.id,
                                                                                    scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims,
                                                                                    async(tokenNew) =>
                     {
                         sessionStorage.token = tokenNew;
                         await saveSessionAsync(sessionStorage);
                         return onUpdated(sessionStorage);
                     },
                                                                                    (missingConfig) => onConfigurationFailure("Missing", missingConfig).AsTask(),
                                                                                    (configName, issue) => onConfigurationFailure(configName, issue).AsTask());
                 },
                                                   why => onFailure(why).AsTask());
             },
                 why => onConfigurationFailure("Missing", why).AsTask());
         },
             (why) => onConfigurationFailure("Missing", why).AsTask());
     },
                onNotFound: () => onNotFound()));
 }
 public static Task <HttpResponseMessage> GetAsync(
     [QueryParameter(CheckFileName = true, Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     EastFive.Api.SessionToken?securityMaybe,
     ContentTypeResponse <Authorization> onFound,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     BadRequestResponse onBadRequest)
 {
     return(authorizationRef.StorageUpdateAsync(
                async(authorization, saveAsync) =>
     {
         if (authorization.deleted.HasValue)
         {
             return onNotFound();
         }
         if (authorization.authorized)
         {
             authorization.LocationAuthentication = default(Uri);
         }
         if (!securityMaybe.HasValue)
         {
             if (authorization.authorized)
             {
                 if (authorization.expired)
                 {
                     return onBadRequest();
                 }
                 if (authorization.lastModified - DateTime.UtcNow > TimeSpan.FromMinutes(1.0))
                 {
                     return onBadRequest();
                 }
                 authorization.expired = true;
                 await saveAsync(authorization);
                 return onFound(authorization);
             }
         }
         return onFound(authorization);
     },
                () => onNotFound()));
 }
Пример #10
0
        public static Task <IHttpResponse> HttpPatchAsync <TResource>(
            this IRef <TResource> resourceRef,
            MutateResource <TResource> modifyResource,
            ContentTypeResponse <TResource> onUpdated,
            NotFoundResponse onNotFound,
            Func <TResource, TResource> additionalMutations = default)
            where TResource : IReferenceable
        {
            return(resourceRef.StorageUpdateAsync(
                       async(resource, saveAsync) =>
            {
                var resourceToSave = modifyResource(resource);
                if (additionalMutations.IsNotDefaultOrNull())
                {
                    resourceToSave = additionalMutations(resourceToSave);
                }

                await saveAsync(resource);
                return onUpdated(resource);
            },
                       () => onNotFound()));
        }
Пример #11
0
        public static async Task <IHttpResponse> QueueUpBackupPartitions(
            [Property(Name = IdPropertyName)] IRef <RepositoryBackup> repositoryBackupRef,
            [Property(Name = WhenPropertyName)] DateTime when,
            RequestMessage <TableBackup> requestQuery,
            IHttpRequest request,
            EastFive.Analytics.ILogger logger,
            MultipartAsyncResponse <InvocationMessage> onQueued,
            NoContentResponse onTooEarly,
            NotFoundResponse onNotFound)
        {
            return(await repositoryBackupRef.StorageUpdateAsync(
                       async (repoBack, saveAsync) =>
            {
                var needsToRun = NCrontab.CrontabSchedule.TryParse(repoBack.frequency,
                                                                   chronSchedule =>
                {
                    var next = chronSchedule.GetNextOccurrence(repoBack.when);
                    if (when > next)
                    {
                        return true;
                    }
                    return false;
                },
                                                                   ex =>
                {
                    return false;
                });
                if (!needsToRun)
                {
                    return onTooEarly();
                }

                var includedTables = BackupFunction.DiscoverStorageResources()
                                     .Where(x => x.message.Any())
                                     .Select(x => x.tableName)
                                     .ToArray();

                CloudStorageAccount account = CloudStorageAccount
                                              .Parse(repoBack.storageSettingCopyFrom);
                CloudTableClient tableClient =
                    new CloudTableClient(account.TableEndpoint, account.Credentials);

                var tables = tableClient.GetTables();
                var resourceInfoToProcess = tables
                                            .Where(table => includedTables.Contains(table.Name, StringComparer.OrdinalIgnoreCase))
                                            .Distinct()
                                            .Select(
                    async cloudTable =>
                {
                    var tableBackup = new TableBackup()
                    {
                        tableBackupRef = Ref <TableBackup> .NewRef(),
                        backup = repositoryBackupRef,
                        tableName = cloudTable.Name,
                        when = DateTime.UtcNow,
                    };
                    var invocationMessage = await requestQuery
                                            .HttpPost(tableBackup)
                                            .CompileRequest(request)
                                            .FunctionAsync();

                    logger.Trace($"Invocation[{invocationMessage.id}] will backup table `{tableBackup.tableName}`.");
                    return invocationMessage;
                })
                                            .Await(readAhead: 10);
                repoBack.when = when;
                await saveAsync(repoBack);

                return onQueued(resourceInfoToProcess);
            },
                       () => onNotFound()));
        }
        public static Task <HttpResponseMessage> GetRedirection(
            [QueryParameter(Name = "ApiKeySecurity")] string apiSecurityKey,
            [QueryParameter(Name = "authorization")] IRef <Authorization> authRef,
            ApiSecurity apiSecurity,
            AzureApplication application,
            HttpRequestMessage request,
            RedirectResponse onRedirection,
            GeneralFailureResponse onFailure,
            UnauthorizedResponse onUnauthorized,
            ConfigurationFailureResponse onConfigFailure)
        {
            return(authRef.StorageUpdateAsync(
                       async(authorization, saveAsync) =>
            {
                var url = await await Method.ById(authorization.Method, application,
                                                  async method =>
                {
                    return await await method.ParseTokenAsync(authorization.parameters, application,
                                                              async(externalId, loginProvider) =>
                    {
                        var tag = "OpioidTool";
                        return await EastFive.Web.Configuration.Settings.GetString($"AffirmHealth.PDMS.PingRedirect.{tag}.PingAuthName",
                                                                                   async pingAuthName =>
                        {
                            return await EastFive.Web.Configuration.Settings.GetGuid($"AffirmHealth.PDMS.PingRedirect.{tag}.PingReportSetId",
                                                                                     reportSetId =>
                            {
                                var requestParams = authorization.parameters
                                                    .AppendIf("PingAuthName".PairWithValue(pingAuthName), !authorization.parameters.ContainsKey("PingAuthName"))
                                                    .AppendIf("ReportSetId".PairWithValue(reportSetId.ToString()), !authorization.parameters.ContainsKey("ReportSetId"))
                                                    .ToDictionary();

                                return Auth.Redirection.ProcessAsync(authorization,
                                                                     updatedAuth => 1.AsTask(),
                                                                     method, externalId, requestParams,
                                                                     Guid.NewGuid(), request.RequestUri, application, loginProvider,
                                                                     (uri) =>
                                {
                                    return uri;
                                },
                                                                     (why) => default(Uri),
                                                                     application.Telemetry);
                            },
                                                                                     why =>
                            {
                                return default(Uri).AsTask();
                            });
                        },
                                                                                   why =>
                        {
                            return default(Uri).AsTask();
                        });
                    },
                                                              (why) => default(Uri).AsTask());
                },
                                                  () => default(Uri).AsTask());
                if (url.IsDefaultOrNull())
                {
                    return onFailure("Failed to determine correct redirect URL");
                }

                authorization.expired = false;
                await saveAsync(authorization);
                return onRedirection(url);
            }));
        }
Пример #13
0
        public static async Task <IHttpResponse> UpdateAsync(
            [WorkflowParameterFromVariable(
                 Value = Workflows.PasswordLoginCreateAccount.Variables.Authorization)]
            [UpdateId(Name = AuthenticationPropertyName)]
            IRef <Authentication> authenticationRef,

            [WorkflowParameter(Value = "true")]
            [OptionalQueryParameter(Name = "hold")]
            bool?hold,

            [WorkflowParameterFromVariable(
                 Value = Workflows.PasswordLoginCreateAccount.Variables.UserId)]
            [Property(Name = UserIdentificationPropertyName)]
            string userIdentification,

            [WorkflowParameterFromVariable(
                 Value = Workflows.PasswordLoginCreateAccount.Variables.Password)]
            [Property(Name = PasswordPropertyName)]
            string password,

            [WorkflowHeaderRequired("Accept", "application/json")]
            Microsoft.Net.Http.Headers.MediaTypeHeaderValue[] acceptsTypes,

            IHttpRequest httpRequest,
            RedirectResponse onUpdated,

            [WorkflowVariable(Workflows.PasswordLoginCreateAccount.Variables.State, AuthorizationPropertyName)]
            [WorkflowVariable2(Workflows.PasswordLoginCreateAccount.Variables.Token, "token")]
            ContentTypeResponse <AuthorizationParameters> onJsonPreferred,

            ContentTypeResponse <string> onHeldup,
            NotFoundResponse onNotFound,
            GeneralConflictResponse onInvalidPassword)
        {
            return(await authenticationRef.StorageUpdateAsync(
                       async (authentication, saveAsync) =>
            {
                return await await CheckCredentialsAsync(userIdentification, password,
                                                         async(account) =>
                {
                    authentication.userIdentification = userIdentification;
                    authentication.authenticated = DateTime.UtcNow;
                    await saveAsync(authentication);
                    var authorizationUrl = new Uri(httpRequest.RequestUri, $"/api/LoginRedirection?state={authentication.authenticationRef.id}&token={authentication.token}");

                    if (hold.HasValue && hold.Value)
                    {
                        if (acceptsTypes.Any(hdr => "application/json".Equals(hdr.MediaType.ToString(), StringComparison.OrdinalIgnoreCase)))
                        {
                            var authorizationParameters = new AuthorizationParameters
                            {
                                state = authentication.authenticationRef,
                                token = authentication.token,
                            };
                            return onJsonPreferred(authorizationParameters);
                        }
                        return onHeldup(authorizationUrl.AbsoluteUri);
                    }
                    return onUpdated(authorizationUrl);
                },
                                                         why => onInvalidPassword(why).AsTask());
            },
                       () => onNotFound()));
        }