private void InitialiseSingleConnection(ITest test)
 {
     if (test is TestFixture)
     {
         SingleConnectionAuthInfo = SingleConnectionAuthSpec == null
             ? AuthenticationInfoProvider.Current.DefaultAuthInfo
             : AuthenticationInfoProvider.Current.Manager.GetAuthenticationInfo(SingleConnectionAuthSpec);
         var credentials = SingleConnectionAuthInfo.Users.ContainsKey("mainUser")
             ? SingleConnectionAuthInfo.Users["mainUser"]
             : SingleConnectionAuthInfo.Users.First().Value;
         SharedSession = GetClient(test.Id).CreateSession(PrivateAuthentication.WithCredentials(credentials.Company.Name, credentials.Login, credentials.Password));
         SharedSession.Authenticate();
         var connection = new AuthApiConnection();
         if (!((test.Properties.Get(TestCaseExAttribute.SuppressAuthenticationParameterName) as bool?).GetValueOrDefault(false)))
         {
             connection.Authenticate(SharedSession.Authentication().Session);
         }
         else
         {
             connection.SuppressAuthentication = true;
         }
         test.Properties.Add(AuthApiConnectionParameterName, connection);
     }
     else if (test is TestMethod)
     {
         ITest parentFixture = test.Parent;
         while (!(parentFixture is TestFixture))
         {
             parentFixture = parentFixture.Parent;
         }
         test.Properties.Add(AuthApiConnectionParameterName, parentFixture.Properties.Get(AuthApiConnectionParameterName));
     }
 }
        public async Task ServerTest()
        {
            var req = FieldRequest.CreateFields();

            req = req.Append(CreateFieldRequest.Builder().With(ResourceId.Activity, FieldType.Number, "test").Build().Content);

            var built = ((CreateFieldsRequest.IBuilderWithRecord)req).Build();

            IPrivateClient client = PrivateClient.CreateClient(new PrivateServerSettings {
                ServerUrl = new Uri("http://namtest3-web.dynamic.ps.porters.local"), LoggerFactory = TestLoggerFactoryAttribute.CurrentLoggerFactory
            });

            using (var session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
            {
                var fields = await session.CallAsync(built);

                Assume.That(fields.FieldFailed, Has.Count.EqualTo(0));
                Assume.That(fields.FieldSuccess, Has.Count.GreaterThan(0));
                var mapping = fields.FieldSuccess.ToDictionary(entry => entry.Value, entry => entry.Key);

                var res = await session.CallAsync(FieldRequest.GetFields().Select(FieldProperty.Name).WhereGuid(fields.FieldSuccess.Values));

                var conv = res
                           .ToDictionary(fieldEntry => mapping[(Guid)fieldEntry.Value[FieldProperty.Id]], fieldEntry => fieldEntry.Value);
                Assert.That(res, Has.Count.GreaterThan(0));
            }
        }
        public override void AfterTest(ITest test)
        {
            // ignore assemblies
            if (test != null && test.IsSuite && test.ClassName == null)
            {
                if (SharedSession != null)
                {
                    FinalisingPrivateFixtures(test, SharedSession);
                }
                else
                {
                    var authInfo    = test.Properties.Get(TestInitAuthInfoPropertyName) as MultiItemAuthenticationInfo;
                    var credentials = authInfo.Users.ContainsKey("mainUser") ? authInfo.Users["mainUser"] : authInfo.Users.First().Value;
                    using (var session = GetClient(test.Id)
                                         .CreateSession(PrivateAuthentication.WithCredentials(credentials.Company.Name, credentials.Login, credentials.Password), InitSessionOptions()))
                    {
                        FinalisingPrivateFixtures(test, session);
                    }
                }

                DisposeAuthenticationInfo(test);
            }

            if (init != null && test != null && init.Item2 == test.Id)
            {
                init.Item1.Dispose();
            }

            base.AfterTest(test);
        }
 /// <summary>
 /// Get PrivateSession
 /// </summary>
 /// <param name=""></param>
 public ISession <PrivateAuthentication> GetPrivateSession(string company, string username, string password)
 {
     if (_privateClient != null)
     {
         return(_privateClient.CreateSession(PrivateAuthentication.WithCredentials(company, username, password), null));
     }
     return(null);
 }
Exemple #5
0
        public void SetUp()
        {
            string serverUrl = "http://namtest2-web.dynamic.ps.porters.local";
            PrivateServerSettings settings = new PrivateServerSettings();

            settings.ServerUrl = new Uri(serverUrl);
            client             = PrivateClient.CreateClient(settings);
            session            = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password"));
            Assume.That(session.Authenticate(), Is.True, "Cannot login to the server!");
        }
 public AuthResponseCode Unsubscribe(string appId, string redirectUrl, string scope, string companyName, string login, string password, bool doLoginInAdvance = true)
 {
     if (doLoginInAdvance)
     {
         using (var privateApiSession = DoLogin(companyName, login, password))
         {
             return(Unsubscribe(appId, redirectUrl, scope, privateApiSession.Authentication()));
         }
     }
     return(Unsubscribe(appId, redirectUrl, scope, privateApiAuthData: PrivateAuthentication.WithCredentials(companyName, login, password)));
 }
        internal static ApiClient GetApiClient_ForPrivateApplication(string Username, string Password, ILogger Logger)
        {
            string       PrivateApplication_ConsumerKey = Settings.PrivateApplication_ConsumerKey;
            APITokenData APITokenData    = Factory.GetAPITokenData_AndSave(Username, Password, Logger);
            var          IAuthentication = new PrivateAuthentication(PrivateApplication_ConsumerKey, APITokenData.APIToken);

            string    ApiBaseUri = Settings.ApiBaseUri;
            ApiClient ApiClient  = new ApiClient(ApiBaseUri, IAuthentication, Logger);

            return(ApiClient);
        }
Exemple #8
0
        public void TestPrivateAuthenticationSuccess()
        {
            IPrivateClient client = PrivateClient.CreateClient(new PrivateServerSettings {
                ServerUrl = new Uri("http://namtest3-web.dynamic.ps.porters.local")
            });

            using (var session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
            {
                var result = session.Call(MetaDataRequest.LastUpdated(1));
                Assert.That(result.LastUpdateDate, Is.GreaterThan(0));
            }
        }
Exemple #9
0
        public async Task UpdateSingleField()
        {
            IPrivateClient client = PrivateClient.CreateClient(new PrivateServerSettings {
                ServerUrl = new Uri("http://namtest2-web.dynamic.ps.porters.local"), LoggerFactory = TestLoggerFactoryAttribute.CurrentLoggerFactory
            });

            using (var session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
            {
                var req = await session.CallAsync(FieldRequest.UpdateField().Field("Client.P_Name".ToField()).Label("Woof"));

                Assert.That(req);
            }
        }
        private void frmSample_Load(object sender, EventArgs e)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls12
                                                              | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

            if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "token.txt"))
            {
                txtToken.Text = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "token.txt");
                CompanyToken  = txtToken.Text;
                auth          = new Pepperi.SDK.PrivateAuthentication(DeveloperKey, CompanyToken);
                client        = new ApiClient(APIBaseAddress, auth, new PepperiLogger());
            }
        }
        internal static APITokenData GetAPITokenData_AndSave(string Username, string Password, ILogger Logger)
        {
            string ApiTokenBaseUri = Settings.ApiTokenBaseUri;
            string PrivateApplication_ConsumerKey = Settings.PrivateApplication_ConsumerKey;

            APITokenData APITokenData = PrivateAuthentication.GetAPITokenData(ApiTokenBaseUri, PrivateApplication_ConsumerKey, Username, Password, Logger);

            //save APITokenData.BaseURI in Settings (eg, file)
            Settings.ApiBaseUriFromTokenOrOauth = APITokenData.BaseURI;

            //save APITokenData.APIToken in Settings (eg, file)
            Settings.PrivateApplication_ApiToken = APITokenData.APIToken;

            return(APITokenData);
        }
Exemple #12
0
        public async Task DeleteSingleRecordI()
        {
            using (var client = PrivateClient.CreateClient(new PrivateServerSettings()
            {
                ServerUrl = new Uri("http://deletetest-web.dynamic.ps.porters.local"), LoggerFactory = TestLoggerFactoryAttribute.CurrentLoggerFactory
            }))
                using (var session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
                {
                    var request = DeleteRecordRequest.Builder().Append(ResourceId.Process, 10001, 10002);

                    var response = await session.CallAsync(request);

                    Assert.That(response.DeletedRecords, Has.Count.EqualTo(1));
                    Assert.That(response.DeletedRecords.Keys, Does.Contain(ResourceId.Process));
                    Assert.That(response.DeletedRecords[ResourceId.Process], Has.Count.EqualTo(2));
                    Assert.That(response.DeletedRecords[ResourceId.Process], Does.Contain(10001));
                    Assert.That(response.DeletedRecords[ResourceId.Process], Does.Contain(10002));
                }
        }
Exemple #13
0
        public async Task CreateSingleRecordOnServer()
        {
            using (var client = PrivateClient.CreateClient(new PrivateServerSettings()
            {
                ServerUrl = new Uri("http://namtest2-web.dynamic.ps.porters.local"), LoggerFactory = TestLoggerFactoryAttribute.CurrentLoggerFactory
            }))
                using (var session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
                {
                    var request = ResourceRequest.CreateRecords()
                                  .Append(ResourceId.Recruiter, builder => builder.Append("P_Name", "test record 3").Append("P_Client", new CreateRecordRequest.Reference("key1")).Append("P_Owner", 1), "req1")
                                  .Append(ResourceId.Client, builder => builder.Append("P_Name", "test record").Append("P_Owner", 1), "key1")
                                  .Append(ResourceId.Client, builder => builder.Append("P_Name", "test record 2").Append("P_Owner", 1), "key2")
                                  .Append(ResourceId.Client, builder => builder.Append("P_Name", "test record 3").Append("P_Owner", 1), "key3")
                                  .Build();
                    var response = await session.CallAsync(request);

                    Assert.That(response.Errors, Is.Empty);
                    Assert.That(response.RecordIds, Has.Count.EqualTo(4));
                }
        }
        internal static ApiClient GetApiClient_ForPrivateApplication(string APIToken, ILogger Logger)
        {
            #region validate input

            if (APIToken == null || APIToken.Trim().Length == 0)
            {
                throw new PepperiException("Invalid argument. Api token can not be empty.");
            }

            #endregion

            string ApiBaseUri = Settings.ApiBaseUri;
            string PrivateApplication_ConsumerKey = Settings.PrivateApplication_ConsumerKey;

            var IAuthentication = new PrivateAuthentication(PrivateApplication_ConsumerKey, APIToken);

            ApiClient ApiClient = new ApiClient(ApiBaseUri, IAuthentication, Logger);

            return(ApiClient);
        }
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         var token = PrivateAuthentication.GetAPITokenData(APIBaseAddress, DeveloperKey, txtEmail.Text, txtPassword.Text, Logger);
         if (token.APIToken == Guid.Empty.ToString())
         {
             throw new Exception("user or passsword are incorrect.");
         }
         txtToken.Text = token.APIToken;
         System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "token.txt", token.APIToken);
         auth   = new PrivateAuthentication(DeveloperKey, token.APIToken);
         client = new ApiClient(APIBaseAddress, auth, Logger);
         MessageBox.Show("Connected!");
     }
     catch (Exception ex)
     {
         MessageBox.Show("Not Connected!. reason: " + ex.ToString());
     }
 }
            public async Task RetrievesData()
            {
                PrivateClient client = PrivateClient.CreateClient(new PrivateServerSettings {
                    ServerUrl = new Uri("http://arwyntest-web.dynamic.ps.porters.local")
                });

                using (PrivateSession session = client.CreateSession(PrivateAuthentication.WithCredentials("TestCompany", "*****@*****.**", "password")))
                {
                    var request = ResourceRequest.GetRecords(ResourceId.Process)
                                  .WithFields(FieldCollection.Builder()
                                              .Append("Process.P_PhaseMemo".ToField())
                                              .Build())
                                  .WithRecords(10003);
                    var result = await session.CallAsync(request);

                    Assert.That(result.RecordData.Count, Is.EqualTo(1));
                    Assert.That(result.RecordData.First().Version, Is.EqualTo(1));
                    Assert.That(result.RecordData.First().Count, Is.EqualTo(2));
                    Assert.That(result.RecordData.First().RecordId, Is.EqualTo(10003));
                    Assert.That(result.RecordData.First()["Process.P_PhaseMemo".ToField()], Is.EqualTo("サンプル選考プロセスメモ"));
                }
            }
        public override void BeforeTest(ITest test)
        {
            var client = GetClient(test.Id);

            // ignore assemblies
            if (test.IsSuite && test.ClassName == null)
            {
                return;
            }

            List <AggregateException> errors = new List <AggregateException>();
            var authInfo    = GetInitialisationAuthData(test);
            var credentials = authInfo.Users.ContainsKey("mainUser") ? authInfo.Users["mainUser"] : authInfo.Users.First().Value;

            test.Properties.Add(TestInitAuthInfoPropertyName, authInfo);

            if (SharedSession != null)
            {
                PreparingPrivateFixtures(test, errors, SharedSession);
            }
            else
            {
                using (var session = GetClient(test.Id)
                                     .CreateSession(PrivateAuthentication.WithCredentials(credentials.Company.Name, credentials.Login, credentials.Password), InitSessionOptions()))
                {
                    PreparingPrivateFixtures(test, errors, session);
                }
            }

            if (test is NUnit.Framework.Internal.TestMethod) // store auth info only for test cases, not for test fixtures
            {
                test.Properties.Add(TestAuthInfoPropertyName, GetTestAuthData(test));
            }
            if (errors.Count > 0)
            {
                Assume.That(errors, Is.Empty, $"Data Fixture Creation Error: {errors.Select(ex => ex.Message).Aggregate((a, b) => $"{a}, {b}")}");
            }
            base.BeforeTest(test);
        }
        private AuthResponseCode RunAuthorizationProcess(string appId, string redirectUrl, string scope, PrivateAuthentication privateApiAuthData, string code = "code")
        {
            ResultOauthCode   = null;
            SubscriptionTrace = SubscriptionStep.NotStarted;
            var publicApiServerUri = new Uri(TestConfig.GetValueFromConfig("PublicServer"));
            var webServerUrl       = new Uri(TestConfig.GetValueFromConfig("BaseURI"));
            var cookiesCollector   = new Dictionary <string, string>();

            Log("Initialising Autherisation Process");
            var response = SendRequest(new Uri(publicApiServerUri, OverrideInitialRelativeUrl ?? string.Format(InitialRelativeUrlTemplate, appId, redirectUrl, scope, code)),
                                       cookiesCollector, null, null);

            SubscriptionTrace |= SubscriptionStep.FirstOauthReqeust;
            var errorCode = CheckErrors(response.Headers.Location, response, redirectUrl);

            if (errorCode.HasValue)
            {
                response.Dispose();
                return(errorCode.Value);
            }

            var memcacheSessionId   = OverrideMemcacheSessionCookie ?? cookiesCollector["jmemcachedsessionid"];
            var secondStepUrlEnding = response.Headers.Location.PathAndQuery;

            response.Dispose();

            Uri thirdStepUrl = null;

            if (privateApiAuthData.Session == null)
            {
                Log("2nd stage. No session, do manual login");
                thirdStepUrl       = DoManualLogin(privateApiAuthData.Company, privateApiAuthData.Username, privateApiAuthData.Password, cookiesCollector, publicApiServerUri, new Uri(webServerUrl, secondStepUrlEnding));
                SubscriptionTrace |= SubscriptionStep.ManualLogin;
                errorCode          = CheckErrors(thirdStepUrl, null, redirectUrl);
                if (errorCode.HasValue)
                {
                    return(errorCode.Value);
                }
            }
            else
            {
                Log("2nd stage. Use existing session.");
                var version       = GetVersion(privateApiAuthData);
                var useLoginToken = version.CompareTo(HrbcVersion.Parse("3.12.23")) >= 0;
                Log($"HRBC Version {version}. UseLoginToken={useLoginToken}.");
                response = SendRequest(new Uri(webServerUrl, secondStepUrlEnding), useLoginToken
                    ? new Dictionary <string, string> {
                    ["HRBCAUTH"] = privateApiAuthData.Session
                }
                    : new Dictionary <string, string> {
                    ["PHPSESSID"] = privateApiAuthData.Session, ["HRBCACCOUNT"] = privateApiAuthData.Account
                }, null, null);

                errorCode = CheckErrors(response.Headers.Location, response, redirectUrl);
                if (errorCode.HasValue)
                {
                    response.Dispose();
                    return(errorCode.Value);
                }

                thirdStepUrl = new Uri(publicApiServerUri, response.Headers.Location.PathAndQuery);
                response.Dispose();
            }

            if (!SkipAuthorisationConfirmation)
            {
                if (AuthSessionUrlQueryCustomisation != null && thirdStepUrl.Query.Contains("session="))
                {
                    thirdStepUrl = new Uri(new string(thirdStepUrl.AbsoluteUri.TakeWhile(x => x != '?').ToArray()) + AuthSessionUrlQueryCustomisation(thirdStepUrl.Query));
                }

                Log("Auth confimation");
                response = SendRequest(thirdStepUrl, new Dictionary <string, string> {
                    ["jmemcachedsessionid"] = memcacheSessionId
                }, null, null);
                SubscriptionTrace |= SubscriptionStep.AuthorisationConfirmation;

                errorCode = CheckErrors(response.Headers.Location, response, redirectUrl, false);
                response.Dispose();
                if (errorCode.HasValue)
                {
                    return(errorCode.Value);
                }
            }

            Log("Finalise");
            response = SendRequest(new Uri(publicApiServerUri, "/v1/authorization"), new Dictionary <string, string> {
                ["jmemcachedsessionid"] = memcacheSessionId
            }, null, DenyAuthorizaton ? "permission=deny" : "permission=accept");
            SubscriptionTrace |= SubscriptionStep.AuthorisationConfirmationChoiseMade;
            errorCode          = CheckErrors(response.Headers.Location, response, redirectUrl);
            response.Dispose();
            if (errorCode.HasValue)
            {
                return(errorCode.Value);
            }

            return(AuthResponseCode.Success);
        }
Exemple #19
0
 public ISession <PrivateAuthentication> GetPrivateSession(PrivateAuthentication auth)
 {
     return(privateClient?.CreateSession(auth, InitSessionOptions()));
 }
 public AuthResponseCode Unsubscribe(string appId, string redirectUrl, string scope, PrivateAuthentication privateApiAuthData)
 {
     return(RunAuthorizationProcess(appId, redirectUrl, scope, privateApiAuthData, code: "remove"));
 }
        private HrbcVersion GetVersion(PrivateAuthentication auth)
        {
            var privateApiSession = TestBase.PrivateAuthentication.GetPrivateSession(PrivateAuthentication.NoCredentials);

            return(privateApiSession.Call <int, HrbcVersion>(MetaDataRequest.DetectCurrentVersion()));
        }