Ejemplo n.º 1
0
        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()));
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        public async static Task <IHttpResponse> GetByAccountAsync(
            [QueryParameter(Name = AccountPropertyName)] Guid accountId,
            IAuthApplication application, SessionToken security,
            MultipartAsyncResponse <XIntegration> onContents,
            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(onContents(integrations));
        }
Ejemplo n.º 4
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));
        }
Ejemplo n.º 5
0
 public static Task <IHttpResponse> QueryBySessionAsync(
     [QueryParameter(Name = "session")] IRef <Session> sessionRef,
     IAuthApplication application,
     MultipartAsyncResponse <Method> onContent,
     ReferencedDocumentNotFoundResponse <Session> onSessionNotFound,
     UnauthorizedResponse onHacked)
 {
     return(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);
         })
                                    .AsyncEnumerable()
                                    .Where(kvp => kvp.Key)
                                    .SelectValues()
                                    .Select(
             (loginProvider) =>
         {
             return new Method
             {
                 authenticationId = new Ref <Method>(loginProvider.Value.Id),
                 name = loginProvider.Value.Method,
             };
         });
         return onContent(integrationProviders);
     },
                //() => onSessionNotFound().AsTask());
                () => onHacked()));
 }
Ejemplo n.º 6
0
        public static IHttpResponse GetByMethodAsync(
            [QueryParameter(Name = Authorization.MethodPropertyName)] IRef <Method> methodRef,
            IAuthApplication application, SessionToken security,
            MultipartAsyncResponse <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(onContents(integrations));
        }
Ejemplo n.º 7
0
 public Task <TResult> GetLoginProviderAsync <TResult>(IAuthApplication application,
                                                       Func <string, IProvideLogin, TResult> onFound,
                                                       Func <TResult> onNotFound)
 {
     return(GetLoginProvider(this.id, application,
                             onFound,
                             onNotFound).AsTask());
 }
Ejemplo n.º 8
0
 public async static Task <IHttpResponse> CreateAsync(
     [Property(Name = AccountPropertyName)] Guid accountId,
     [Property(Name = AuthorizationPropertyName)] IRef <Authorization> authorizationRef,
     [Resource] AccountMapping accountMapping,
     IAuthApplication 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()));
 }
Ejemplo n.º 9
0
 public static Task <IHttpResponse> QueryByIdAsync(
     [QueryId] IRef <Method> methodRef,
     IAuthApplication application,
     ContentTypeResponse <Method> onFound,
     NotFoundResponse onNotFound)
 {
     return(ById(methodRef, application,
                 method => onFound(method),
                 () => onNotFound()));
 }
Ejemplo n.º 10
0
 public AuthController(
     IUserApplication userApplication,
     IAuthApplication authApplication,
     ITokenApplication tokenApplication,
     IMapper mapper)
 {
     this._authApplication  = authApplication;
     this._userApplication  = userApplication;
     this._tokenApplication = tokenApplication;
     this._mapper           = mapper;
 }
Ejemplo n.º 11
0
 public Task <TResult> GetAuthorizationKeyAsync <TResult>(IAuthApplication 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()));
 }
Ejemplo n.º 12
0
        public static async Task <IHttpResponse> GetAsync(
            //[WorkflowNewId]
            //[WorkflowVariable(
            //    Workflows.PasswordLoginCreateAccount.Variables.State,
            //    AuthorizationPropertyName)]
            [OptionalQueryParameter(Name = AuthorizationPropertyName)]
            IRefOptional <Authorization> authorizationRefOptional,

            [WorkflowParameter(
                 Value = "d989b604-1e25-4d77-b79e-fe1c7d36f833",
                 Description = "Unique and static to each client (i.e. iOS or Web)")]
            [QueryParameter(Name = ClientPropertyName)]
            IRef <Client> clientRef,

            [WorkflowNewId(Description = "No idea what this does.")]
            [OptionalQueryParameter(Name = ValidationPropertyName)]
            string validation,

            IAuthApplication application, IProvideUrl urlHelper,
            //ContentTypeResponse<Authentication> onFound,

            [WorkflowVariable(
                 Workflows.PasswordLoginCreateAccount.Variables.Authorization,
                 Authentication.AuthenticationPropertyName)]
            [WorkflowVariableRedirectUrl(
                 VariableName = Workflows.PasswordLoginCreateAccount.Variables.AuthorizationRedirect)]
            RedirectResponse onFound,

            ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
        {
            return(await await clientRef.StorageGetAsync(
                       (client) =>
            {
                var authentication = new Authentication
                {
                    authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
                    authorizationMaybe = authorizationRefOptional,
                    client = clientRef,
                };
                return authentication.StorageCreateAsync(
                    (entity) =>
                {
                    var location = urlHelper.GetLocation <Authentication>(
                        auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                        application);
                    return onFound(location);
                });
            },
                       () => onInvalidClient().AsTask()));
        }
Ejemplo n.º 13
0
        internal Task <Uri> GetLogoutUrlAsync(IAuthApplication application,
                                              IProvideUrl 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.")));
        }
Ejemplo n.º 14
0
 public static Method ByMethodName(string methodName, IAuthApplication application)
 {
     return(application.LoginProviders
            .SelectValues()
            .Where(loginProvider => loginProvider.Method == methodName)
            .First <IProvideLogin, Method>(
                (loginProvider, next) =>
     {
         return new Method
         {
             authenticationId = new Ref <Method>(loginProvider.Id),
             name = loginProvider.Method,
         };
     },
                () => throw new Exception($"Login provider `{methodName}` is not enabled.")));
 }
Ejemplo n.º 15
0
 public static Task <TResult> ById <TResult>(IRef <Method> method, IAuthApplication application,
                                             Func <Method, TResult> onFound,
                                             Func <TResult> onNotFound)
 {
     return(GetLoginProvider(method.id, application,
                             (key, loginProvider) =>
     {
         var authentication = new Method
         {
             authenticationId = new Ref <Method>(loginProvider.Id),
             name = loginProvider.Method,
         };
         return onFound(authentication);
     },
                             onNotFound).AsTask());
 }
Ejemplo n.º 16
0
        public static IHttpResponse AllAsync(
            [QueryParameter(Name = "start_time")] DateTime startTime,
            [QueryParameter(Name = "end_time")] DateTime endTime,
            RequestMessage <Authorization> authorizations,
            IAuthApplication application,
            EastFive.Api.SessionToken?securityMaybe,
            MultipartAsyncResponse <Login> onFound)
        {
            var methodLookups = application.LoginProviders
                                .Select(
                (loginProvider) =>
            {
                return(loginProvider.Value.Id.PairWithValue(loginProvider.Value.Method));
            })
                                .ToDictionary();
            var results = authorizations
                          .Where(auth => auth.lastModified <= endTime)
                          .Where(auth => auth.lastModified >= startTime)
                          .StorageGet()
                          .Take(100)
                          .Select(
                async auth =>
            {
                var name = auth.accountIdMaybe.HasValue ?
                           await application.GetActorNameDetailsAsync(auth.accountIdMaybe.Value,
                                                                      (a, b, c) => $"{a} {b}",
                                                                      () => "")
                            :
                           "";
                return(new Login()
                {
                    actorId = auth.accountIdMaybe,
                    authorization = auth.authorizationRef,
                    name = name,
                    method = methodLookups.ContainsKey(auth.Method.id) ?
                             methodLookups[auth.Method.id]
                                :
                             auth.Method.id.ToString(),
                    when = auth.lastModified,
                });
            })
                          .Await();

            return(onFound(results));
        }
Ejemplo n.º 17
0
        public static IHttpResponse QueryAsync(
            IAuthApplication application,
            [WorkflowVariableResourceResponse]
            MultipartAcceptArrayResponse <Method> onContent)
        {
            var methods = application.LoginProviders
                          .Select(
                (loginProvider) =>
            {
                return(new Method
                {
                    authenticationId = loginProvider.Value.Id.AsRef <Method>(),
                    name = loginProvider.Value.Method,
                });
            });

            return(onContent(methods));
        }
Ejemplo n.º 18
0
 public static Task <IHttpResponse> UpdateBodyAsync(
     [UpdateId(Name = SessionIdPropertyName)] IRef <Session> sessionRef,
     [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
     IAuthApplication 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 Api.Auth.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()));
 }
Ejemplo n.º 19
0
 public static Task <IHttpResponse> GetByRequestIdAsync(
     [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef,
     [QueryParameter(Name = EastFive.Api.Azure.AzureApplication.QueryRequestIdentfier)] IRef <Authorization> authorization,
     //EastFive.Api.SessionToken security,
     IAuthApplication application, IProvideUrl urlHelper,
     ContentTypeResponse <Session> onUpdated,
     NotFoundResponse onNotFound,
     ForbiddenResponse forbidden,
     ConfigurationFailureResponse onConfigurationFailure,
     GeneralConflictResponse onFailure)
 {
     return(UpdateBodyAsync(sessionRef, authorization.Optional(),
                            application,
                            onUpdated,
                            onNotFound,
                            forbidden,
                            onConfigurationFailure,
                            onFailure));
 }
Ejemplo n.º 20
0
        //public static async Task<TResult> LegacyAccountMappingAsync<TResult>(Authorization authorization,
        //        Method authenticationMethod, string externalAccountKey,
        //        IDictionary<string, string> extraParams,
        //        IAzureApplication application,
        //        IProvideLogin loginProvider,
        //        Uri baseUri,
        //    Func<Guid, Func<bool, Task<TResult>>, TResult> onLocated,
        //    Func<Guid, TResult> onCreated,
        //    Func<TResult> onSelfServe,
        //    Func<Uri, TResult> onInterupted,
        //    Func<string, TResult> onGeneralFailure,
        //        TelemetryClient telemetry)
        //{
        //    return await await AccountMapping.FindByMethodAndKeyAsync(
        //            authenticationMethod.authenticationId, externalAccountKey,
        //            authorization,
        //            // Found
        //        internalAccountId =>
        //        {
        //            return onLocated(
        //                    internalAccountId,
        //                    (isAccountInvalid) => OnNotFound(isAccountInvalid))
        //                .AsTask();
        //        },
        //        () => OnNotFound(false));

        //    async Task<TResult> OnNotFound(bool isAccountInvalid)
        //    {
        //        return await await UnmappedCredentialAsync(externalAccountKey, extraParams,
        //                    authenticationMethod, authorization,
        //                    loginProvider, application, baseUri,

        //                // Create mapping
        //                (internalAccountId) =>
        //                {
        //                    return AccountMapping.CreateByMethodAndKeyAsync(
        //                            authorization, externalAccountKey, internalAccountId,
        //                        () =>
        //                        {
        //                            return onCreated(internalAccountId);
        //                        },
        //                        () =>
        //                        {
        //                            return onLocated(internalAccountId, default);
        //                        },
        //                            isAccountInvalid);
        //                },

        //                // Allow self serve
        //                () =>
        //                {
        //                    return onSelfServe().AsTask();
        //                },

        //                // Intercept process
        //                (interceptionUrl) =>
        //                {
        //                    return onInterupted(interceptionUrl).AsTask();
        //                },

        //                // Failure
        //                (why) =>
        //                {
        //                    return onGeneralFailure(why).AsTask();
        //                },
        //                telemetry);
        //    }
        //}

        private static Task <TResult> CreateLoginResponseAsync <TResult>(
            Guid?accountId, IDictionary <string, string> extraParams,
            Method method, Authorization authorization,
            IAuthApplication application,
            IHttpRequest request, IInvokeApplication endpoints,
            Uri baseUrl,
            IProvideAuthorization authorizationProvider,
            Func <Uri, Func <IHttpResponse, IHttpResponse>, TResult> onRedirect,
            Func <string, TResult> onBadResponse,
            TelemetryClient telemetry)
        {
            return(application.GetRedirectUriAsync(
                       accountId, extraParams,
                       method, authorization,
                       request, endpoints,
                       baseUrl,
                       authorizationProvider,
                       (redirectUrlSelected, modifier) =>
            {
                telemetry.TrackEvent($"CreateResponse - redirectUrlSelected1: {redirectUrlSelected.AbsolutePath}");
                telemetry.TrackEvent($"CreateResponse - redirectUrlSelected2: {redirectUrlSelected.AbsoluteUri}");
                return onRedirect(redirectUrlSelected, modifier);
            },
                       (paramName, why) =>
            {
                var message = $"Invalid parameter while completing login: {paramName} - {why}";
                telemetry.TrackException(new ResponseException(message));
                return onBadResponse(message);
            },
                       () =>
            {
                var message = $"Invalid account while completing login";
                telemetry.TrackException(new ResponseException(message));
                return onBadResponse(message);
            },
                       (why) =>
            {
                var message = $"General failure while completing login: {why}";
                telemetry.TrackException(new ResponseException(message));
                return onBadResponse(message);
            }));
        }
Ejemplo n.º 21
0
        public static async Task <IHttpResponse> QueryByIntegrationAsync(
            [QueryParameter(Name = "integration")] IRef <XIntegration> integrationRef,
            IAuthApplication application, EastFive.Api.SessionToken security,
            MultipartAsyncResponse <Method> onContent,
            UnauthorizedResponse onUnauthorized,
            ReferencedDocumentNotFoundResponse <XIntegration> 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);
                })
                                           .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);
            },
                       () => onIntegrationNotFound().AsTask()));
        }
Ejemplo n.º 22
0
 private static TResult GetLoginProvider <TResult>(Guid authenticationId, IAuthApplication application,
                                                   Func <string, IProvideLogin, TResult> onFound,
                                                   Func <TResult> onNotFound)
 {
     //var debug = application.LoginProviders.ToArrayAsync().Result;
     return(application.LoginProviders
            .Where(
                loginProvider =>
     {
         return loginProvider.Value.Id == authenticationId;
     })
            .First(
                (loginProviderKvp, next) =>
     {
         var loginProviderKey = loginProviderKvp.Key;
         var loginProvider = loginProviderKvp.Value;
         return onFound(loginProviderKey, loginProvider);
     },
                onNotFound));
 }
Ejemplo n.º 23
0
        public async Task <TResult> RedeemTokenAsync <TResult>(
            IDictionary <string, string> parameters,
            IAuthApplication application,
            Func <string, IRefOptional <Authorization>, IProvideLogin, IDictionary <string, string>, TResult> onSuccess,
            Func <Guid?, IDictionary <string, string>, TResult> onLogout,
            Func <string, TResult> onCouldNotConnect,
            Func <string, TResult> onFailure)
        {
            var methodName             = this.name;
            var matchingLoginProviders = application.LoginProviders
                                         .SelectValues()
                                         .Where(loginProvider => loginProvider.Method == methodName)
                                         .ToArray();

            if (!matchingLoginProviders.Any())
            {
                return(onFailure("Method does not match any existing authentication."));
            }
            var matchingLoginProvider = matchingLoginProviders.First();

            return(await matchingLoginProvider.RedeemTokenAsync(parameters,
                                                                (userKey, authorizationIdMaybe, deprecatedId, updatedParameters) =>
            {
                var allParameters = updatedParameters
                                    .Concat(
                    parameters
                    .Where(param => !updatedParameters.ContainsKey(param.Key)))
                                    .ToDictionary();
                var authorizationRef = authorizationIdMaybe.HasValue ?
                                       new RefOptional <Authorization>(authorizationIdMaybe.Value)
                        :
                                       new RefOptional <Authorization>();
                return onSuccess(userKey, authorizationRef,
                                 matchingLoginProvider, allParameters);
            },
                                                                (authorizationId, extraParams) => onLogout(authorizationId, extraParams),
                                                                (why) => onFailure(why),
                                                                (why) => onCouldNotConnect(why),
                                                                (why) => onFailure(why),
                                                                (why) => onFailure(why)));
        }
Ejemplo n.º 24
0
        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());
            }));
        }
Ejemplo n.º 25
0
        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()));
        }
Ejemplo n.º 26
0
        private static async Task <TResult> GetClaimsAsync <TResult>(
            IAuthApplication application, IRefOptional <Authorization> authorizationRefMaybe,
            Func <IDictionary <string, string>, Guid?, bool, TResult> onClaims,
            Func <string, TResult> onFailure)
        {
            if (!authorizationRefMaybe.HasValueNotNull())
            {
                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, claims, authorized) =>
                {
                    var claimsWithAccountId = claims
                                              .Append(accountIdClaimType.PairWithValue(accountId.ToString()))
                                              .ToDictionary();
                    return onClaims(claimsWithAccountId, accountId, authorized);
                },
                                             (why, authorized) => onClaims(new Dictionary <string, string>(), default(Guid?), authorized));
            },
                       (why) =>
            {
                return GetSessionAcountAsync(authorizationRef, application,
                                             (accountId, claims, authorized) =>
                {
                    var claimsDictionary = claims
                                           .NullToEmpty()
                                           .ToDictionary();
                    return onClaims(claimsDictionary, accountId, authorized);
                },
                                             (why, authorized) => onClaims(new Dictionary <string, string>(), default(Guid?), authorized));
            }));
        }
Ejemplo n.º 27
0
        public Task <TResult> ParseTokenAsync <TResult>(IDictionary <string, string> parameters,
                                                        IAuthApplication application,
                                                        Func <string, IProvideLogin, TResult> onParsed,
                                                        Func <string, TResult> onFailure)
        {
            var methodName             = this.name;
            var matchingLoginProviders = application.LoginProviders
                                         .SelectValues()
                                         .Where(loginProvider => loginProvider.Method == methodName)
                                         .ToArray();

            if (!matchingLoginProviders.Any())
            {
                return(onFailure("Method does not match any existing authentication.").AsTask());
            }
            var matchingLoginProvider = matchingLoginProviders.First();

            return(matchingLoginProvider.ParseCredentailParameters(parameters,
                                                                   (externalId, authorizationIdMaybeDiscard, lookupDiscard) =>
            {
                return onParsed(externalId, matchingLoginProvider);
            },
                                                                   onFailure).AsTask());
        }
Ejemplo n.º 28
0
        public async static Task <IHttpResponse> CreateAsync(
            [Api.Meta.Flows.WorkflowNewId]
            [Property(Name = AuthorizationIdPropertyName)]
            IRef <Authorization> authorizationRef,

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

            [Api.Meta.Flows.WorkflowParameter(Value = "http://example.com")]
            [Property(Name = LocationAuthorizationReturnPropertyName)]
            Uri locationAuthenticationReturn,

            [Resource] Authorization authorization,
            IAuthApplication application, IProvideUrl urlHelper,
            CreatedBodyResponse <Authorization> onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ReferencedDocumentDoesNotExistsResponse <Method> onAuthenticationDoesNotExist)
        {
            authorization.accountIdMaybe = default;
            authorization.authorized     = false;

            return(await await Auth.Method.ById(method, application,
                                                async (method) =>
            {
                //var authorizationIdSecure = authentication.authenticationId;
                authorization.LocationAuthentication = await method.GetLoginUrlAsync(
                    application, urlHelper, authorizationRef.id);

                //throw new ArgumentNullException();
                return await authorization.StorageCreateAsync(
                    createdId => onCreated(authorization),
                    () => onAlreadyExists());
            },
                                                () => onAuthenticationDoesNotExist().AsTask()));
        }
Ejemplo n.º 29
0
        public static IEnumerableAsync <Method> DeleteInCredentialProviders(this AccountLinks accountLinks, IAuthApplication application)
        {
            var loginProvidersWithMethods = application.LoginProviders
                                            .SelectValues()
                                            .Select(
                loginProvider =>
            {
                var method = Method.ByMethodName(loginProvider.Method, application);
                return(method, loginProvider);
            });

            var(accountLinkMethodLoginProviderKvps, unmatched1, unmatched2) = accountLinks.accountLinks
                                                                              .Match(loginProvidersWithMethods,
                                                                                     (accountLink, methodLoginProvider) => accountLink.method.id == methodLoginProvider.method.id);

            return(accountLinkMethodLoginProviderKvps
                   .Where(tpl => tpl.Item2.loginProvider is IProvideLoginManagement)
                   .Select(
                       async accountLinkLoginProvider =>
            {
                var(accountLink, (method, loginProvider)) = accountLinkLoginProvider;
                var loginManager = loginProvider as IProvideLoginManagement;
                return await loginManager.DeleteAuthorizationAsync(accountLink.externalAccountKey,
                                                                   () => method,
                                                                   why => default(Method?),
                                                                   () => default,
Ejemplo n.º 30
0
 public AuthController(IAuthApplication authApplication)
 {
     _authApplication = authApplication;
 }