public static async Task <HttpResponseMessage> GetAllSecureAsync(
     [QueryParameter(Name = "ApiKeySecurity")] string apiSecurityKey,
     [QueryParameter(Name = "authorization")] IRef <Authorization> authorizationRef,
     ApiSecurity apiSecurity,
     AzureApplication application,
     HttpRequestMessage request,
     MultipartResponseAsync <Authorization> onContent,
     RedirectResponse onSuccess,
     NotFoundResponse onNotFound,
     ForbiddenResponse onFailure)
 {
     return(await await authorizationRef.StorageGetAsync(
                async authorization =>
     {
         return await await Method.ById(authorization.Method, application,
                                        async method =>
         {
             return await await method.ParseTokenAsync(authorization.parameters, application,
                                                       (externalId, loginProvider) =>
             {
                 return Auth.Redirection.ProcessAsync(authorization,
                                                      async updatedAuth =>
                 {
                 }, method, externalId, authorization.parameters,
                                                      Guid.NewGuid(), request.RequestUri, application, loginProvider,
                                                      (uri) => onSuccess(uri),
                                                      (why) => onFailure().AddReason(why),
                                                      application.Telemetry);
             },
                                                       why => onFailure().AddReason(why).AsTask());
         },
                                        () => onFailure().AddReason("Method no longer supported").AsTask());
     },
                () => onNotFound().AsTask()));
 }
        //private static Task<TResult> UnmappedCredentialAsync<TResult>(
        //        string subject, IDictionary<string, string> extraParams,
        //        EastFive.Azure.Auth.Method authentication, Authorization authorization,
        //        IProvideAuthorization authorizationProvider,
        //        IAuthApplication application,
        //        Uri baseUri,
        //    Func<Guid, TResult> createMapping,
        //    Func<TResult> onAllowSelfServe,
        //    Func<Uri, TResult> onInterceptProcess,
        //    Func<string, TResult> onFailure,
        //    TelemetryClient telemetry)
        //{
        //    return application.OnUnmappedUserAsync(subject, extraParams,
        //            authentication, authorization, authorizationProvider, baseUri,
        //        (accountId) => createMapping(accountId),
        //        () => onAllowSelfServe(),
        //        (callback) => onInterceptProcess(callback),
        //        () =>
        //        {
        //            var message = "Token is not connected to a user in this system";
        //            telemetry.TrackException(new ResponseException(message));
        //            return onFailure(message);
        //        });
        //}

        public static async Task <TResult> MapAccountAsync <TResult>(Authorization authorization,
                                                                     Guid internalAccountId, string externalAccountKey,
                                                                     IInvokeApplication endpoints,
                                                                     Uri baseUri,
                                                                     AzureApplication application, IHttpRequest request,
                                                                     Func <Uri, TResult> onRedirect,
                                                                     Func <string, TResult> onFailure,
                                                                     TelemetryClient telemetry)
        {
            // applies when intercept process is used
            if (authorization.accountIdMaybe.IsDefault())
            {
                authorization = await authorization.authorizationRef.StorageUpdateAsync(
                    async (a, saveAsync) =>
                {
                    a.accountIdMaybe = internalAccountId;
                    await saveAsync(a);
                    return(a);
                });
            }

            return(await await AccountMapping.CreateByMethodAndKeyAsync(authorization, externalAccountKey,
                                                                        internalAccountId,
                                                                        ProcessAsync,
                                                                        ProcessAsync));

            async Task <TResult> ProcessAsync()
            {
                return(await await Method.ById(authorization.Method, application,
                                               async method =>
                {
                    return await await method.GetLoginProviderAsync(application,
                                                                    (loginProviderMethodName, loginProvider) =>
                    {
                        return CreateLoginResponseAsync(
                            internalAccountId, authorization.parameters,
                            method, authorization,
                            application, request, endpoints, baseUri, loginProvider,
                            (url, modifier) => onRedirect(url),
                            onFailure,
                            telemetry);
                    },
                                                                    () =>
                    {
                        return onFailure("Login provider is no longer supported by the system").AsTask();
                    });
                },
                                               () => onFailure("Method no longer suppored.").AsTask()));
            }
        }
Exemple #3
0
        public static async Task <IHttpResponse> LaunchAsync(

            [Api.Meta.Flows.WorkflowParameter(Value = "{{AuthenticationMethod}}")]
            [QueryParameter(Name = "method")] IRef <Method> methodRef,

            RequestMessage <AccountRequest> api,
            IHttpRequest request,
            IAzureApplication application,
            IProvideUrl urlHelper,
            [Api.Meta.Flows.WorkflowVariableRedirectUrl(
                 VariableName = Workflows.AuthorizationFlow.Variables.RedirectUrl)]
            RedirectResponse onLaunched,
            BadRequestResponse onInvalidMethod)
        {
            return(await await Method.ById(methodRef, application,
                                           async method =>
            {
                var authRef = Ref <Authorization> .SecureRef();
                var authorization = new Authorization
                {
                    authorizationRef = authRef,
                    LocationAuthenticationReturn = api
                                                   // .Where(query => query.authorization == authRef)
                                                   .HttpAction(ResponseAction)
                                                   .CompileRequest(request)
                                                   .RequestUri,
                    Method = methodRef,
                };

                return await await authorization.StorageCreateAsync(
                    async(discard) =>
                {
                    var redir = await method.GetLoginUrlAsync(
                        application, urlHelper, authRef.id);
                    return onLaunched(redir);
                });
            },
                                           () => onInvalidMethod().AsTask()));
        }
 public static async Task <TResult> MapAccountAsync <TResult>(Authorization authorization,
                                                              Guid internalAccountId, string externalAccountKey,
                                                              Guid requestId,
                                                              Uri baseUri,
                                                              AzureApplication application,
                                                              Func <Uri, TResult> onRedirect,
                                                              Func <string, TResult> onFailure,
                                                              TelemetryClient telemetry)
 {
     return(await await AccountMapping.CreateByMethodAndKeyAsync(authorization, externalAccountKey,
                                                                 internalAccountId,
                                                                 async() =>
     {
         return await await Method.ById(authorization.Method, application,
                                        async method =>
         {
             return await await method.GetLoginProviderAsync(application,
                                                             (loginProviderMethodName, loginProvider) =>
             {
                 return CreateLoginResponseAsync(requestId,
                                                 internalAccountId, authorization.parameters,
                                                 method, authorization,
                                                 baseUri,
                                                 application, loginProvider,
                                                 (url) => onRedirect(url),
                                                 onFailure,
                                                 telemetry);
             },
                                                             () =>
             {
                 return onFailure("Login provider is no longer supported by the system").AsTask();
             });
         },
                                        () => onFailure("Method no longer suppored.").AsTask());
     },
                                                                 (why) => onFailure(why).AsTask()));
 }
Exemple #5
0
 private static async Task <TResult> GetSessionAcountAsync <TResult>(IRef <Authorization> authorizationRef,
                                                                     Api.Azure.AzureApplication application,
                                                                     Func <Guid, bool, TResult> onSuccess,
                                                                     Func <string, bool, TResult> onFailure)
 {
     return(await await authorizationRef.StorageGetAsync(
                async (authorization) =>
     {
         var methodRef = authorization.Method;
         return await await Method.ById(methodRef, application,
                                        async method =>
         {
             return await await method.GetAuthorizationKeyAsync(application, authorization.parameters,
                                                                (externalUserKey) =>
             {
                 return Auth.AccountMapping.FindByMethodAndKeyAsync(method.authenticationId, externalUserKey,
                                                                    authorization,
                                                                    accountId => onSuccess(accountId, authorization.authorized),
                                                                    () => onFailure("No mapping to that account.", authorization.authorized));
             },
                                                                (why) => onFailure(why, authorization.authorized).AsTask(),
                                                                () => onFailure("This login method is no longer supported.", false).AsTask());
         },
                                        () =>
         {
             return CheckSuperAdminBeforeFailure(authorizationRef,
                                                 "Authorization method is no longer valid on this system.", authorization.authorized,
                                                 onSuccess, onFailure).AsTask();
         });
     },
                () =>
     {
         return CheckSuperAdminBeforeFailure(authorizationRef, "Authorization not found.", false,
                                             onSuccess, onFailure).AsTask();
     }));
 }
        public async static Task <HttpResponseMessage> GetAllSecureAsync(
            [QueryParameter(Name = "ApiKeySecurity")] string apiSecurityKey,
            [QueryParameter(Name = "method")] IRef <Method> methodRef,
            [OptionalQueryParameter(Name = "successOnly")] bool successOnly,
            ApiSecurity apiSecurity,
            AzureApplication application,
            HttpRequestMessage request,
            ContentTypeResponse <RedirectionManager[]> onContent,
            UnauthorizedResponse onUnauthorized,
            ConfigurationFailureResponse onConfigFailure)
        {
            Expression <Func <Authorization, bool> > allQuery =
                (authorization) => true;
            var redirections = await allQuery
                               .StorageQuery()
                               .Where(authorization => !authorization.Method.IsDefaultOrNull())
                               .Where(authorization => authorization.Method.id == methodRef.id)
                               .Select <Authorization, Task <RedirectionManager?> >(
                async authorization =>
            {
                RedirectionManager?Failure(string why)
                {
                    if (successOnly)
                    {
                        return(default(RedirectionManager?));
                    }

                    return(new RedirectionManager
                    {
                        authorization = authorization.authorizationRef.Optional(),
                        message = why,
                        when = authorization.lastModified
                    });
                }

                return(await await Method.ById <Task <RedirectionManager?> >(authorization.Method, application,
                                                                             async method =>
                {
                    return await method.ParseTokenAsync(authorization.parameters, application,
                                                        (externalId, loginProvider) =>
                    {
                        return new RedirectionManager
                        {
                            when = authorization.lastModified,
                            message = $"Ready:{externalId}",
                            authorization = authorization.authorizationRef.Optional(),
                            redirection = new Uri(
                                request.RequestUri,
                                $"/api/RedirectionManager?ApiKeySecurity={apiSecurityKey}&authorization={authorization.id}"),
                        };
                    },
                                                        (why) => Failure(why));
                },
                                                                             () => Failure("Method no longer supported").AsTask()));
            })
                               //Parallel()
                               .Throttle()
                               .SelectWhereHasValue()
                               .OrderByDescendingAsync(item => item.when);

            return(onContent(redirections.ToArray()));
        }
        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);
            }));
        }
Exemple #8
0
        public async static Task <IHttpResponse> GetAllSecureAsync(

            [Api.Meta.Flows.WorkflowParameter(Value = "{{AuthenticationMethod}}")]
            [QueryParameter(Name = "method")]
            IRef <Method> methodRef,

            [OptionalQueryParameter(Name = "successOnly")] bool successOnly,

            [Api.Meta.Flows.WorkflowParameter(Description = "ACP,Dash,TCM,HUDDLE", Value = "")]
            [OptionalQueryParameter(Name = "search")]
            string search,

            [OptionalQueryParameter(Name = "months")] int?monthsMaybe,
            AzureApplication application,
            EastFive.Api.Security security,
            IHttpRequest request,

            [Api.Meta.Flows.WorkflowVariable(AuthorizationPropertyName, "authorization{0}")]
            ContentTypeResponse <RedirectionManager[]> onContent,
            UnauthorizedResponse onUnauthorized,
            ConfigurationFailureResponse onConfigFailure,
            BadRequestResponse onBadRequest)
        {
            // this query is faster than the version commented out below
            var methodMaybe = await Method.ById(methodRef, application, (m) => m, () => default(Method?));

            if (methodMaybe.IsDefault())
            {
                return(onBadRequest().AddReason("Method no longer supported"));
            }
            var method = methodMaybe.Value;

            var months = monthsMaybe.HasValue ? Math.Abs(monthsMaybe.Value) : 1;
            var since  = DateTime.UtcNow.Date.AddMonths(-months);
            var query  = new TableQuery <GenericTableEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.GenerateFilterConditionForGuid("method", QueryComparisons.Equal, method.id),
                    TableOperators.And,
                    TableQuery.CombineFilters(
                        TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, since),
                        TableOperators.And,
                        TableQuery.GenerateFilterConditionForBool("authorized", QueryComparisons.Equal, true)
                        )
                    )
                );
            var table = EastFive.Azure.Persistence.AppSettings.Storage.ConfigurationString(
                (conn) =>
            {
                var account = CloudStorageAccount.Parse(conn);
                var client  = account.CreateCloudTableClient();
                return(client.GetTableReference("authorization"));
            },
                (why) => throw new Exception(why));

            var segment      = default(TableQuerySegment <GenericTableEntity>);
            var token        = default(TableContinuationToken);
            var redirections = new RedirectionManager[] { };

            do
            {
                segment = await table.ExecuteQuerySegmentedAsync(query, token);

                token = segment.ContinuationToken;
                var result = await segment.Results
                             .Select(
                    async (entity) =>
                {
                    var id          = Guid.Parse(entity.RowKey);
                    var when        = entity.Timestamp.DateTime;
                    var props       = entity.WriteEntity(default);