Exemplo n.º 1
0
        public string Authorise(AuthCredentials auth)
        {
            //Verify user is valid credentials
            var isValidAuth = Security.ValidateBackOfficeCredentials(auth.Username, auth.Password);

            //Are credentials correct?
            if (isValidAuth)
            {
                //Get the backoffice user from username
                var user = ApplicationContext.Services.UserService.GetByUsername(auth.Username);


                //Generate AuthToken DB object
                var newToken = new UmbracoAuthToken();
                newToken.IdentityId   = user.Id;
                newToken.IdentityType = IdentityAuthType.User.ToString();

                //Generate a new token for the user
                var authToken = UmbracoAuthTokenFactory.GenerateUserAuthToken(newToken);

                //Store in DB (inserts or updates existing)
                UserAuthTokenDbHelper.InsertAuthToken(authToken);

                //Return the JWT token as the response
                //This means valid login & client in our case mobile app stores token in local storage
                return(authToken.AuthToken);
            }

            //Throw unauthorised HTTP error
            var httpUnauthorised = new HttpResponseMessage(HttpStatusCode.Unauthorized);

            throw new HttpResponseException(httpUnauthorised);
        }
Exemplo n.º 2
0
 public MetricProvider(string api_endpoint, string metric_name, string reponse_body_identifier, AuthCredentials auth_credentials, Dictionary <string, double> value_mapping, SortedDictionary <string, string> labels, ResponseType responseType, ExecutionType executionType)
 {
     mApiEndpoint            = api_endpoint;
     mMetricName             = metric_name;
     mResponsebodyIdentifier = reponse_body_identifier;
     mResponseType           = responseType;
     mExecutionType          = executionType;
     mAuthCredentials        = auth_credentials;
     mValueMapping           = value_mapping;
     mLabels = labels;
     mClient = new HttpClient();
     if (mAuthCredentials != null)
     {
         if (mAuthCredentials.Token != null)
         {
             mClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mAuthCredentials.Token);
         }
         else
         {
             if (mAuthCredentials.Username != null && mAuthCredentials.Password != null)
             {
                 var byteArray = Encoding.ASCII.GetBytes(mAuthCredentials.Username + ":" + mAuthCredentials.Password);
                 mClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
             }
         }
     }
 }
        public async Task <ActionResult <UserView> > Login([FromBody] AuthCredentials creds)
        {
            var user = await db.Users.Where(u => u.LoginName == creds.LoginName).FirstOrDefaultAsync();

            if (user == null)
            {
                return(Unauthorized());
            }

            if (!hasher.CompareHashAndPassword(user.PasswordHash, creds.Password))
            {
                return(Unauthorized());
            }

            var sessionJwt    = auth.GetAuthToken(new AuthClaims(user.Id));
            var cookieOptions = new CookieOptions()
            {
                HttpOnly = true,
                MaxAge   = Constants.SESSION_EXPIRATION,
#if RELEASE
                Secure = useSecureCookies,
#endif
            };

            Response.Cookies.Append(Constants.SESSION_COOKIE_NAME, sessionJwt, cookieOptions);

            return(Ok(new UserView(user)));
        }
Exemplo n.º 4
0
 public void InvalidLoginUsingTcpSimplexChannel_NoAuthClient()
 {
     var url         = "tcp://localhost:8091/CustomAuthenticationTestHost_TcpSimplex";
     var protocol    = new TcpCustomClientProtocolSetup(true);
     var credentials = new AuthCredentials(UserName, Password);
     var connection  = new ZyanConnection(url, protocol, credentials, true, true);
 }
Exemplo n.º 5
0
 private Task <XmlRpcObject> LoginAsync(AuthCredentials credentials)
 {
     authenticationToken = null;
     isAuthenticated     = false;
     isVip = false;
     return(ApiRequest("LogIn", Arg(credentials.Username), Arg(credentials.Password), Arg("en"), Arg(UserAgent)));
 }
Exemplo n.º 6
0
        public async Task <IActionResult> Login([FromBody] AuthCredentials credentials)
        {
            if (!ValidateLogin(credentials.Login, credentials.Password))
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, credentials.Login),
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(identity),
                new AuthenticationProperties
            {
                IsPersistent = true,
                IssuedUtc    = DateTimeOffset.UtcNow,
                ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(30)
            });

            return(Ok());
        }
Exemplo n.º 7
0
 public static Proto.User FromNative(this AuthCredentials native)
 {
     return(new Proto.User
     {
         Email = native.Email,
         EmailN = native.Email,
         PasswordHash = native.PasswordHash,
     });
 }
Exemplo n.º 8
0
 public AuthCredentialsViewModel(AuthCredentials credentials)
 {
     _credentials      = credentials;
     ServerCredentials = new EmailServerCredentialsViewModel()
     {
         Model = _credentials.ServerCredentials,
         Icon  = new BitmapImage(new Uri(@"/Resources/google.png", UriKind.Relative))
     };
 }
Exemplo n.º 9
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        /// <param name="auth">Auth Credentials for last.fm</param>
        public LastFmAgent(AuthCredentials auth)
        {
            if (auth == null)
            {
                throw new ArgumentNullException("auth");
            }

            _credentials = string.Format("api_key={0}", auth.ApiKey);
        }
        public async Task <ActionResult <AuthUser> > Authenticate(AuthCredentials credentials)
        {
            var user = await _identityService.Authenticate(credentials);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            return(Ok(user));
        }
Exemplo n.º 11
0
        private AuthResult Login(string userName, string password)
        {
            lock (LoginSyncLock)
            {
                var authCredentials = new AuthCredentials(userName, password);

                var authResult = this.MainActivity?.AuthenticationService.LogIn(authCredentials);

                return(authResult);
            }
        }
Exemplo n.º 12
0
        public void InvalidLoginUsingTcpSimplexChannel_NoAuthClient()
        {
            var url         = "tcp://localhost:8091/CustomAuthenticationTestHost_TcpSimplex";
            var protocol    = new TcpCustomClientProtocolSetup(true);
            var credentials = new AuthCredentials(UserName, Password);

            using (var connection = new ZyanConnection(url, protocol, credentials, true, true))
            {
                var proxy1 = connection.CreateProxy <ISampleServer>("SampleServer");
                Assert.AreEqual("Hallo", proxy1.Echo("Hallo"));
                proxy1 = null;
            }
        }
        private async Task <AuthenticateResult> RequestLogin(AuthCredentials credentials)
        {
            if (_service is null)
            {
                return(AuthenticateResult.Fail("Auth service not configured"));
            }

            var token = await _service.LoginAsync(credentials);

            return(string.IsNullOrEmpty(token)
                                ? AuthenticateResult.Fail("Access forbidden")
                                : AuthenticateResult.Success(ProvideTokenAuthTicket(token)));
        }
Exemplo n.º 14
0
        public IActionResult Get([FromForm] AuthCredentials authCreds)
        {
            if (!authCreds.isValid)
            {
                return(BadRequest("Inserisci username e password"));
            }

            if (_auth.AuthenticateWithCredentials(authCreds.Username, authCreds.Password))
            {
                return(Ok(new { token = _jwtManager.GenerateTokenForUser(authCreds.Username) }));
            }

            return(Unauthorized());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Reestablish connection to server.
        /// </summary>
        /// <remarks>
        /// This method checks if the session is valid. If not, a new logon in perfomed automatically.
        /// Handle the NewLogonNeeded event to provide credentials.
        /// </remarks>
        /// <returns>True, if reconnecting was successfull, otherwis false </returns>
        internal bool InternalReconnect()
        {
            // When the session isn´t valid, the server process must have been restarted
            if (!RemoteDispatcher.ExistSession(_sessionID))
            {
                AuthCredentials credentials     = null;
                var             performNewLogon = true;

                // If cached auto login credentials are present
                if (_autoLoginOnExpiredSession)
                {
                    credentials = _autoLoginCredentials;
                }
                else
                {
                    var newLogonNeededEventArgs = new NewLogonNeededEventArgs();
                    if (OnNewLogonNeeded(newLogonNeededEventArgs))
                    {
                        performNewLogon = !newLogonNeededEventArgs.Cancel;
                        credentials     = newLogonNeededEventArgs.Credentials;
                    }
                    else
                    {
                        performNewLogon = false;
                    }
                }

                if (performNewLogon)
                {
                    if (credentials == null)
                    {
                        credentials = new AuthCredentials();
                    }

                    credentials.Authenticate(_sessionID, RemoteDispatcher);
                    ReconnectRemoteEvents();

                    RemoteDispatcher.ReceiveClientHeartbeat(_sessionID);
                    return(true);
                }
            }
            else
            {
                RemoteDispatcher.ReceiveClientHeartbeat(_sessionID);
                return(true);
            }
            return(false);
        }
        public string AuthoriseMember(AuthCredentials auth)
        {
            //Verify user is valid credentials - using current membership provider
            //Should be native Umbraco one
            var isValidAuth = Membership.ValidateUser(auth.Username, auth.Password);

            //Are credentials correct?
            if (isValidAuth)
            {
                //Get the member from username
                var member = ApplicationContext.Services.MemberService.GetByUsername(auth.Username);

                //Check if we have an Auth Token for user
                var hasAuthToken = UserAuthTokenDbHelper.GetAuthToken(member.Id);

                //If the token already exists
                if (hasAuthToken != null)
                {
                    //Lets just return it in the request
                    return(hasAuthToken.AuthToken);
                }

                //Else user has no token yet - so let's create one
                //Generate AuthToken DB object
                var newToken = new UmbracoAuthToken();
                newToken.IdentityId   = member.Id;
                newToken.IdentityType = IdentityAuthType.Member.ToString();

                //Generate a new token for the user
                var authToken = UmbracoAuthTokenFactory.GenerateAuthToken(newToken);

                //We insert authToken as opposed to newToken
                //As authToken now has DateTime & JWT token string on it now

                //Store in DB (inserts or updates existing)
                UserAuthTokenDbHelper.InsertAuthToken(authToken);

                //Return the JWT token as the response
                //This means valid login & client in our case mobile app stores token in local storage
                return(authToken.AuthToken);
            }

            //Throw unauthorised HTTP error
            var httpUnauthorised = new HttpResponseMessage(HttpStatusCode.Unauthorized);

            throw new HttpResponseException(httpUnauthorised);
        }
Exemplo n.º 17
0
        public UserSettingsViewModel()
        {
            var user = new User()
            {
                Name = "User"
            };
            var auth = new AuthCredentials();

            auth.Login               = "******";
            auth.Password            = "******";
            auth.ServerCredentialsId = 0;
            user.CredentialsList.Add(auth);

            var z = auth.ServerCredentials;

            Users.Add(new UserViewModel(user));
            AppStorage.Instance.Users.ForEach(x => Users.Add(new UserViewModel(x)));
        }
Exemplo n.º 18
0
        public async Task <ActionResult <UserView> > Register([FromBody] AuthCredentials creds)
        {
            if (await db.Users.AnyAsync(u => u.LoginName == creds.LoginName))
            {
                return(BadRequest("login name already exists"));
            }

            var user = new User()
            {
                LoginName    = creds.LoginName,
                PasswordHash = hasher.HashFromPassword(creds.Password),
            };

            db.Add(user);
            await db.SaveChangesAsync();

            return(Created($"/api/users/{user.Id}", new UserView(user)));
        }
Exemplo n.º 19
0
        static void CreateMetricProviders(string metricDefinitionFile)
        {
            // Read metric definition and create array of MetricDefinition objects.
            string definition = File.ReadAllText(metricDefinitionFile);

            MetricDefinition[] metricDefinitions = MetricDefinition.FromJson(definition);

            foreach (MetricDefinition def in metricDefinitions)
            {
                string service_name = def.ServiceName;
                string url          = def.Url;
                foreach (Metric metric in def.Metrics)
                {
                    string                            api_endpoint            = metric.ApiEndpoint != null ? url + metric.ApiEndpoint : null;
                    string                            metric_name             = def.ServiceName + "_" + metric.MetricName;
                    string                            reponse_body_identifier = metric.DesiredResponseField;
                    AuthCredentials                   auth_credentials        = def.AuthCredentials;
                    Dictionary <string, double>       string_value_mapping    = metric.StringValueMapping;
                    SortedDictionary <string, string> labels        = metric.Labels;
                    ResponseType                      responseType  = metric.ResponseType;
                    ExecutionType                     executionType = metric.ExecutionType;

                    // Create MetricEndpoint which executes API calls or executes a program/script
                    MetricProvider metricEndpoint = null;
                    if (executionType == ExecutionType.SCRIPT && metric.Program != null && metric.Argument != null)
                    {
                        metricEndpoint = new MetricProvider(metric_name, metric.Program, metric.Argument, labels, executionType);
                    }
                    else if (executionType == ExecutionType.API_CALL && api_endpoint != null)
                    {
                        metricEndpoint = new MetricProvider(api_endpoint, metric_name, reponse_body_identifier, auth_credentials, string_value_mapping, labels, responseType, executionType);
                    }

                    // Create Prometheus Gauges
                    GaugeConfiguration config = new GaugeConfiguration();
                    if (labels != null)
                    {
                        config.LabelNames = labels.Keys.ToArray();
                    }
                    Gauge metricGauge = Metrics.CreateGauge(name: metric_name, help: metric_name, config);
                    mPrometheusMetricManager.AddMetricStruct(metricEndpoint, metricGauge);
                }
            }
        }
Exemplo n.º 20
0
        public AuthResult LogIn(AuthCredentials authCredentials)
        {
            try
            {
                using (var webClient = new WebClient())
                {
                    var response = webClient.UploadString($"{GlobalConstants.AuthenticationServiceConstants.ApiAuthUrl}?userName={authCredentials.UserName}&password={authCredentials.Password}", string.Empty);

                    var authModel = JsonConvert.DeserializeObject <AuthResult>(response);
                    if (authModel.IsSuccess)
                    {
                        this.ServiceProvider.SharedPreferencesProvider.Save(SharedPreferencesKey, new AuthToken(authModel.AuthToken));

                        this.CurrentUser      = IsAuthenticated ? authCredentials : null;
                        this.CurrentAuthToken = authModel.AuthToken;

                        FirebaseIIdService.SendRefreshedTokenToServer(FirebaseInstanceId.Instance.Token);

                        return(new AuthResult(IsAuthenticated));
                    }
                    else
                    {
                        this.CurrentUser      = null;
                        this.CurrentAuthToken = null;

                        return(new AuthResult(false));
                    }
                }
            }
            catch (Exception ex)
            {
                this.CurrentUser      = null;
                this.CurrentAuthToken = null;

                this.ServiceProvider.LoggingService.Log(ex, LogType.Error);
            }

            return(new AuthResult(false));
        }
Exemplo n.º 21
0
        public IActionResult GetToken([FromBody] AuthCredentials authCredentials)
        {
            if (authCredentials.UserName == "welton" && authCredentials.Password == "1234")
            {
                var claims = new[] {
                    new Claim(ClaimTypes.Name, "Welton Weylle Borges Lago")
                };

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    issuer: "api.fake",
                    audience: "api.fake",
                    claims: claims,
                    expires: DateTime.UtcNow.AddMinutes(1),
                    signingCredentials: creds);

                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }));
            }

            return(BadRequest("Invalid Credentials"));
        }
Exemplo n.º 22
0
        public async Task <AuthUser> Authenticate(AuthCredentials credentials)
        {
            var user = await _userCollection.Find <UserDTO>(user => user.Email == credentials.Email).FirstOrDefaultAsync();

            if (user == null)
            {
                return(null);
            }

            if (!user.Password.Code.Equals(HashingUtility.GetHash(credentials.Password, user.Password.Salt)))
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);


            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("userId", user.Id.ToString()),
                    new Claim(ClaimTypes.Email, user.Email)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(new AuthUser()
            {
                User = GetQueryUser(user),
                Token = tokenHandler.WriteToken(token)
            });
        }
Exemplo n.º 23
0
        public HttpResponseMessage Authenticate(AuthCredentials auth)
        {
            var repo = new UserRepository();
            var user = repo.GetByCredentials(auth.Login, auth.Password);

            if (user == null)
            {
                var resp = Request.CreateResponse(HttpStatusCode.Unauthorized);
                resp.Content = new StringContent("Persmission Denied");
                return(resp);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            user.IpAdress = HttpContext.Current?.Request.UserHostAddress;
            user.Cookie   = Guid.NewGuid();

            var cookie = new CookieHeaderValue("msidt", user.Cookie.ToString());

            cookie.Domain = Request.RequestUri.Host;
            cookie.Path   = "/";


            if (user.Expire == 0)
            {
                cookie.Expires = DateTime.Now.AddSeconds(3600);
            }
            else
            {
                cookie.Expires = DateTime.Now.AddSeconds(user.Expire);
            }

            response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            repo.Complete();
            response.Content = new StringContent("Persmission Granted");
            return(response);
        }
Exemplo n.º 24
0
 public AuthLoginRequest(AuthCredentials credentials) : base("/login", Method.POST)
 {
     AddJsonBody(credentials);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Test Case:
        /// </summary>
        //[TestMethod]
        //[TestCategory("SyncManager")]
        public void MergeTest()
        {
            var    epoch       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string uniqueName  = ((DateTime.UtcNow - epoch).TotalSeconds).ToString();
            string uniqueName2 = uniqueName + "_";

            string failureMessage = string.Empty;

            UnAuthCredentials.Clear();

            using (CognitoSyncManager sm1 = new CognitoSyncManager(AuthCredentials))
            {
                sm1.WipeData(false);
                Thread.Sleep(2000);
                using (Dataset d = sm1.OpenOrCreateDataset("test"))
                {
                    d.Put(uniqueName, uniqueName);
                    d.OnSyncSuccess += delegate(object s1, SyncSuccessEventArgs e1)
                    {
                        UnAuthCredentials.Clear();

                        using (CognitoSyncManager sm2 = new CognitoSyncManager(UnAuthCredentials))
                        {
                            Thread.Sleep(2000);
                            using (Dataset d2 = sm2.OpenOrCreateDataset("test"))
                            {
                                d2.Put(uniqueName2, uniqueName2);
                                d2.OnSyncSuccess += delegate(object s2, SyncSuccessEventArgs e2)
                                {
                                    AuthCredentials.Clear();
                                    UnAuthCredentials.Clear();
                                    //now we will use auth credentials.
                                    using (CognitoSyncManager sm3 = new CognitoSyncManager(AuthCredentials))
                                    {
                                        Thread.Sleep(2000);
                                        using (Dataset d3 = sm3.OpenOrCreateDataset("test"))
                                        {
                                            bool mergeTriggered = false;
                                            d3.OnSyncSuccess += (object sender, SyncSuccessEventArgs e) =>
                                            {
                                                if (!mergeTriggered)
                                                {
                                                    failureMessage += "Expecting DatasetMerged instead of OnSyncSuccess\n";
                                                }
                                            };
                                            d3.OnSyncFailure += (object sender, SyncFailureEventArgs e) =>
                                            {
                                                failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                                            };
                                            d3.OnSyncConflict += (Dataset dataset, List <SyncConflict> syncConflicts) =>
                                            {
                                                failureMessage += "Not expecting OnSyncConflict\n";
                                                return(false);
                                            };
                                            d3.OnDatasetDeleted += (Dataset dataset) =>
                                            {
                                                failureMessage += "Not expecting OnDatasetDeleted\n";
                                                return(false);
                                            };
                                            d3.OnDatasetMerged += (Dataset ds, List <string> datasetNames) =>
                                            {
                                                mergeTriggered = true;
                                                return(true);
                                            };
#if BCL35
                                            d3.Synchronize();
#else
                                            RunAsSync(async() => await d3.SynchronizeAsync());
#endif
                                        }
                                    }
                                };
                                d2.OnSyncFailure += (object sender, SyncFailureEventArgs e) =>
                                {
                                    failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                                };
                                d2.OnSyncConflict += (Dataset dataset, List <SyncConflict> conflicts) =>
                                {
                                    failureMessage += "Not expecting OnSyncConflict\n";
                                    return(false);
                                };
                                d2.OnDatasetDeleted += (Dataset dataset) =>
                                {
                                    failureMessage += "Not expecting OnDatasetDeleted\n";
                                    return(false);
                                };
                                d2.OnDatasetMerged += (Dataset dataset, List <string> datasetNames) =>
                                {
                                    failureMessage += "Not expecting OnDatasetMerged\n";
                                    return(false);
                                };
#if BCL35
                                d2.Synchronize();
#else
                                RunAsSync(async() => await d2.SynchronizeAsync());
#endif
                            }
                        }
                    };
                    d.OnSyncFailure += delegate(object s, SyncFailureEventArgs e)
                    {
                        failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                    };
                    d.OnSyncConflict += (Dataset dataset, List <SyncConflict> syncConflicts) =>
                    {
                        failureMessage += "Not expecting OnSyncConflict\n";
                        return(false);
                    };
                    d.OnDatasetDeleted += (Dataset dataset) =>
                    {
                        failureMessage += "Not expecting OnDatasetDeleted\n";
                        return(false);
                    };
                    d.OnDatasetMerged += (Dataset dataset, List <string> datasetNames) =>
                    {
                        failureMessage += "Not expecting OnDatasetMerged\n";
                        return(false);
                    };
#if BCL35
                    d.Synchronize();
#else
                    RunAsSync(async() => await d.SynchronizeAsync());
#endif
                }
            }
            if (!string.IsNullOrEmpty(failureMessage))
            {
                Assert.Fail(failureMessage);
            }
        }
Exemplo n.º 26
0
        public void MergeTest()
        {
            var    epoch       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string uniqueName  = ((DateTime.UtcNow - epoch).TotalSeconds).ToString();
            string uniqueName2 = uniqueName + "_";

            UnAuthCredentials.Clear();

            AutoResetEvent ars            = new AutoResetEvent(false);
            string         failureMessage = string.Empty;

            CognitoSyncManager sm1           = null;
            AutoResetEvent     mainThreadArs = new AutoResetEvent(false);

            Amazon.Runtime.Internal.UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
            {
                sm1 = new CognitoSyncManager(AuthCredentials, TestRunner.RegionEndpoint);
                mainThreadArs.Set();
            });
            mainThreadArs.WaitOne();
            sm1.WipeData(false);
            Thread.Sleep(2000);
            Dataset d = sm1.OpenOrCreateDataset("test");

            d.Put(uniqueName, uniqueName);
            d.OnSyncSuccess += delegate(object s1, SyncSuccessEventArgs e1)
            {
                ars.Set();
            };
            d.OnSyncFailure += delegate(object s, SyncFailureEventArgs e)
            {
                failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                ars.Set();
            };
            d.OnSyncConflict += (Dataset dataset, List <SyncConflict> syncConflicts) =>
            {
                failureMessage += "Not expecting OnSyncConflict\n";
                return(false);
            };
            d.OnDatasetDeleted += (Dataset dataset) =>
            {
                failureMessage += "Not expecting OnDatasetDeleted\n";
                return(false);
            };
            d.OnDatasetMerged += (Dataset dataset, List <string> datasetNames) =>
            {
                failureMessage += "Not expecting OnDatasetMerged\n";
                return(false);
            };
            d.SynchronizeAsync(new AsyncOptions {
                ExecuteCallbackOnMainThread = false
            });
            ars.WaitOne();

            d.Dispose();
            sm1.Dispose();
            Utils.AssertStringIsNullOrEmpty(failureMessage);

            UnAuthCredentials.Clear();

            CognitoSyncManager sm2 = null;

            Amazon.Runtime.Internal.UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
            {
                sm2 = new CognitoSyncManager(UnAuthCredentials, TestRunner.RegionEndpoint);
                mainThreadArs.Set();
            });
            mainThreadArs.WaitOne();
            Thread.Sleep(2000);

            Dataset d2 = sm2.OpenOrCreateDataset("test");

            d2.Put(uniqueName2, uniqueName2);
            d2.OnSyncSuccess += delegate(object s2, SyncSuccessEventArgs e2)
            {
                ars.Set();
            };
            d2.OnSyncFailure += (object sender, SyncFailureEventArgs e) =>
            {
                failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                ars.Set();
            };
            d2.OnSyncConflict += (Dataset dataset, List <SyncConflict> conflicts) =>
            {
                failureMessage += "Not expecting OnSyncConflict\n";
                return(false);
            };
            d2.OnDatasetDeleted += (Dataset dataset) =>
            {
                failureMessage += "Not expecting OnDatasetDeleted\n";
                return(false);
            };
            d2.OnDatasetMerged += (Dataset dataset, List <string> datasetNames) =>
            {
                failureMessage += "Not expecting OnDatasetMerged\n";
                return(false);
            };
            d2.SynchronizeAsync(new AsyncOptions {
                ExecuteCallbackOnMainThread = false
            });
            ars.WaitOne();

            d2.Dispose();
            sm2.Dispose();
            Utils.AssertStringIsNullOrEmpty(failureMessage);

            AuthCredentials.Clear();
            UnAuthCredentials.Clear();

            CognitoSyncManager sm3 = null;

            Amazon.Runtime.Internal.UnityRequestQueue.Instance.ExecuteOnMainThread(() =>
            {
                sm3 = new CognitoSyncManager(AuthCredentials, TestRunner.RegionEndpoint);
                mainThreadArs.Set();
            });
            mainThreadArs.WaitOne();

            Thread.Sleep(2000);

            Dataset d3             = sm3.OpenOrCreateDataset("test");
            bool    mergeTriggered = false;

            d3.OnSyncSuccess += (object sender, SyncSuccessEventArgs e) =>
            {
                if (!mergeTriggered)
                {
                    failureMessage += "Expecting DatasetMerged instead of OnSyncSuccess\n";
                }
                ars.Set();
            };
            d3.OnSyncFailure += (object sender, SyncFailureEventArgs e) =>
            {
                failureMessage += string.Format("Not expecting OnSyncFailure Got exception {0}\n", e.Exception.Message);
                ars.Set();
            };
            d3.OnSyncConflict += (Dataset dataset, List <SyncConflict> syncConflicts) =>
            {
                failureMessage += "Not expecting OnSyncConflict\n";
                return(false);
            };
            d3.OnDatasetDeleted += (Dataset dataset) =>
            {
                failureMessage += "Not expecting OnDatasetDeleted\n";
                return(false);
            };
            d3.OnDatasetMerged += delegate(Dataset ds, List <string> datasetNames)
            {
                mergeTriggered = true;
                return(true);
            };
            d3.SynchronizeAsync(new AsyncOptions {
                ExecuteCallbackOnMainThread = false
            });

            ars.WaitOne();
            Utils.AssertStringIsNullOrEmpty(failureMessage);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Creates a new instance of the NewLogonNeededEventArgs class.
 /// </summary>
 /// <param name="credentials">Security credentials</param>
 /// <param name="cancel">Cancel flag</param>
 public NewLogonNeededEventArgs(AuthCredentials credentials, bool cancel)
 {
     Cancel      = cancel;
     Credentials = credentials;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Creates a new instance of the NewLogonNeededEventArgs class.
 /// </summary>
 /// <param name="credentials">Credentials for logon</param>
 public NewLogonNeededEventArgs(AuthCredentials credentials)
 {
     Cancel      = false;
     Credentials = credentials;
 }
Exemplo n.º 29
0
        /// <summary>
        /// Creates a new instance of the ZyanConnection class.
        /// </summary>
        /// <param name="serverUrl">URL of remote server (e.G. "tcp://server1:46123/myapp").</param>
        /// <param name="protocolSetup">Protocol and communication settings.</param>
        /// <param name="credentials">Login credentials.</param>
        /// <param name="autoLoginOnExpiredSession">Specifies whether the proxy should relogin automatically when the session expired.</param>
        /// <param name="keepSessionAlive">Specifies whether the session should be automaticly kept alive.</param>
        public ZyanConnection(string serverUrl, IClientProtocolSetup protocolSetup, AuthCredentials credentials, bool autoLoginOnExpiredSession, bool keepSessionAlive)
        {
            if (string.IsNullOrEmpty(serverUrl))
            {
                throw new ArgumentException(LanguageResource.ArgumentException_ServerUrlMissing, "serverUrl");
            }

            if (protocolSetup == null)
            {
                // try to select the protocol automatically
                protocolSetup = ClientProtocolSetup.GetClientProtocol(serverUrl);
                if (protocolSetup == null)
                {
                    throw new ArgumentNullException("protocolSetup");
                }
            }

            if (!protocolSetup.IsUrlValid(serverUrl))
            {
                throw new ArgumentException(LanguageResource.ArgumentException_ServerUrlIsInvalid, "serverUrl");
            }

            _proxies                   = new List <WeakReference>();
            _protocolSetup             = protocolSetup;
            _sessionID                 = Guid.NewGuid();
            _serverUrl                 = serverUrl;
            _autoLoginOnExpiredSession = autoLoginOnExpiredSession;
            _keepSessionAlive          = keepSessionAlive;

            if (_autoLoginOnExpiredSession)
            {
                _autoLoginCredentials = credentials;
            }

            _serializationHandling  = new SerializationHandlerRepository();
            CallInterceptionEnabled = false;
            _callInterceptors       = new CallInterceptorCollection();
            RegisterStandardSerializationHandlers();
            string[] addressParts = _serverUrl.Split('/');
            _componentHostName = addressParts[addressParts.Length - 1];

            _remotingChannel = _protocolSetup.CreateChannel();
            if (!ZyanSettings.DisableUrlRandomization)
            {
                _remotingChannel = ChannelWrapper.WrapChannel(_remotingChannel, _protocolSetup.ChannelName);
            }

            if (_remotingChannel != null)
            {
                var registeredChannel = ChannelServices.GetChannel(_remotingChannel.ChannelName);

                if (registeredChannel == null)
                {
                    ChannelServices.RegisterChannel(_remotingChannel, false);
                }
                else
                {
                    _remotingChannel = registeredChannel;
                }
            }
            else
            {
                throw new ApplicationException(LanguageResource.ApplicationException_NoChannelCreated);
            }

            var connectionNotification = _remotingChannel as IConnectionNotification;

            if (connectionNotification != null)
            {
                connectionNotification.ConnectionEstablished += Channel_ConnectionEstablished;
            }

            string channelName = _remotingChannel.ChannelName;

            if (credentials == null)
            {
                credentials = new AuthCredentials();
            }

            try
            {
                credentials.Authenticate(_sessionID, RemoteDispatcher);

                _registeredComponents = new List <ComponentInfo>(RemoteDispatcher.GetRegisteredComponents());
                _sessionAgeLimit      = RemoteDispatcher.SessionAgeLimit;
            }
            catch (Exception ex)
            {
                // unregister remoting channel
                var registeredChannel = ChannelServices.GetChannel(channelName);
                if (registeredChannel != null)
                {
                    ChannelServices.UnregisterChannel(registeredChannel);
                }

                // dispose channel if it's disposable
                var disposableChannel = registeredChannel as IDisposable;
                if (disposableChannel != null)
                {
                    disposableChannel.Dispose();
                }

                _remotingChannel  = null;
                _remoteDispatcher = null;
                throw ex.PreserveStackTrace();
            }

            var reconnectEvents  = new Action(ReconnectRemoteEventsCore);
            var debounceInterval = ZyanSettings.ReconnectRemoteEventsDebounceInterval.TotalMilliseconds;

            ReconnectRemoteEvents = reconnectEvents.Debounce((int)debounceInterval);

            StartKeepSessionAliveTimer();
            lock (_connections)
            {
                _connections.Add(this);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Releases unmanaged and — optionally — managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (!_isDisposed)
            {
                _isDisposed = true;

                if (_pollingTimer != null)
                {
                    _pollingTimer.Dispose();
                    _pollingTimer = null;
                }
                _pollingEnabled = false;

                if (_keepSessionAliveTimer != null)
                {
                    _keepSessionAliveTimer.Dispose();
                    _keepSessionAliveTimer = null;
                }
                try
                {
                    foreach (var zyanProxy in AliveProxies)
                    {
                        zyanProxy.RemoveAllRemoteEventHandlers();
                    }
                    RemoteDispatcher.Logoff(_sessionID);
                }
                catch (RemotingException)
                { }
                catch (SocketException)
                { }
                catch (WebException)
                { }
                catch (MessageException)
                { }
                catch (Exception ex)
                {
                    Trace.WriteLine("Unexpected exception of type {0} caught while disposing ZyanConnection: {1}", ex.GetType(), ex.Message);
                }
                finally
                {
                    lock (_connections)
                    {
                        _connections.Remove(this);
                    }
                }
                if (_remotingChannel != null)
                {
                    // unsubscribe from connection notifications
                    var connectionNotification = _remotingChannel as IConnectionNotification;
                    if (connectionNotification != null)
                    {
                        connectionNotification.ConnectionEstablished -= Channel_ConnectionEstablished;
                    }

                    // unregister remoting channel
                    var registeredChannel = ChannelServices.GetChannel(_remotingChannel.ChannelName);
                    if (registeredChannel != null && registeredChannel == _remotingChannel)
                    {
                        ChannelServices.UnregisterChannel(_remotingChannel);
                    }

                    // dispose remoting channel, if it's disposable
                    var disposableChannel = _remotingChannel as IDisposable;
                    if (disposableChannel != null)
                    {
                        disposableChannel.Dispose();
                    }

                    _remotingChannel = null;
                }
                _remoteDispatcher      = null;
                _serverUrl             = string.Empty;
                _sessionID             = Guid.Empty;
                _protocolSetup         = null;
                _serializationHandling = null;
                _componentHostName     = string.Empty;

                if (_registeredComponents != null)
                {
                    _registeredComponents.Clear();
                    _registeredComponents = null;
                }
                if (_callInterceptors != null)
                {
                    _callInterceptors.Clear();
                    _callInterceptors = null;
                }
                if (_autoLoginCredentials != null)
                {
                    _autoLoginCredentials = null;
                }
                GC.WaitForPendingFinalizers();
            }
        }