public static async Task <HttpResponseMessage> UpdateAsync(
            [Property(Name = UserIdentificationPropertyName)] string userIdentification,
            [Property(Name = PasswordPropertyName)] string password,
            Api.Azure.AzureApplication application,
            CreatedResponse onUpdated,
            AlreadyExistsResponse onUsernameAlreadyTaken,
            GeneralConflictResponse onInvalidPassword)
        {
            if (!password.HasBlackSpace())
            {
                return(onInvalidPassword("Password cannot be empty"));
            }

            var accountRef = userIdentification
                             .MD5HashGuid()
                             .AsRef <Account>();

            return(await accountRef
                   .StorageCreateOrUpdateAsync(
                       async (created, account, saveAsync) =>
            {
                if (!created)
                {
                    return onUsernameAlreadyTaken();
                }

                account.userIdentification = userIdentification;
                account.password = Account.GeneratePasswordHash(userIdentification, password);
                await saveAsync(account);
                return onUpdated();
            }));
        }
        public async static Task <HttpResponseMessage> GetByAccountAsync(
            [QueryParameter(Name = AccountPropertyName)] Guid accountId,
            Api.Azure.AzureApplication application, SessionToken security,
            MultipartResponseAsync <XIntegration> onContents,
            ReferencedDocumentNotFoundResponse <object> onAccountNotFound,
            UnauthorizedResponse onUnauthorized)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(onUnauthorized());
            }

            var integrations = GetIntegrationsByAccount(accountId)
                               .Select(
                kvp =>
            {
                var integration = kvp.Key;
                return(Auth.Method.ById(kvp.Value.Method,
                                        application,
                                        method =>
                {
                    integration.methodName = method.name;
                    return integration;
                },
                                        () => default(XIntegration?)));
            })
                               .Await()
                               .SelectWhereHasValue();

            return(await onContents(integrations));
        }
Esempio n. 3
0
        private static async Task <TResult> GetClaimsAsync <TResult>(
            Api.Azure.AzureApplication application, IRefOptional <Authorization> authorizationRefMaybe,
            Func <IDictionary <string, string>, Guid?, bool, TResult> onClaims,
            Func <string, TResult> onFailure)
        {
            if (!authorizationRefMaybe.HasValue)
            {
                return(onClaims(new Dictionary <string, string>(), default(Guid?), false));
            }
            var authorizationRef = authorizationRefMaybe.Ref;

            return(await Api.AppSettings.ActorIdClaimType.ConfigurationString(
                       (accountIdClaimType) =>
            {
                return GetSessionAcountAsync(authorizationRef, application,
                                             (accountId, authorized) =>
                {
                    var claims = new Dictionary <string, string>()
                    {
                        { accountIdClaimType, accountId.ToString() }
                    };
                    return onClaims(claims, accountId, authorized);
                },
                                             (why, authorized) => onClaims(new Dictionary <string, string>(), default(Guid?), authorized));
            },
                       (why) => onClaims(new Dictionary <string, string>(), default(Guid?), false).AsTask()));
        }
        public async static Task <HttpResponseMessage> GetByIdAsync(
            [QueryParameter(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef,
            Api.Azure.AzureApplication 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 async static Task <HttpResponseMessage> GetByMethodAsync(
            [QueryParameter(Name = Authorization.MethodPropertyName)] IRef <Method> methodRef,
            Api.Azure.AzureApplication application, SessionToken security,
            MultipartResponseAsync <XIntegration> onContents,
            UnauthorizedResponse onUnauthorized)
        {
            if (!security.accountIdMaybe.HasValue)
            {
                return(onUnauthorized());
            }
            var accountId = security.accountIdMaybe.Value;

            var integrations = GetIntegrationsByAccount(accountId)
                               .Where(integration => integration.Value.Method.id == methodRef.id)
                               .Select(
                kvp =>
            {
                var integration = kvp.Key;
                return(Auth.Method.ById(kvp.Value.Method,
                                        application,
                                        method =>
                {
                    integration.methodName = method.name;
                    return integration;
                },
                                        () => default(XIntegration?)));
            })
                               .Await()
                               .SelectWhereHasValue();

            return(await onContents(integrations));
        }
 public static async Task <HttpResponseMessage> QueryBySessionAsync(
     [QueryParameter(Name = "session")] IRef <Session> sessionRef,
     Api.Azure.AzureApplication application,
     MultipartResponseAsync <Method> onContent,
     ReferencedDocumentNotFoundResponse <Session> onIntegrationNotFound)
 {
     return(await await sessionRef.StorageGetAsync(
                session =>
     {
         var integrationProviders = application.LoginProviders
                                    .Where(loginProvider => loginProvider.Value.GetType().IsSubClassOfGeneric(typeof(IProvideSession)))
                                    .Select(
             async loginProvider =>
         {
             var supportsIntegration = await(loginProvider.Value as IProvideSession).SupportsSessionAsync(session);
             return supportsIntegration.PairWithValue(loginProvider);
         })
                                    .Await()
                                    .Where(kvp => kvp.Key)
                                    .SelectValues()
                                    .Select(
             (loginProvider) =>
         {
             return new Method
             {
                 authenticationId = new Ref <Method>(loginProvider.Value.Id),
                 name = loginProvider.Value.Method,
             };
         });
         return onContent(integrationProviders);
     },
                () => onIntegrationNotFound().AsTask()));
 }
        public async Task <TResult> ParseCredentailParameters <TResult>(
            Api.Azure.AzureApplication application,
            Func <string, IProvideLogin, TResult> onSuccess,
            Func <string, TResult> onFailure)
        {
            var parameters = this.parameters;

            return(await await Auth.Method.ById(this.Method, application, // TODO: Cleanup
                                                (method) =>
            {
                return application.LoginProviders
                .SelectValues()
                .Where(loginProvider => loginProvider.Method == method.name)
                .FirstAsync(
                    (loginProvider) =>
                {
                    return loginProvider.ParseCredentailParameters(parameters,
                                                                   (string userKey, Guid? authorizationIdDiscard, Guid? deprecatedId) =>
                    {
                        return onSuccess(userKey, loginProvider);
                    },
                                                                   (why) => onFailure(why));
                },
                    () => onFailure("Method does not match any existing authentication."));
            },
                                                () => onFailure("Authentication not found").AsTask()));
        }
Esempio n. 8
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = StatePropertyName)] string state,
     [QueryParameter(Name = ClientPropertyName)] IRef <Client> clientRef,
     [QueryParameter(Name = ValidationPropertyName)] string validation,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     //ContentTypeResponse<Authentication> onFound,
     RedirectResponse onFound,
     ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
 {
     return(await await clientRef.StorageGetAsync(
                (client) =>
     {
         var authentication = new Authentication
         {
             authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
             state = state,
         };
         return authentication.StorageCreateAsync(
             (entity) =>
         {
             var location = urlHelper.GetLocation <Authentication>(
                 auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                 application);
             return onFound(location);
         },
             () => throw new Exception("Secure guid not unique"));
     },
                () => onInvalidClient().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));
        }
Esempio n. 10
0
 public Task <TResult> GetLoginProviderAsync <TResult>(Api.Azure.AzureApplication application,
                                                       Func <string, Security.SessionServer.IProvideLogin, TResult> onFound,
                                                       Func <TResult> onNotFound)
 {
     return(GetLoginProviderAsync(this.id, application,
                                  onFound,
                                  onNotFound));
 }
 [Api.HttpPost] //(MatchAllBodyParameters = false)]
 public async static Task <HttpResponseMessage> CreateAsync(
     [Property(Name = AccountPropertyName)] Guid accountId,
     [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef,
     [Resource] AccountMapping accountMapping,
     Api.Azure.AzureApplication application, Api.SessionToken security,
     CreatedResponse onCreated,
     ForbiddenResponse onForbidden,
     UnauthorizedResponse onUnauthorized,
     ReferencedDocumentDoesNotExistsResponse <Authorization> onAuthenticationDoesNotExist,
     GeneralConflictResponse onFailure)
 {
     if (!await application.CanAdministerCredentialAsync(accountId, security))
     {
         return(onUnauthorized());
     }
     return(await await authorizationRef.StorageGetAsync(
                async authorization =>
     {
         accountMapping.Method = authorization.Method;     // method is used in the .mappingId
         var authorizationLookup = new AuthorizationLookup
         {
             accountMappingRef = accountMapping.mappingId,
             authorizationLookupRef = authorizationRef,
         };
         return await await authorizationLookup.StorageCreateAsync(
             async(idDiscard) =>
         {
             accountMapping.accountMappingLookup = await await authorization.ParseCredentailParameters(
                 application,
                 (accountKey, loginProvider) =>
             {
                 var lookup = new AccountMappingLookup()
                 {
                     accountkey = accountKey,
                     accountMappingId = accountMapping.mappingId,
                     Method = authorization.Method,
                 };
                 return lookup.StorageCreateAsync(
                     (discard) => new RefOptional <AccountMappingLookup>(
                         lookup.accountMappingLookupId),
                     () => new RefOptional <AccountMappingLookup>());
             },
                 (why) =>
             {
                 var amLookupMaybe = new RefOptional <AccountMappingLookup>();
                 return amLookupMaybe.AsTask();
             });
             return await accountMapping.StorageCreateAsync(
                 createdId =>
             {
                 return onCreated();
             },
                 () => onForbidden().AddReason("Account is already mapped to that authentication."));
         },
             () => onFailure("Authorization is already mapped to another account.").AsTask());
     },
                () => onAuthenticationDoesNotExist().AsTask()));
 }
Esempio n. 12
0
 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()));
 }
 public static Task <TResult> DeleteInternalAsync <TResult>(
     IRef <XIntegration> integrationRef, Api.Azure.AzureApplication application,
     Func <TResult> onDeleted,
     Func <TResult> onNotFound)
 {
     return(integrationRef.StorageDeleteAsync(
                () =>
     {
         return onDeleted();
     },
                () => onNotFound()));
 }
Esempio n. 14
0
 public Task <TResult> GetAuthorizationKeyAsync <TResult>(Api.Azure.AzureApplication application,
                                                          IDictionary <string, string> parameters,
                                                          Func <string, TResult> onAuthorizeKey,
                                                          Func <string, TResult> onFailure,
                                                          Func <TResult> loginMethodNoLongerSupported)
 {
     return(GetLoginProviderAsync(application,
                                  (name, loginProvider) => loginProvider.ParseCredentailParameters(parameters,
                                                                                                   (externalUserKey, authenticationIdMaybe, scopeMaybeDiscard) => onAuthorizeKey(externalUserKey),
                                                                                                   why => onFailure(why)),
                                  () => loginMethodNoLongerSupported()));
 }
Esempio n. 15
0
 public static Task <HttpResponseMessage> DeleteAsync(
     [UpdateId(Name = SessionIdPropertyName)] IRef <Session> sessionRef,
     Api.Azure.AzureApplication application,
     NoContentResponse onDeleted,
     NotFoundResponse onNotFound)
 {
     return(sessionRef.StorageDeleteAsync(
                () =>
     {
         return onDeleted();
     },
                onNotFound: () => onNotFound()));
 }
Esempio n. 16
0
        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,
Esempio n. 17
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()));
        }
Esempio n. 18
0
        internal Task <Uri> GetLogoutUrlAsync(Api.Azure.AzureApplication application,
                                              UrlHelper urlHelper, Guid authorizationIdSecure)
        {
            var authenticationId = this.id;

            return(GetLoginProviderAsync(application,
                                         (name, loginProvider) =>
            {
                var redirectionResource = loginProvider.CallbackController;
                var redirectionLocation = urlHelper.GetLocation(redirectionResource);
                return loginProvider.GetLogoutUrl(authorizationIdSecure, redirectionLocation,
                                                  type => urlHelper.GetLocation(type));
            },
                                         () => throw new Exception($"Login provider with id {authenticationId} does not exists.")));
        }
Esempio n. 19
0
 public static async Task <HttpResponseMessage> CreateAsync(
     [Resource] Client client,
     Api.Azure.AzureApplication application,
     CreatedResponse onCreated,
     AlreadyExistsResponse onAlreadyExists,
     GeneralConflictResponse onFailure)
 {
     return(await client
            .StorageCreateAsync(
                (discard) =>
     {
         return onCreated();
     },
                () => onAlreadyExists()));
 }
Esempio n. 20
0
 public static Task <TResult> ById <TResult>(IRef <Method> method, Api.Azure.AzureApplication application,
                                             Func <Method, TResult> onFound,
                                             Func <TResult> onNotFound)
 {
     return(GetLoginProviderAsync(method.id, application,
                                  (key, loginProvider) =>
     {
         var authentication = new Method
         {
             authenticationId = new Ref <Method>(loginProvider.Id),
             name = loginProvider.Method,
         };
         return onFound(authentication);
     },
                                  onNotFound));
 }
        [Api.HttpGet] //(MatchAllBodyParameters = false)]
        public async static Task <HttpResponseMessage> GetByAccountAsync(
            [QueryParameter(Name = AccountPropertyName)] Guid accountId,
            Api.Azure.AzureApplication application, SessionToken security,
            MultipartResponseAsync <Integration> onContents,
            ReferencedDocumentNotFoundResponse <object> onAccountNotFound,
            UnauthorizedResponse onUnauthorized)
        {
            if (!await application.CanAdministerCredentialAsync(accountId, security))
            {
                return(onUnauthorized());
            }

            return(await await GetIntegrationsByAccountAsync(accountId,
                                                             (kvps) => onContents(kvps.SelectKeys()),
                                                             () => onAccountNotFound().AsTask()));
        }
Esempio n. 22
0
 public static Task <HttpResponseMessage> QueryAsync(
     Api.Azure.AzureApplication application,
     MultipartResponseAsync <Method> onContent)
 {
     return(onContent(
                application.LoginProviders
                .Select(
                    (loginProvider) =>
     {
         return new Method
         {
             authenticationId = loginProvider.Value.Id.AsRef <Method>(),
             name = loginProvider.Value.Method,
         };
     })));
 }
Esempio n. 23
0
 public static Task <Method> ByMethodName(string methodName, Api.Azure.AzureApplication application)
 {
     return(application.LoginProviders
            .SelectValues()
            .Where(loginProvider => loginProvider.Method == methodName)
            .FirstAsync(
                (loginProvider) =>
     {
         return new Method
         {
             authenticationId = new Ref <Method>(loginProvider.Id),
             name = loginProvider.Method,
         };
     },
                () => throw new Exception($"Login provider `{methodName}` is not enabled.")));
 }
        [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()));
        }
Esempio n. 25
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()));
 }
Esempio n. 26
0
        [HttpPost] //(MatchAllBodyParameters = false)]
        public async static Task <HttpResponseMessage> CreateAsync(
            [Property(Name = SessionIdPropertyName)] IRef <Session> sessionId,
            [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
            [Resource] Session session,
            Api.Azure.AzureApplication application,
            CreatedBodyResponse <Session> onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse forbidden,
            ConfigurationFailureResponse onConfigurationFailure,
            GeneralConflictResponse onFailure)
        {
            session.refreshToken = Security.SecureGuid.Generate().ToString("N");

            return(await Security.AppSettings.TokenScope.ConfigurationUri(
                       scope =>
            {
                return Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes.ConfigurationDouble(
                    async(tokenExpirationInMinutes) =>
                {
                    return await await GetClaimsAsync(application, authorizationRefMaybe,
                                                      (claims, accountIdMaybe, authorized) =>
                    {
                        session.account = accountIdMaybe;
                        session.authorized = authorized;
                        return session.StorageCreateAsync(
                            (sessionIdCreated) =>
                        {
                            return BlackBarLabs.Security.Tokens.JwtTools.CreateToken(sessionId.id,
                                                                                     scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims,
                                                                                     (tokenNew) =>
                            {
                                session.token = tokenNew;
                                return onCreated(session);
                            },
                                                                                     (missingConfig) => onConfigurationFailure("Missing", missingConfig),
                                                                                     (configName, issue) => onConfigurationFailure(configName, issue));
                        },
                            () => onAlreadyExists());
                    },
                                                      (why) => onFailure(why).AsTask());
                },
                    (why) => onConfigurationFailure("Missing", why).AsTask());
            },
                       (why) => onConfigurationFailure("Missing", why).AsTask()));
        }
Esempio n. 27
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()));
 }
Esempio n. 28
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));
 }
Esempio n. 29
0
        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()));
        }
Esempio n. 30
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = AuthenticationPropertyName)] IRef <Authentication> authenticationRef,
     [Accepts(Media = "text/html")] MediaTypeWithQualityHeaderValue accept,
     HttpRequestMessage request,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     ContentTypeResponse <Authentication> onFound,
     HtmlResponse onHtmlWanted,
     NotFoundResponse onNotFound)
 {
     if (!accept.IsDefaultOrNull())
     {
         return(onHtmlWanted(EastFive.Azure.Properties.Resources.loginHtml));
     }
     return(await authenticationRef.StorageGetAsync(
                (authentication) =>
     {
         return onFound(authentication);
     },
                () => onNotFound()));
 }