示例#1
0
        public async Task <HrbcAccountInfoResponse> Handle(PrivateSession session, HrbcAccountInfoRequest request, Func <PrivateConnection> connectionFactory)
        {
            object cacheEntry;
            string hrbcAccount;

            if (session.Cache.TryGetValue("HrbcAccount", out cacheEntry))
            {
                hrbcAccount = (string)cacheEntry;
            }
            else
            {
                // Um.. no cookie cache? need to refresh. get login page and use cookies to refresh
                Func <string, string> cookieExtractor;
                using (var connection = connectionFactory())
                    using (var loginPage = await connection.AppendHook(PrivateConnectionHooks.ForceQuery("/index/Login")).AppendHook(PrivateConnectionHooks.CookieExtractor(out cookieExtractor)).SendAsync())
                    {
                        hrbcAccount = cookieExtractor("HRBCACCOUNT");
                        var entry = session.Cache.CreateEntry("HrbcAccount");
                        entry.SlidingExpiration = TimeSpan.FromHours(1);
                        entry.Value             = hrbcAccount;
                    }
            }
            var properties = hrbcAccount.Split('-');

            return(new HrbcAccountInfoResponse(new Dictionary <HrbcAccountInfoProperty, object> {
                { HrbcAccountInfoProperty.CompanyId, properties[0] }, { HrbcAccountInfoProperty.UserId, properties[1] }
            }));
        }
示例#2
0
        private async Task <SessionCsrfPair> GetSession(Func <PrivateConnection> connectionFactory)
        {
            Func <string, string> cookieExtractor;

            using (var connection = connectionFactory())
                using (var loginPage = await connection.AppendHook(PrivateConnectionHooks.ForceQuery("index/Login")).AppendHook(PrivateConnectionHooks.CookieExtractor(out cookieExtractor)).SendAsync())
                    using (var stream = new MemoryStream())
                        using (var reader = new StreamReader(stream))
                        {
                            var sessionId = cookieExtractor(SessionIdCookieName);

                            await loginPage.CopyToAsync(stream);

                            stream.Position = 0;
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                var m = RegexCsrf.Match(line);
                                if (m.Success)
                                {
                                    return(new SessionCsrfPair(sessionId, m.Groups[0].Value));
                                }
                            }
                            return(null);
                        }
        }
示例#3
0
        public void TestCreateFileUpload()
        {
            using (var client = PrivateClient.CreateClient(new PrivateServerSettings()
            {
                ServerUrl = server, LoggerFactory = TestLoggerFactoryAttribute.CurrentLoggerFactory
            }))
                using (var session = client.CreateSession(auth))
                {
                    var    cookie = PrivateConnectionHooks.CookieExtractor(out Func <string, string> func);
                    string token  = func.Invoke("YII_CSRF_TOKEN");

                    var str = "Client ID,Client Name,Date Updated,Updated by";

                    var createFileUploadRequest = CreateFileUploadRequest.Builder()
                                                  .FrmIf(new HRBCClientPrivate.API.File.JsonFile.FrmIf {
                        Size = "86", Name = "ImportTestCSVFile.csv", ContentType = "application/vnd.ms-excel", Content = StringToBase64String(str)
                    })
                                                  .CsrfToken(token);

                    Task <CreateFileUploadResponse> task = session.CallAsync(createFileUploadRequest.Build());
                    TestContext.Out.WriteLine("Take the second cup of coffee in meantime!");
                    CreateFileUploadResponse fieldData = task.Result;
                    Assert.That(fieldData, Is.Not.Null, "Response data is null!");
                    Assert.AreEqual(fieldData.FieldId, "Test Tester", "Wrong field name value!");
                }
        }
示例#4
0
        private async Task <LoginResponse> DoLogin(PrivateSession session, Func <PrivateConnection> connectionFactory, SessionCsrfPair sessionCsrfPair, LoginRequest request, IAuthentication cred)
        {
            if (sessionCsrfPair == null)
            {
                return(new LoginResponse(null));
            }

            try
            {
                Func <string, string>      cookieExtractor;
                Func <HttpResponseHeaders> headerExtractor;
                using (var connection = connectionFactory())
                    using (var response = await connection
                                          .AppendHook(PrivateConnectionHooks.ForceQuery("index/Login?name=yt0"))
                                          .AppendHook(PrivateConnectionHooks.CookieExtractor(out cookieExtractor))
                                          .AppendHook(PrivateConnectionHooks.HeaderExtractor(out headerExtractor))
                                          .AppendHook(Hooks.DisableAutoRedirect)
                                          .Method(PrivateConnectionMethod.Form)
                                          .SuccessCondition(code => code != 301)
                                          .SendAsync(new Form.Login {
                        Crlf = sessionCsrfPair.Csrf, Auth = new Form.Auth {
                            Company = request.Company, Username = request.Username, Password = request.Password
                        }
                    }))
                    {
                        var locationHeader = headerExtractor().Location;

                        if (locationHeader != null && !locationHeader.AbsolutePath.EndsWith("/index/login"))
                        {
                            UpdateIdInfo(session, cookieExtractor);
                            return(new LoginResponse(cookieExtractor(SessionIdCookieName)));
                        }

                        throw new AuthenticationException(cred, $"Could not login to server (cookiekey:{SessionIdCookieName}, cslf:{sessionCsrfPair.Csrf}, company:{request.Company}, user:{request.Username}, password:{request.Password}, redirect: {((locationHeader == null) ? "null" : locationHeader.AbsolutePath)}, code: {response.Code})");
                    }
            }
            catch (ConnectionResponseException e)
            {
                throw new AuthenticationException(cred, "Could not login to server", e);
            }
            catch (AggregateException e)
            {
                e.Handle(ex =>
                {
                    if (ex is ConnectionResponseException)
                    {
                        throw new AuthenticationException(cred, "Could not login to server", ex);
                    }
                    return(false);
                });
                throw e;
            }
        }
示例#5
0
        public async Task <bool> Handle(PrivateSession session, string request, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory()
                                    .SuccessCondition(code => code == 302)
                                    .AppendHook(Hooks.DisableAutoRedirect)
                                    .AppendHook(PrivateConnectionHooks.ForceQuery("index/logout")))
            {
                await connection.SendAsync();

                return(true);
            }
        }
        public async Task <bool> Handle(PrivateSession session, long id, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory().Method(PrivateConnectionMethod.Read))
            {
                connection.AppendHook(PrivateConnectionHooks.ForceQuery(FileURL));
                IConnectionResponse response = await connection.SendAsync(new DeleteRequestData()
                {
                    Id = id
                });

                return(response.Code == 200);
            }
        }
示例#7
0
        public async Task <CreateUserResponse> Handle(PrivateSession session, CreateUserRequest request, Func <PrivateConnection> connectionFactory)
        {
            var csrfToken = await session.CallAsync(MetaDataRequest.GetCrlfToken("mycompany/agents"));

            var createUserRequestEquivalentData = new JsonUser.CreateUserRequestEquivalentData
            {
                Name             = request.Name,
                AdminNewsMailFlg = request.AdminNewsMailFlg ? 1 : 0,
                ApprovalFlg      = request.ApprovalFlg ? 1 : 0,
                DeptId           = request.DeptId,
                EndDate          = request.EndDate,
                Language         = request.Language,
                Mail             = request.Mail,
                Mobile           = request.Mobile,
                MobileMail       = request.MobileMail,
                NewsMailFlg      = request.NewsMailFlg ? 1 : 0,
                StartDate        = request.StartDate,
                Tel      = request.Tel,
                TimeZone = request.TimeZone,
                Username = request.Username,
                Role     = request.Administrator ? "admin" : "user"
            };
            var requestModel = new JsonUser.CreateUserRequestEquivalent
            {
                User      = createUserRequestEquivalentData,
                CsrfToken = csrfToken
            };

            using (var connection = connectionFactory().AppendHook(PrivateConnectionHooks.ForceQuery(USER)).Method(PrivateConnectionMethod.Create))
            {
                try
                {
                    using (var response = await connection.SendAsync(requestModel))
                    {
                        var result = await response.ReadAsync <JsonUser.CreateEquivalentUserResponse>();

                        return(new CreateUserResponse(result.Id));
                    }
                }
                catch (ConnectionResponseException e)
                {
                    //FIXME this will not work correctly because response is not in privateapi format.
                    throw e.ToRequestException("Could not create a user", requestModel);
                }
            }
        }
示例#8
0
        protected virtual string determineHrbcAccount(PrivateSession session, Func <PrivateConnection> connectionFactory)
        {
            if (session.Authentication().Account != null)
            {
                return(session.Authentication().Account);
            }
            Func <string, string> cookieExtractor;

            using (var connection = connectionFactory())
            {
                //get login page and use cookie
                var task = connection.AppendHook(PrivateConnectionHooks.ForceQuery("/index/Login")).AppendHook(PrivateConnectionHooks.CookieExtractor(out cookieExtractor)).SendAsync();
                task.Wait();
                using (var loginPage = task.Result)
                {
                    var hrbcAccount = cookieExtractor("HRBCACCOUNT");
                    session.Cache.Set("HrbcAccount", hrbcAccount, TimeSpan.FromHours(1));
                    return(hrbcAccount);
                }
            }
        }
示例#9
0
        public async Task <string> Handle(PrivateSession session, string query, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory())
                using (var page = await connection.AppendHook(PrivateConnectionHooks.ForceQuery(query)).SendAsync())
                    using (var stream = new MemoryStream())
                        using (var reader = new StreamReader(stream))
                        {
                            await page.CopyToAsync(stream);

                            stream.Position = 0;
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                var m = RegexCsrf.Match(line);
                                if (m.Success)
                                {
                                    return(m.Groups[1].Value);
                                }
                            }
                            throw new RequestException("The CRLF Token could not be retrieved from this page");
                        }
        }
        public async Task <HrbcVersion> Handle(PrivateSession session, int request, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory().AppendHook(PrivateConnectionHooks.ForceQuery("index/Login")))
                using (var loginPage = await connection.SendAsync())
                    using (var stream = new MemoryStream())
                        using (var reader = new StreamReader(stream))
                        {
                            await loginPage.CopyToAsync(stream);

                            stream.Position = 0;
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                var m = RegexVersion.Match(line);
                                if (m.Success)
                                {
                                    return(HrbcVersion.Parse(m.Groups[1].Value));
                                }
                            }
                            throw new Exception("Could not detect HrbcVersion");
                        }
        }