Exemple #1
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 async static Task <HttpResponseMessage> QueryByActorId(
     [QueryParameter(Name = ActorPropertyName)] Guid actorId,
     Context context, AzureApplication application,
     EastFive.Api.SessionToken security,
     UrlHelper urlHelper,
     ContentResponse onFound,
     MultipartResponseAsync onFounds,
     ReferencedDocumentNotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     ServiceUnavailableResponse onServiceUnavailable)
 {
     return(await await context.PasswordCredentials.GetPasswordCredentialByActorAsync(
                actorId,
                security, application,
                (credentials) =>
     {
         var credentialResources = credentials
                                   .Select(
             passwordCredential =>
         {
             var resource = Convert(passwordCredential, urlHelper);
             var response = onFound(resource);
             return response;
         })
                                   .ToArray();
         return onFounds(credentialResources);
     },
                () => onNotFound().AsTask(),
                () => onUnauthorized().AsTask(),
                (why) => onServiceUnavailable().AsTask()));
 }
        [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));
        }
        [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()));
        }
        [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()));
        }
Exemple #6
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()));
 }
Exemple #7
0
 public static Task <HttpResponseMessage> GetByRequestIdAsync(
     [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef,
     [QueryParameter(Name = "request_id")] IRef <Authorization> authorization,
     EastFive.Api.SessionToken security,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     ContentTypeResponse <Session> onUpdated,
     NotFoundResponse onNotFound,
     ForbiddenResponse forbidden,
     ConfigurationFailureResponse onConfigurationFailure,
     GeneralConflictResponse onFailure)
 {
     return(UpdateBodyAsync(sessionRef, authorization.Optional(),
                            application,
                            onUpdated,
                            onNotFound,
                            forbidden,
                            onConfigurationFailure,
                            onFailure));
 }
        public static async Task <HttpResponseMessage> QueryByIntegrationAsync(
            [QueryParameter(Name = "integration")] IRef <Integration> integrationRef,
            Api.Azure.AzureApplication application, EastFive.Api.SessionToken security,
            MultipartResponseAsync <Method> onContent,
            UnauthorizedResponse onUnauthorized,
            ReferencedDocumentNotFoundResponse <Integration> onIntegrationNotFound)
        {
            return(await await integrationRef.StorageGetAsync(
                       async (integration) =>
            {
                var accountId = integration.accountId;
                if (!await application.CanAdministerCredentialAsync(accountId, security))
                {
                    return onUnauthorized();
                }

                var integrationProviders = application.LoginProviders
                                           .Where(loginProvider => loginProvider.Value.GetType().IsSubClassOfGeneric(typeof(IProvideIntegration)))
                                           .Select(
                    async loginProvider =>
                {
                    var integrationProvider = loginProvider.Value as IProvideIntegration;
                    var supportsIntegration = await integrationProvider.SupportsIntegrationAsync(accountId);
                    return supportsIntegration.PairWithValue(loginProvider);
                })
                                           .Await()
                                           .Where(kvp => kvp.Key)
                                           .SelectValues()
                                           .Select(
                    (loginProvider) =>
                {
                    var integrationProvider = loginProvider.Value as IProvideIntegration;
                    return new Method
                    {
                        authenticationId = new Ref <Method>(loginProvider.Value.Id),
                        name = integrationProvider.GetDefaultName(new Dictionary <string, string>()),
                    };
                });
                return await onContent(integrationProviders);
            },
                       () => onIntegrationNotFound().AsTask()));
        }
 public static async Task <HttpResponseMessage> DeleteByIdAsync(
     [Property(Name = IdPropertyName)] Guid passwordCredentialId,
     Context context, AzureApplication application,
     EastFive.Api.SessionToken security,
     UrlHelper urlHelper,
     NoContentResponse onDeleted,
     UnauthorizedResponse onUnauthorized,
     NotFoundResponse onNotFound,
     ServiceUnavailableResponse onServiceUnavailable)
 {
     return(await context.PasswordCredentials.DeletePasswordCredentialAsync(passwordCredentialId,
                                                                            security, application,
                                                                            () =>
     {
         var response = onDeleted();
         return response;
     },
                                                                            () => onUnauthorized(),
                                                                            () => onNotFound(),
                                                                            (why) => onServiceUnavailable().AddReason(why)));
 }
        public async static Task <IHttpResponse> CreateAsync(
            [Property(Name = AccountPropertyName)] Guid accountId,
            [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
            [Resource] XIntegration integration,
            IAuthApplication application, EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse onForbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthorizationDoesNotExist,
            GeneralConflictResponse onFailure)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(onForbidden());
            }

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

                return await CreateWithAuthorization(integration, authorization,
                                                     () => onCreated(),
                                                     () => onAlreadyExists(),
                                                     (why) => onFailure(why));
            },
                       async() =>
            {
                if (authorizationRefMaybe.HasValue)
                {
                    return onAuthorizationDoesNotExist();
                }
                return await integration.StorageCreateAsync(
                    (discard) => onCreated(),
                    () => onAlreadyExists());
            }));
        }
 public static async Task <HttpResponseMessage> QueryByIdAsync(
     [QueryParameter(Name = IdPropertyName)] Guid credentialId,
     Context context, AzureApplication application,
     EastFive.Api.SessionToken security,
     UrlHelper urlHelper,
     ContentResponse onFound,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     ServiceUnavailableResponse onServiceUnavailable)
 {
     return(await context.PasswordCredentials.GetPasswordCredentialAsync(credentialId,
                                                                         security, application,
                                                                         (passwordCredential) =>
     {
         var passwordCred = Convert(passwordCredential, urlHelper);
         var response = onFound(passwordCred);
         return response;
     },
                                                                         () => onNotFound(),
                                                                         () => onUnauthorized(),
                                                                         (why) => onServiceUnavailable().AddReason(why)));
 }
 public static Task <HttpResponseMessage> PutAsync(
     [Property(Name = IdPropertyName)] Guid credentialId,
     [PropertyOptional(Name = TokenPropertyName)] string token,
     [PropertyOptional(Name = ForceChangePropertyName)] bool forceChange,
     [PropertyOptional(Name = LastEmailSentPropertyName)] DateTime?lastEmailSent,
     Context context, AzureApplication application,
     EastFive.Api.SessionToken security,
     NoContentResponse onUpdated,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     ServiceUnavailableResponse onServiceUnavailable,
     GeneralConflictResponse onFailure)
 {
     return(context.PasswordCredentials.UpdatePasswordCredentialAsync(credentialId,
                                                                      token, forceChange, lastEmailSent,
                                                                      security, application,
                                                                      () => onUpdated(),
                                                                      () => onNotFound(),
                                                                      () => onUnauthorized(),
                                                                      () => onServiceUnavailable(),
                                                                      (why) => onFailure($"Update failed:{why}")));
 }
        [Api.HttpPost] //(MatchAllBodyParameters = false)]
        public async static Task <IHttpResponse> CreateAsync(
            [Property(Name = AccountPropertyName)] Guid accountId,
            [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
            [Resource] Integration integration,
            Api.Azure.AzureApplication application,
            EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse forbidden,
            ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthenticationDoesNotExist,
            GeneralConflictResponse onFailure)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(forbidden());
            }

            return(await await authorizationRefMaybe.StorageGetAsync(
                       authorization =>
            {
                // TODO? This
                // var accountIdDidMatch = await await authorization.ParseCredentailParameters(
                return CreateWithAuthorization(integration, authorization,
                                               accountId,
                                               () => onCreated(),
                                               () => onAlreadyExists(),
                                               (why) => onFailure(why));
            },
                       async() =>
            {
                return await await integration.StorageCreateAsync(
                    discard =>
                {
                    return SaveAccountLookupAsync(accountId, integration,
                                                  () => onCreated());
                },
                    () => onAlreadyExists().AsTask());
            }));
        }
        public static Task <HttpResponseMessage> CreatePasswordCredentialAsync(
            [Property(Name = IdPropertyName)] Guid credentialId,
            [Property(Name = ActorPropertyName)] Guid actorId,
            [PropertyOptional(Name = DisplayNamePropertyName)] string displayName,
            [PropertyOptional(Name = UserIdPropertyName)] string userId,
            [PropertyOptional(Name = TokenPropertyName)] string token,
            [PropertyOptional(Name = IsEmailPropertyName)] bool isEmail,
            [PropertyOptional(Name = ForceChangePropertyName)] bool forceChange,
            [PropertyOptional(Name = LastEmailSentPropertyName)] DateTime?lastEmailSent,
            Context context, AzureApplication application,
            UrlHelper url,
            EastFive.Api.SessionToken security,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            GeneralConflictResponse onUsernameAlreadyInUse,
            GeneralConflictResponse onInsufficentPassword,
            GeneralConflictResponse onUsernameAlreadyMappedToActor,
            UnauthorizedResponse onUnauthorized,
            ServiceUnavailableResponse onServiceUnavailable,
            GeneralConflictResponse onFailure)
        {
            var callbackUrl = url.GetLocation <EastFive.Api.Azure.Credentials.Controllers.OpenIdResponseController>();

            return(context.PasswordCredentials.CreatePasswordCredentialsAsync(
                       credentialId, actorId,
                       displayName, userId, isEmail, token, forceChange,
                       lastEmailSent, callbackUrl,
                       security, application,
                       () => onCreated(),
                       () => onAlreadyExists(),
                       (actorUsingId) => onUsernameAlreadyInUse($"Username already in use with Actor:{actorUsingId}"),
                       () => onInsufficentPassword($"Password is insufficient."),
                       () => onUsernameAlreadyMappedToActor($"Relationship already exists"),
                       () => onUsernameAlreadyMappedToActor($"Login is already in use"),
                       () => onUnauthorized(),
                       () => onServiceUnavailable(),
                       (why) => onFailure(why)));
        }
        public static async Task <IHttpResponse> DeleteAsync(
            [UpdateId(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef,
            IAuthApplication application, EastFive.Api.SessionToken security,
            NoContentResponse onDeleted,
            NotFoundResponse onNotFound,
            ForbiddenResponse onForbidden)
        {
            var integrationMaybe = await integrationRef.StorageGetAsync(i => i, () => default(XIntegration?));

            if (!integrationMaybe.HasValue)
            {
                return(onNotFound());
            }

            var integration = integrationMaybe.Value;

            if (!await application.CanAdministerCredentialAsync(integration.accountId, security))
            {
                return(onForbidden());
            }

            return(await DeleteInternalAsync(integrationRef, () => onDeleted(), () => onNotFound()));
        }
Exemple #16
0
        public static async Task <IHttpResponse> QueryByIntegrationAccountAsync(
            [QueryParameter(Name = "integration_account")] Guid accountId,
            IAuthApplication application, EastFive.Api.SessionToken security,
            MultipartAsyncResponse <Method> onContent,
            UnauthorizedResponse onUnauthorized)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(onUnauthorized());
            }

            var integrationProviders = application.LoginProviders
                                       .Where(loginProvider => loginProvider.Value.GetType().IsSubClassOfGeneric(typeof(IProvideIntegration)))
                                       .Select(
                async loginProvider =>
            {
                var integrationProvider = loginProvider.Value as IProvideIntegration;
                var supportsIntegration = await integrationProvider.SupportsIntegrationAsync(accountId);
                return(supportsIntegration.PairWithValue(loginProvider));
            })
                                       .AsyncEnumerable()
                                       .Where(kvp => kvp.Key)
                                       .SelectValues()
                                       .Select(
                (loginProvider) =>
            {
                var integrationProvider = loginProvider.Value as IProvideIntegration;
                return(new Method
                {
                    authenticationId = new Ref <Method>(loginProvider.Value.Id),
                    name = integrationProvider.GetDefaultName(new Dictionary <string, string>()),
                });
            });

            return(onContent(integrationProviders));
        }