Example #1
0
        private static async Task <Auth.Session> CreateSession(string userIdentification,
                                                               IAzureApplication application, IHttpRequest request)
        {
            var authentication = new Authentication
            {
                authenticationRef  = Ref <Authentication> .SecureRef(),
                authenticated      = DateTime.UtcNow,
                userIdentification = userIdentification,
                token = SecureGuid.Generate().ToString("N"),
            };

            return(await await authentication
                   .StorageCreateAsync(
                       async (authenticationDiscard) =>
            {
                var method = EastFive.Azure.Auth.Method.ByMethodName(
                    CredentialProvider.IntegrationName, application);

                var parameters = new Dictionary <string, string>()
                {
                    { "state", authentication.authenticationRef.id.ToString() },
                    { "token", authentication.token },
                    { CredentialProvider.referrerKey, "https://example.com/internal" }
                };


                return await await method.RedeemTokenAsync(parameters, application,
                                                           async(externalAccountKey, authorizationRefMaybe, loginProvider, extraParams) =>
                {
                    var authorization = new Auth.Authorization
                    {
                        authorizationRef = new Ref <Auth.Authorization>(Security.SecureGuid.Generate()),
                        Method = method.authenticationId,
                        parameters = extraParams,
                        authorized = true,
                    };

                    return await await Auth.Redirection.AuthorizeWithAccountAsync(
                        authorization,
                        async(authorizationToSave) =>
                    {
                        bool created = await authorizationToSave.StorageCreateAsync(
                            discard => true);
                    },
                        method,
                        externalAccountKey, extraParams,
                        application, request, loginProvider,
                        request.RequestUri,
                        async(accountId, authorizationUpdated) =>
                    {
                        return await CreateSessionAsync(authorization);
                    },
                        (interruptTo, accountId, authorizationUpdated) => throw new Exception($"Cannot redirect to `{interruptTo}`"),
                        (why, authorizationUpdated) => throw new Exception(why),
Example #2
0
        public async Task CanLoginWithAuthenticationRequest()
        {
            // TODO: Only get Authorization with property header
            // TODO: Can't get twice
            // TODO: IF authorized, LocationAuthentication should not be set

            // var sessionFactory = new RestApplicationFactory();
            var sessionFactory = await TestApplicationFactory.InitAsync();

            var superAdmin = await sessionFactory.SessionSuperAdminAsync();

            (superAdmin as Api.Azure.AzureApplication)
            .AddOrUpdateInstantiation(typeof(Auth.CredentialProviders.AdminLogin),
                                      async(app) =>
            {
                await 1.AsTask();
                return(new Auth.CredentialProviders.AdminLogin());
            });
            (superAdmin as Api.Azure.AzureApplication)
            .AddOrUpdateInstantiation(typeof(ProvideLoginMock),
                                      async(app) =>
            {
                await 1.AsTask();
                return(new ProvideLoginMock());
            });

            var authenticationAdmin = await superAdmin.GetAsync <Method, Method>(
                onContents :
                authentications =>
            {
                var matchingAuthentications = authentications
                                              .Where(auth => auth.name == Auth.CredentialProviders.AdminLogin.IntegrationName);
                Assert.IsTrue(matchingAuthentications.Any());
                return(matchingAuthentications.First());
            });

            var mockAuthenticationMock = await superAdmin.GetAsync <Method, Method>(
                onContents :
                authentications =>
            {
                var matchingAuthentications = authentications
                                              .Where(auth => auth.name == ProvideLoginMock.IntegrationName);
                Assert.IsTrue(matchingAuthentications.Any());
                return(matchingAuthentications.First());
            });

            var authReturnUrl         = new Uri("http://example.com/authtest");
            var authorizationIdSecure = Security.SecureGuid.Generate();
            var authorizationInvite   = new Auth.Authorization
            {
                authorizationRef             = authorizationIdSecure.AsRef <Auth.Authorization>(),
                Method                       = mockAuthenticationMock.authenticationId,
                LocationAuthenticationReturn = authReturnUrl,
            };
            var authroizationWithUrls = await superAdmin.PostAsync(authorizationInvite,
                                                                   onCreatedBody :
                                                                   (authorizationResponse, contentType) =>
            {
                Assert.AreEqual(authorizationInvite.Method.id, authorizationResponse.Method.id);
                Assert.AreEqual(authReturnUrl, authorizationResponse.LocationAuthenticationReturn);
                return(authorizationResponse);
            });


            var externalSystemUserId = Guid.NewGuid().ToString();
            var internalSystemUserId = Guid.NewGuid();

            // var mockParameters = ProvideLoginMock.GetParameters(externalSystemUserId);
            Assert.IsTrue(await superAdmin.PostAsync(
                              new Auth.AccountMapping
            {
                accountMappingId = Guid.NewGuid(),
                accountId        = internalSystemUserId,
                authorization    = authorizationInvite.authorizationRef,
            },
                              onCreated: () => true));

            var comms   = sessionFactory.GetUnauthorizedSession();
            var session = new Session
            {
                sessionId = Guid.NewGuid().AsRef <Session>(),
            };
            var token = await comms.PostAsync(session,
                                              onCreatedBody : (sessionWithToken, contentType) => sessionWithToken.token);

            (comms as Api.Azure.AzureApplication)
            .AddOrUpdateInstantiation(typeof(ProvideLoginMock),
                                      async(app) =>
            {
                await 1.AsTask();
                return(new ProvideLoginMock());
            });

            // TODO: comms.LoadToken(session.token);
            var authentication = await comms.GetAsync <Method, Method>(
                onContents :
                authentications =>
            {
                var matchingAuthentications = authentications
                                              .Where(auth => auth.name == ProvideLoginMock.IntegrationName);
                Assert.IsTrue(matchingAuthentications.Any());
                return(matchingAuthentications.First());
            });

            var responseResource = ProvideLoginMock.GetResponse(externalSystemUserId, authorizationInvite.authorizationRef.id);
            var authorizationToAthenticateSession = await await comms.GetAsync(responseResource,
                                                                               onRedirect :
                                                                               async(urlRedirect) =>
            {
                var authIdStr = urlRedirect.GetQueryParam(EastFive.Api.Azure.AzureApplication.QueryRequestIdentfier);
                var authId    = Guid.Parse(authIdStr);
                var authIdRef = authId.AsRef <Auth.Authorization>();

                // TODO: New comms here?
                return(await await comms.GetAsync(
                           (Auth.Authorization authorizationGet) => authorizationGet.authorizationRef.AssignQueryValue(authIdRef),
                           onContent:
                           async(authenticatedAuthorization) =>
                {
                    var sessionVirgin = new Session
                    {
                        sessionId = Guid.NewGuid().AsRef <Session>(),
                        authorization = new RefOptional <Auth.Authorization>(authIdRef),
                    };
                    var tokenNew = await comms.PostAsync(sessionVirgin,
                                                         onCreatedBody: (sessionWithToken, contentType) =>
                    {
                        Assert.AreEqual(internalSystemUserId, sessionWithToken.account.Value);
                        return sessionWithToken.HeaderName.PairWithValue(sessionWithToken.token);
                    });
                    comms.Headers.Add(tokenNew.Key, tokenNew.Value);

                    var integration = new Auth.Integration
                    {
                        integrationRef = Guid.NewGuid().AsRef <Auth.Integration>(),
                        accountId = internalSystemUserId,
                        Method = mockAuthenticationMock.authenticationId,
                        authorization = new RefOptional <Auth.Authorization>(authIdRef),
                    };
                    Assert.IsTrue(await comms.PostAsync(integration,
                                                        onCreated: () => true));

                    session.authorization = new RefOptional <Auth.Authorization>(authenticatedAuthorization.authorizationRef);
                    return await comms.PatchAsync(session,
                                                  onUpdatedBody:
                                                  (updated) =>
                    {
                        return updated;
                    });
                }));
            });

            Assert.AreEqual(internalSystemUserId, authorizationToAthenticateSession.account.Value);
        }