public static IHttpResponse GetAsync(
            IApplication application,
            ContentTypeResponse <Configuration[]> onFound)
        {
            var configs = application.ConfigurationTypes
                          .SelectMany(configurationType =>
                                      configurationType.Key.GetFields(BindingFlags.Public |
                                                                      BindingFlags.Static | BindingFlags.FlattenHierarchy)
                                      .Where(member => member.ContainsCustomAttribute <ConfigKeyAttribute>())
                                      .Select(member => member.GetCustomAttribute <ConfigKeyAttribute>().PairWithKey(member)))
                          .Select(
                memberAttrKvp =>
            {
                var member = memberAttrKvp.Key;
                var attr   = memberAttrKvp.Value;
                return(new Configuration()
                {
                    deploymentOverride = attr.DeploymentOverride,
                    deploymentSecurityConcern = attr.DeploymentSecurityConcern,
                    description = attr.Description,
                    location = attr.Location,
                    moreInfo = attr.MoreInfo,
                    name = $"{member.DeclaringType.FullName}.{member.Name}",
                    PrivateRepositoryOnly = attr.PrivateRepositoryOnly,
                    type = member.GetMemberType(),
                    value = (member.GetValue(null) as string).ConfigurationString(
                        v => v,
                        why => "Not defined"),
                });
            })
                          .ToArray();

            return(onFound(configs));
        }
        public async static Task <IHttpResponse> GetByIdAsync(
            [QueryParameter(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef,
            IAuthApplication application, SessionToken security,
            ContentTypeResponse <XIntegration> onFound,
            NotFoundResponse onNotFound,
            UnauthorizedResponse onUnauthorized)
        {
            if (!security.accountIdMaybe.HasValue)
            {
                return(onUnauthorized());
            }
            var accountId = security.accountIdMaybe.Value;

            return(await await integrationRef.StorageGetAsync(
                       integration =>
            {
                return Auth.Method.ById(integration.Method,
                                        application,
                                        method =>
                {
                    integration.methodName = method.name;
                    return onFound(integration);
                },
                                        () => onNotFound());
            },
                       () => onNotFound().AsTask()));
        }
        public static Task <IHttpResponse> WebhookAsync(
            [Resource] object appInsightsCallback,
            ContentTypeResponse <EventsExceptionResult[]> onResults)
        {
            return(AppSettings.ApplicationInsights.ApplicationId.ConfigurationString(
                       applicationId =>
            {
                return AppSettings.ApplicationInsights.ClientSecret.ConfigurationString(
                    async token =>
                {
                    // Authenticate with client secret (app key)
                    var clientCred = new ApiKeyClientCredentials(token);

                    // New up a client with credentials and AI application Id
                    var client = new ApplicationInsightsDataClient(clientCred);
                    client.AppId = applicationId;

                    var exceptionEvents = await client.GetExceptionEventsAsync(
                        timespan: TimeSpan.FromMinutes(240.0),
                        top: 10,
                        format: "application/json;odata.metadata=full");
                    var requestEvents = await client.GetRequestEventsAsync(
                        timespan: TimeSpan.FromMinutes(30.0));

                    return onResults(exceptionEvents.Value.ToArray());
                });
            }));
        }
        [Api.HttpGet] //(MatchAllBodyParameters = false)]
        public static async Task <HttpResponseMessage> GetAsync(
            EastFive.Api.SessionToken security,
            Api.Azure.AzureApplication application, UrlHelper urlHelper,
            ContentTypeResponse <Whoami> onFound)
        {
            async Task <string> GetName()
            {
                if (!security.accountIdMaybe.HasValue)
                {
                    return(string.Empty);
                }
                return(await application.GetActorNameDetailsAsync(security.accountIdMaybe.Value,
                                                                  (first, last, email) =>
                {
                    return $"{first} {last} [{email}]";
                },
                                                                  () => string.Empty));
            }

            var whoami = new Whoami()
            {
                session = security.sessionId.AsRef <Session>(),
                account = security.accountIdMaybe,
                name    = await GetName(),
            };

            return(onFound(whoami));
        }
Beispiel #5
0
        public static IHttpResponse FindAsync(
            //Security security,
            HttpApplication application, IHttpRequest request, IProvideUrl url,
            ContentTypeResponse <WebIdManifest> onFound,
            ContentTypeResponse <Api.Resources.Manifest> onContent,
            ViewFileResponse <Api.Resources.Manifest> onHtml)
        {
            if (request.GetAcceptTypes().Where(accept => accept.MediaType.ToLower().Contains("html")).Any())
            {
                return(HtmlContent(application, request, url, onHtml));
            }

            LocateControllers();
            var endpoints = Manifest.lookup
                            .Select(
                type =>
            {
                var endpoint = url.GetWebId(type, "x-com.orderowl:ordering");
                return(endpoint);
            })
                            .ToArray();

            var manifest = new WebIdManifest()
            {
                Id        = Guid.NewGuid(),
                Endpoints = endpoints,
            };

            return(onFound(manifest));
        }
 public static async Task <IHttpResponse> SendToPostman(
     [QueryId] IRef <MonitoringRequest> monitoringRequestRef,
     [QueryParameter(Name = WhenPropertyName)] DateTime when,
     Security security,
     ContentTypeResponse <Meta.Postman.Resources.Collection.Item> onContent,
     NotFoundResponse onNotFound,
     GeneralFailureResponse onFailure)
 {
     return(await await monitoringRequestRef
            .StorageGetAsync(
                additionalProperties : (query) => query.Where(item => item.when == when),
                onFound : async itemToCreateOrUpdate =>
     {
         var postmanItem = await itemToCreateOrUpdate.ConvertToPostmanItemAsync();
         return await Collection.CreateOrUpdateMonitoringCollectionAsync(
             $"MonitoringRequest - {itemToCreateOrUpdate.when}", itemToCreateOrUpdate.url,
             collectionToModify =>
         {
             return collectionToModify
             .AppendItem(postmanItem, folderName: itemToCreateOrUpdate.folderName);
         },
             onCreatedOrUpdated: (discard) => onContent(postmanItem),
             onFailure: why => onFailure(why));
     },
                onDoesNotExists : () => onNotFound().AsTask()));
 }
        private ContentResult GetContent <T>(T data, ContentTypeResponse contentType)
        {
            if (data == null)
            {
                return(Content(""));
            }

            try
            {
                if (Request.Headers["Accept"] != null && Request.Headers["Accept"].IndexOf("application/xml", StringComparison.Ordinal) > -1)
                {
                    return(Content(GetXml(data), "application/xml"));
                }

                switch (contentType)
                {
                case ContentTypeResponse.JSON:
                    return(Content(GetJson(data), "application/json"));

                case ContentTypeResponse.XML:
                    return(Content(GetXml(data), "application/xml"));

                default:
                    return(Content(string.Empty));
                }
            }
            catch
            {
                return(GetContent(new { Message = data.ToString() }, contentType));
            }
        }
        public static IHttpResponse ListFlows(
            [OptionalQueryParameter] string flow,
            [OptionalQueryParameter] string collections,
            [OptionalQueryParameter] bool?preferJson,
            //Security security,
            IInvokeApplication invokeApplication,
            HttpApplication httpApp, IHttpRequest request, IProvideUrl url,
            ContentTypeResponse <string []> onSuccess,
            NotFoundResponse onNotFound)
        {
            var lookups = httpApp
                          .GetResources()
                          .ToArray();

            var manifest = new EastFive.Api.Resources.Manifest(lookups, httpApp);

            var flows = manifest.Routes
                        .SelectMany(route => route.Methods)
                        .SelectMany(method => method.MethodPoco
                                    .GetAttributesInterface <IDefineFlow>(multiple: true)
                                    .Select(attr => (method, attr)))
                        .GroupBy(methodAndFlow => methodAndFlow.attr.FlowName)
                        .Where(grp => grp.Key.HasBlackSpace())
                        .Select(grp => grp.Key)
                        .ToArray();

            return(onSuccess(flows));
        }
Beispiel #9
0
 public static Task <IHttpResponse> QueryByIdAsync(
     [QueryId(Name = IdPropertyName)] IRef <Profile> profileRef,
     ContentTypeResponse <Profile> onFound,
     NotFoundResponse onNotFound)
 {
     return(profileRef.HttpGetAsync(onFound, onNotFound));
 }
Beispiel #10
0
        [Api.HttpGet] //(MatchAllBodyParameters = false)]
        public static async Task <IHttpResponse> GetAsync(
            EastFive.Api.SessionToken security,
            IHttpRequest request,
            IAuthApplication application,

            [WorkflowVariable("Session", SessionPropertyName)]
            [WorkflowVariable2("Account", AccountPropertyName)]
            ContentTypeResponse <Whoami> onFound)
        {
            async Task <string> GetName()
            {
                if (!security.accountIdMaybe.HasValue)
                {
                    return(string.Empty);
                }
                return(await application.GetActorNameDetailsAsync(security.accountIdMaybe.Value,
                                                                  (first, last, email) =>
                {
                    return $"{first} {last} [{email}]";
                },
                                                                  () => string.Empty));
            }

            request.TryParseJwt(out System.IdentityModel.Tokens.Jwt.JwtSecurityToken securityToken);
            var whoami = new Whoami()
            {
                session       = security.sessionId.AsRef <Session>(),
                account       = security.accountIdMaybe,
                name          = await GetName(),
                securityToken = securityToken,
            };

            return(onFound(whoami));
        }
        public static async Task <IHttpResponse> SendCollectionToPostman(
            [WorkflowParameterFromVariable(Value =
                                               EastFive.Azure.Workflows.MonitoringFlow.Variables.FolderName)]
            [QueryParameter(Name = FolderNamePropertyName)] string folderName,

            [OptionalQueryParameter(Name = WhenPropertyName)] DateTime?whenMaybe,
            IHttpRequest httpRequest,
            Security security,
            ContentTypeResponse <CollectionSummary> onPosted,
            GeneralFailureResponse onFailure)
        {
            //var postmanItems = await when
            //    .StorageGetBy((MonitoringRequest mr) => mr.when)
            //    .Where(mr => String.Equals(mr.folderName, folderName, StringComparison.CurrentCultureIgnoreCase))
            //    .Select(mr => mr.ConvertToPostmanItemAsync())
            //    .Await()
            //    .ToArrayAsync();

            var postmanItems = await folderName
                               .StorageGetBy((MonitoringRequest mr) => mr.folderName)
                               .Where(mr => whenMaybe.HasValue? whenMaybe.EqualToDay(mr.when) : true)
                               .Select(mr => mr.ConvertToPostmanItemAsync())
                               .Await()
                               .ToArrayAsync();

            return(await Collection.CreateOrUpdateMonitoringCollectionAsync(
                       $"MonitoringRequest - {folderName}", httpRequest.RequestUri,
                       collectionToModify =>
            {
                return collectionToModify
                .AppendItems(postmanItems, folderName: folderName);
            },
                       onCreatedOrUpdated : (collection) => onPosted(collection),
                       why => onFailure(why)));
        }
Beispiel #12
0
        public static async Task <IHttpResponse> GetAsync(
            [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef,
            EastFive.Api.SessionTokenMaybe security,
            IAuthApplication application,
            ContentTypeResponse <Session> onFound,
            NotFoundResponse onNotFound,
            UnauthorizedResponse onUnauthorized,
            ConfigurationFailureResponse onConfigurationFailure)
        {
            if (!IsAnonSessionAllowed())
            {
                if (security.sessionId != sessionRef.id)
                {
                    return(onUnauthorized());
                }
            }
            return(await await sessionRef.StorageGetAsync(
                       (session) =>
            {
                return Web.Configuration.Settings.GetUri(
                    EastFive.Security.AppSettings.TokenScope,
                    scope =>
                {
                    return Web.Configuration.Settings.GetDouble(Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes,
                                                                (tokenExpirationInMinutes) =>
                    {
                        return GetClaimsAsync(application, session.authorization,
                                              (claims, accountIdMaybe, authorized) =>
                        {
                            session.account = accountIdMaybe;
                            session.authorized = authorized;
                            return Api.Auth.JwtTools.CreateToken(session.id,
                                                                 scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims,
                                                                 (tokenNew) =>
                            {
                                session.token = tokenNew;
                                return onFound(session);
                            },
                                                                 (missingConfig) => onConfigurationFailure("Missing", missingConfig),
                                                                 (configName, issue) => onConfigurationFailure(configName, issue));
                        },
                                              (why) => onNotFound());
                    },
                                                                (why) => onConfigurationFailure("Missing", why).AsTask());
                },
                    (why) => onConfigurationFailure("Missing", why).AsTask());
            },
                       () => onNotFound().AsTask()));

            bool IsAnonSessionAllowed()
            {
                var appType = application.GetType();

                if (!appType.TryGetAttributeInterface <IConfigureAuthorization>(out IConfigureAuthorization authConfig))
                {
                    return(false);
                }
                return(authConfig.IsAnonymousSessionAllowed);
            }
        }
 public static async Task <IHttpResponse> PropertyInformation(
     [QueryParameter(Name = "table")] string tableName,
     [QueryParameter(Name = "property")] string propertyName,
     IApplication httpApp,
     ContentTypeResponse <PropertyLookupInformation[]> onFound,
     NotFoundResponse onNotFound,
     BadRequestResponse onPropertyDoesNotSupportFindBy)
 {
     return(await StorageTable.DiscoverStorageResources(httpApp.GetType())
            .Where(table => table.name == tableName)
            .First(
                (storageTable, next) =>
     {
         return storageTable.properties
         .Where(prop => prop.name == propertyName)
         .First(
             async(prop, next2) =>
         {
             if (!prop.member.ContainsAttributeInterface <IProvideFindBy>())
             {
                 return onPropertyDoesNotSupportFindBy();
             }
             var findBy = prop.member.GetAttributeInterface <IProvideFindBy>();
             var information = await findBy.GetInfoAsync(prop.member);
             return onFound(information);
         },
             () => onNotFound().AsTask());
     },
                () => onNotFound().AsTask()));
 }
        public static IHttpResponse All(
            HttpApplication httpApp,
            ContentTypeResponse <StorageTable[]> onFound)
        {
            var tables = DiscoverStorageResources(httpApp.GetType()).ToArray();

            return(onFound(tables));
        }
Beispiel #15
0
        public static IHttpResponse ManifestContent(
            HttpApplication httpApp, System.Net.Http.HttpRequestMessage request, IProvideUrl url,
            ContentTypeResponse <Api.Resources.Manifest> onContent)
        {
            var lookups  = httpApp.GetResources();
            var manifest = new EastFive.Api.Resources.Manifest(lookups, httpApp);

            return(onContent(manifest));
        }
Beispiel #16
0
        public static IHttpResponse FindAsync(
            IApplication app,
            ContentTypeResponse <Route[]> onContent)
        {
            var lookups  = app.Resources.Select(res => res.type).ToArray();
            var manifest = new Manifest(lookups, app as HttpApplication);

            return(onContent(manifest.Routes));
        }
 public static Task <IHttpResponse> GetByIdAsync(
     [QueryId] IRef <InvocationMessage> invocationMessageRef,
     ContentTypeResponse <InvocationMessage> onFound,
     NotFoundResponse onNotFound)
 {
     return(invocationMessageRef.StorageGetAsync(
                (InvocationMessage ent) => onFound(ent),
                () => onNotFound()));
 }
 public static Task <HttpResponseMessage> QueryByIdAsync(
     [QueryId] IRef <Method> methodRef,
     Api.Azure.AzureApplication application,
     ContentTypeResponse <Method> onFound,
     NotFoundResponse onNotFound)
 {
     return(ById(methodRef, application,
                 method => onFound(method),
                 () => onNotFound()));
 }
Beispiel #19
0
        public static async Task <IHttpResponse> LoadAsync(
            RequestMessage <TeamsNotification> teamsNotificationsStorage,
            ContentTypeResponse <TeamsNotification[]> onFound)
        {
            teamsNotifications = await teamsNotificationsStorage
                                 .StorageGet()
                                 .ToArrayAsync();

            return(onFound(teamsNotifications));
        }
        public static async Task <IHttpResponse> ClearPostmanAsync(
            [WorkflowParameterFromVariable(
                 Value = EastFive.Azure.Workflows.MonitoringFlow.Variables.FolderName,
                 Disabled = true)]
            [OptionalQueryParameter(Name = TeamsNotification.CollectionPropertyName)]
            string collectionFolder,
            Security security,
            ContentTypeResponse <CollectionSummary> onCleared,
            NotFoundResponse onNotFound,
            GeneralFailureResponse onFailure)
        {
            return(await EastFive.Api.AppSettings.Postman.MonitoringCollectionId.ConfigurationString(
                       async collectionId =>
            {
                return await await EastFive.Api.Meta.Postman.Resources.Collection.Collection.GetAsync(collectionId,
                                                                                                      collection =>
                {
                    var collectionCleared = collectionFolder.HasBlackSpace() ?
                                            MutateCollectionWithFolderName(collectionFolder)
                                :
                                            MutateCollection();
                    return collectionCleared.UpdateAsync <IHttpResponse>(
                        (updatedCollection) =>
                    {
                        return onCleared(updatedCollection);
                    },
                        onFailure: (why) => onFailure(why));

                    Collection MutateCollection()
                    {
                        return new Collection
                        {
                            info = collection.info,
                            item = new Item[] { },
                            variable = collection.variable,
                        };
                    }

                    Collection MutateCollectionWithFolderName(string folderName)
                    {
                        collection.item = collection.item
                                          .NullToEmpty()
                                          .Where(item => !collectionFolder.Equals(item.name))
                                          .ToArray();
                        return collection;
                    }
                },
                                                                                                      () => onNotFound().AsTask(),
                                                                                                      onFailure: why => onFailure(why).AsTask());
            },
                       onUnspecified : (why) => onFailure("Postman Monitoring not setup").AsTask()));
        }
 public static Task <IHttpResponse> GetByIdAsync(
     [QueryId] IRef <MonitoringRequest> monitoringRequestRef,
     [QueryParameter(Name = WhenPropertyName)] DateTime when,
     Security security,
     ContentTypeResponse <MonitoringRequest> onContent,
     NotFoundResponse onNotFound)
 {
     return(monitoringRequestRef
            .StorageGetAsync(
                additionalProperties: (query) => query.Where(item => item.when == when),
                onFound: mr => onContent(mr),
                onDoesNotExists: () => onNotFound()));
 }
Beispiel #22
0
 public static Task <IHttpResponse> UpdateAsync(
     [WorkflowParameter(Value = "{{TeamsNotification}}")]
     [UpdateId] IRef <TeamsNotification> teamsNotificationRef,
     [MutateResource] MutateResource <TeamsNotification> updated,
     ContentTypeResponse <TeamsNotification> onUpdated,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized)
 {
     return(teamsNotificationRef
            .HttpPatchAsync(updated,
                            onUpdated,
                            onNotFound));
 }
        public static async Task <IHttpResponse> ReplayAsync(
            [QueryId(Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
            Api.Azure.AzureApplication application,
            IInvokeApplication endpoints,
            IHttpRequest request,
            ContentTypeResponse <Session> onReplayed,
            NotFoundResponse onNotFound,
            ForbiddenResponse onAuthorizationFailed,
            ServiceUnavailableResponse onServericeUnavailable,
            ForbiddenResponse onInvalidMethod,
            GeneralConflictResponse onFailure)
        {
            return(await await authorizationRef.StorageGetAsync(
                       async (authorization) =>
            {
                var methodRef = authorization.Method;
                return await await Auth.Method.ById(methodRef, application,
                                                    async(method) =>
                {
                    var paramsUpdated = authorization.parameters
                                        .Append(authorizationRef.id.ToString().PairWithKey("state"))
                                        .ToDictionary();

                    //var authorizationRequestManager = application.AuthorizationRequestManager;
                    return await await Redirection.AuthenticationAsync(
                        method,
                        paramsUpdated,
                        application, request,
                        endpoints,
                        request.RequestUri,
                        authorizationRef.Optional(),
                        async(redirect, accountIdMaybe, modifier) =>
                    {
                        var sessionRef = Ref <Session> .SecureRef();
                        var session = new Session()
                        {
                            sessionId = sessionRef,
                            account = accountIdMaybe,
                            authorization = authorizationRef.Optional(),
                        };
                        var responseCreated = await Session.CreateAsync(sessionRef, authorizationRef.Optional(),
                                                                        session,
                                                                        application,
                                                                        (sessionCreated, contentType) =>
                        {
                            var response = onReplayed(sessionCreated, contentType: contentType);
                            response.SetLocation(redirect);
                            return response;
                        },
                                                                        onAlreadyExists: default,
        [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()));
        }
 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()));
 }
Beispiel #26
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()));
        }
        [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()));
        }
Beispiel #28
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef,
     EastFive.Api.SessionToken security,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     ContentTypeResponse <Session> onFound,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     ConfigurationFailureResponse onConfigurationFailure)
 {
     if (security.sessionId != sessionRef.id)
     {
         return(onUnauthorized());
     }
     return(await await sessionRef.StorageGetAsync(
                (session) =>
     {
         return Web.Configuration.Settings.GetUri(
             EastFive.Security.AppSettings.TokenScope,
             scope =>
         {
             return Web.Configuration.Settings.GetDouble(Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes,
                                                         (tokenExpirationInMinutes) =>
             {
                 return GetClaimsAsync(application, session.authorization,
                                       (claims, accountIdMaybe, authorized) =>
                 {
                     session.account = accountIdMaybe;
                     session.authorized = authorized;
                     return BlackBarLabs.Security.Tokens.JwtTools.CreateToken(session.id,
                                                                              scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims,
                                                                              (tokenNew) =>
                     {
                         session.token = tokenNew;
                         return onFound(session);
                     },
                                                                              (missingConfig) => onConfigurationFailure("Missing", missingConfig),
                                                                              (configName, issue) => onConfigurationFailure(configName, issue));
                 },
                                       (why) => onNotFound());
             },
                                                         (why) => onConfigurationFailure("Missing", why).AsTask());
         },
             (why) => onConfigurationFailure("Missing", why).AsTask());
     },
                () => onNotFound().AsTask()));
 }
Beispiel #29
0
        public static IHttpResponse OptionsAsync(
            IApplication application,
            ContentTypeResponse <Claim[]> onFound)
        {
            var claims = application.GetType()
                         .GetAttributesInterface <IDeclareClaim>(true, true)
                         .Select(
                attr => new Claim
            {
                name  = attr.ClaimName,
                type  = attr.ClaimType,
                value = string.Empty,
            })
                         .ToArray();

            return(onFound(claims));
        }
 public static async Task <IHttpResponse> Information(
     [QueryParameter(Name = NamePropertyName)] string name,
     HttpApplication httpApp,
     ContentTypeResponse <TableInformation> onFound,
     NotFoundResponse onNotFound)
 {
     return(await DiscoverStorageResources(httpApp.GetType())
            .Where(table => table.name == name)
            .First(
                async(storageTable, next) =>
     {
         var information = await storageTable.type
                           .StorageTableInformationAsync(storageTable.cloudTable);
         return onFound(information);
     },
                () => onNotFound().AsTask()));
 }