public async Task LoginUser()
        {
            var mediator = ServiceProvider.GetService <IMediator>();

            var userAgent = new UserAgentModel
            {
                UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
                Browser         = "Chrome",
                DeviceBrand     = "",
                DeviceFamily    = "Other",
                DeviceModel     = "",
                OperatingSystem = "Windows 10",
                IpAddress       = "127.0.0.1"
            };

            var request = new TokenRequest
            {
                GrantType = "password",
                ClientId  = "UnitTest",
                UserName  = "******",
                Password  = "******"
            };

            var command = new AuthenticateCommand(userAgent, request);
            var result  = await mediator.Send(command).ConfigureAwait(false);
        }
Example #2
0
        public async Task <AuthTokenDto> Login(AuthenticateCommand command)
        {
            var queryable = await this.Get(p => p.Email == command.Email);

            var person = await queryable.Include(x => x.Roles).SingleOrDefaultAsync();

            if (person == null || !EncryptSha512.VerifyPassword(command.Password, person.Password))
            {
                throw new InvalidCredentialsException("Invalid email & password");
            }

            var now         = DateTimeOffset.Now.ToUniversalTime();
            var unixNow     = now.ToUnixTimeSeconds();
            var unixExpired = now.AddYears(1).ToUnixTimeSeconds();
            var payload     = new Dictionary <string, object>
            {
                { Issdate, unixNow },
                { Expiredate, unixExpired },
                { UserId, person.Id }
            };
            var token = JWT.JsonWebToken.Encode(payload, SecretKey, JWT.JwtHashAlgorithm.HS256);

            return(new AuthTokenDto
            {
                Token = token,
                Roles = person.Roles.Select(x => x.ToPersonRoleDto().Name).ToArray(),
                Person = person.ToDto()
            });
        }
        /// <summary>
        /// Checks for permissions for the currently requested operation
        /// </summary>
        /// <param name="authenticateCommand"></param>
        /// <param name="securityKeysPair"></param>
        /// <returns></returns>
        private bool CheckPermissions(AuthenticateCommand authenticateCommand, SecurityKeysPair securityKeysPair)
        {
            bool permissionGained = false;

            if (authenticateCommand.Uri.Contains("/orders/cancelorder"))
            {
                return(securityKeysPair.ValidatePermission(PermissionsConstant.Cancel_Order));
            }
            else if (authenticateCommand.Uri.Contains("/orders/openorders"))
            {
                return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Open_Orders));
            }
            else if (authenticateCommand.Uri.Contains("/orders/closedorders"))
            {
                return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Closed_Orders));
            }
            else if (authenticateCommand.Uri.Contains("/orders/createorder"))
            {
                return(securityKeysPair.ValidatePermission(PermissionsConstant.Place_Order));
            }
            else if (authenticateCommand.Uri.Contains("trades/tradehistory") || authenticateCommand.Uri.Contains("trades/querytrades") || authenticateCommand.Uri.Contains("orders/queryorders") || authenticateCommand.Uri.Contains("trades/tradedetails"))
            {
                return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Open_Orders) || securityKeysPair.ValidatePermission(PermissionsConstant.Query_Closed_Orders));
            }
            throw new InvalidOperationException("Permission not allowed for this operation.");
        }
Example #4
0
        public async Task <Advisor> AuthenticateAsync(AuthenticateCommand command)
        {
            var advisor = await Repository.GetByUsernameAndPasswordAsync(command.Login, command.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("1312358653DF49C98DC841974DB3D775");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, advisor.ID.ToString()),
                    new Claim(ClaimTypes.Role, "admin")
                }),
                Expires            = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            advisor.SetToken(tokenHandler.WriteToken(token));

            advisor.SetPassword("");

            return(advisor);
        }
Example #5
0
 public override void ProcessAuthenticateCommand(AuthenticateCommand cmd)
 {
     this.Session.AppendResponse(
         new ServerStatusResponse(cmd.Tag,
                                  ServerStatusResponseType.NO,
                                  "AUTHENTICATE is unsupportted yet")
         );
 }
Example #6
0
        public async Task <ActionResult <AuthenticateResponse> > Authenticate(AuthenticateCommand command)
        {
            var response = await _mediator.Send(command);

            SetTokenCookie(response.RefreshToken);

            return(Ok(response));
        }
        public async Task <IActionResult> Login([FromForm] AuthenticateCommand command)
        {
            command.IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
            command.UserAgent = HttpContext.Request.Headers["User-Agent"].ToString();
            var user = await _mediator.Send(command);

            return(Ok(user));
        }
Example #8
0
 public virtual void ProcessAuthenticateCommand(AuthenticateCommand cmd)
 {
     this.Session.AppendResponse(
         new ServerStatusResponse(cmd.Tag,
                                  ServerStatusResponseType.NO,
                                  "AUTHENTICATE State Error")
         );
 }
        /// <summary>
        /// Validates the credentials related to the API Key
        /// </summary>
        /// <returns></returns>
        private bool ApiKeyValidation(AuthenticateCommand authenticateCommand)
        {
            SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(authenticateCommand.Apikey);

            if (securityKeysPair != null)
            {
                User user = _userRepository.GetUserById(securityKeysPair.UserId);
                if (user != null)
                {
                    // If the keys are system generated, then we only need to check the session timeout for the user
                    if (securityKeysPair.SystemGenerated)
                    {
                        // Calculate for how much time is allowed in the session timeout for SystemGenerated key, saved in user
                        //int activeWindow = securityKeysPair.CreationDateTime.AddMinutes(user.AutoLogout.Minutes).Minute;
                        if (securityKeysPair.LastModified.AddMinutes(user.AutoLogout.Minutes) > DateTime.Now)
                        {
                            //update activity time
                            securityKeysPair.LastModified = DateTime.Now;
                            _persistenceRepository.SaveUpdate(securityKeysPair);
                            return(true);
                        }
                        else
                        {
                            _securityKeysRepository.DeleteSecurityKeysPair(securityKeysPair);
                            throw new InvalidOperationException("Session timeout for the API Key.");
                        }
                    }
                    // Else we need to check the expiration date of the keys, and whetehr the user has permissions for
                    // commencing with the desired operation
                    else
                    {
                        if (securityKeysPair.EnableExpirationDate)
                        {
                            if (securityKeysPair.ExpirationDate > DateTime.Now)
                            {
                                return(CheckPermissions(authenticateCommand, securityKeysPair));
                            }
                            throw new InvalidOperationException("Key Expired");
                        }
                        else
                        {
                            return(CheckPermissions(authenticateCommand, securityKeysPair));
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException(string.Format("{0} {1}", "No user found against userId: ",
                                                                      securityKeysPair.UserId));
                }
            }
            else
            {
                throw new InvalidOperationException(string.Format("{0} {1}",
                                                                  "No SecurityKeysPair found against the given API Key."));
            }
            return(false);
        }
Example #10
0
 /// <summary>
 /// Constructor for UserViewModel
 /// </summary>
 public UserViewModel()
 {
     _DefaultUser        = new User();
     _DefaultMarket      = new MarketTrade();
     UpdateCommand       = new UserUpdateCommand(this);
     AuthenticateCommand = new AuthenticateCommand(this);
     LimitBuyCommand     = new LimitBuyCommand(this);
     LimitSellCommand    = new LimitSellCommand(this);
 }
Example #11
0
        public async Task <IActionResult> Login(CancellationToken cancellationToken, TokenRequest tokenRequest)
        {
            var userAgent = Request.UserAgent();
            var command   = new AuthenticateCommand(userAgent, tokenRequest);

            var result = await Mediator.Send(command, cancellationToken).ConfigureAwait(false);

            return(Ok(result));
        }
Example #12
0
        public async Task <ActionResult <AuthenticateResponse> > Authenticate(AuthenticateRequest model, CancellationToken cancellationToken)
        {
            var command = new AuthenticateCommand(model.Email, model.Password);
            await _commandProcessor.SendAsync(command, cancellationToken : cancellationToken);

            setTokenCookie(command.Response.RefreshToken);

            return(Ok(_accountRenderer.Render(command.Response)));
        }
        public static IObservable <bool> ContinueAfterAuthenticate(this ISocialPlatform socialPlatform,
                                                                   IObservable <bool> command)
        {
            var authCommand = new AuthenticateCommand(socialPlatform);

            return(authCommand
                   .Execute(Unit.Default)
                   .Where(x => x.Result)
                   .ContinueWith(command));
        }
        public async Task <string> AuthenticateAsync(AuthenticateCommand command)
        {
            var user = await _userRepository.GetAsync(command.Username);

            if (user is null)
            {
                _notificator.Handle(UserConstants.NOT_FOUND, ENotificationType.NotFound);
                _logger.LogInformation(UserLogConstants.NOT_FOUND);

                return(default);
Example #15
0
        public FluentSessionRecorder Authenticate(string username, string password, TimeSpan?timeout = null)
        {
            var defaultTimeout = TimeSpan.FromSeconds(5);

            var command = new AuthenticateCommand(username, password, timeout ?? defaultTimeout);

            _performer.Perform(command);

            return(this);
        }
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand userAuthenticate)
        {
            var user = await _mediator.Send(userAuthenticate, CancellationToken.None);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user.Data));
        }
 public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand authenticateCommand)
 {
     try
     {
         return(Ok(await Mediator.Send(authenticateCommand)));
     }
     catch (AppException ex)
     {
         return(BadRequest(new { message = ex.Message }));
     }
 }
Example #18
0
        [HttpPost("authenticate")]                      //tym postem strzelamy po token
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand command)
        {
            var user = await _usersService.Authenticate(command.Login, command.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user));
        }
Example #19
0
        public void Authenticate(string accessToken)
        {
            DoStandardPrecheck(false);

            var cmd = new AuthenticateCommand()
            {
                AccessToken = accessToken,
            };

            //Send the event
            connection.EnqueueCommand(cmd);
        }
Example #20
0
        public async Task <IActionResult> Login(CancellationToken cancellationToken, TokenRequest tokenRequest)
        {
            var userAgent = Request.UserAgent();
            var command   = new AuthenticateCommand(userAgent, tokenRequest);
            var result    = await Mediator.Send(command, cancellationToken).ConfigureAwait(false);

            return(new  OkObjectResult(new
            {
                Data = result,
                Status = StatusCodes.Status200OK
            }));
        }
Example #21
0
        public async Task <IActionResult> Login([FromBody] AuthenticateCommand command, [FromServices] AuthService authService)
        {
            var r = await authService
                    .Authenticate(command.Username, command.Senha);

            if (!r.success)
            {
                return(BadRequest(new FailViewModel(r.message)));
            }

            return(Ok(r.result));
        }
Example #22
0
        private async Task ExecuteAuthentication(Tuple <string, string> creds)
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy        = true;
            Authenticated = await App.ApiService.Authenticate(creds.Item1, creds.Item2);

            Error  = "Identifiants invalides";
            IsBusy = false;
            AuthenticateCommand.ChangeCanExecute();
        }
Example #23
0
        private async Task AuthenticateAsync(HandshakePacket handshake, CancellationToken cancellationToken = default)
        {
            byte sequenceNumber = 1;

            bool useSsl = false;

            if (_options.SslMode != SslMode.DISABLED)
            {
                bool sslAvailable = (handshake.ServerCapabilities & (long)CapabilityFlags.SSL) != 0;

                if (!sslAvailable && _options.SslMode >= SslMode.REQUIRE)
                {
                    throw new InvalidOperationException("The server doesn't support SSL encryption");
                }

                if (sslAvailable)
                {
                    var command = new SslRequestCommand(PacketConstants.Utf8Mb4GeneralCi);
                    await _channel.WriteCommandAsync(command, sequenceNumber ++, cancellationToken);

                    _channel.UpgradeToSsl();
                    useSsl = true;
                }
            }

            var authenticateCommand = new AuthenticateCommand(_options, PacketConstants.Utf8Mb4GeneralCi, handshake.Scramble, handshake.AuthPluginName);
            await _channel.WriteCommandAsync(authenticateCommand, sequenceNumber, cancellationToken);

            var packet = await _channel.ReadPacketSlowAsync(cancellationToken);

            sequenceNumber += 2;

            ThrowIfErrorPacket(packet, "Authentication error.");

            if (packet[0] == (byte)ResponseType.Ok)
            {
                return;
            }

            if (packet[0] == (byte)ResponseType.AuthPluginSwitch)
            {
                var body          = new ReadOnlySequence <byte>(packet, 1, packet.Length - 1);
                var switchRequest = new AuthPluginSwitchPacket(body);
                await HandleAuthPluginSwitch(switchRequest, sequenceNumber, useSsl, cancellationToken);
            }
            else
            {
                await AuthenticateSha256Async(packet, handshake.Scramble, sequenceNumber, useSsl, cancellationToken);
            }
        }
Example #24
0
        public async Task handler_success_authenticate()
        {
            var repository     = new Mock <IUserRepository>();
            var tokenFactory   = new Mock <ITokenFactory>();
            var tokenGenerator = new Mock <ITokenGenerator>();
            var handler        = new AuthenticateCommandHandler(repository.Object, tokenFactory.Object, new FakeHashService());
            var request        = new AuthenticateCommand("*****@*****.**", "veryhard4break!");

            repository.Setup(mock => mock.Get(It.IsAny <Login>())).ReturnsAsync(User.Make(Guid.NewGuid(), (Login)request.Login, Password.MakeFromEncrypted(request.Password), Company.Make(Guid.NewGuid(), (CompanyName)"INC")));
            tokenFactory.Setup(mock => mock.Create()).Returns(tokenGenerator.Object);

            var result = await handler.Handle(request, CancellationToken.None);

            result.Status.Should().Be(AuthenticateStatus.Success);
        }
Example #25
0
        /// <summary>
        /// Authenticates using the specified <see cref="command" />.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public async Task <AuthTokenDto> Authenticate(AuthenticateCommand command)
        {
            var request = new RequestBuilder()
                          .BaseUri(this.CombineUrl("login"))
                          .Method(HttpMethod.Post)
                          .JsonContent(command);
            var response = await this.ExecuteRequest(request);

            var json = await response.Content.ReadAsStringAsync();

            var authToken = JsonConvert.DeserializeObject <AuthTokenDto>(json);

            DefaultHeaders[HeaderAuthorization] = $"JWT {authToken.Token}";

            return(authToken);
        }
Example #26
0
        public async Task TooManyArguments()
        {
            var auth = new MockIndex <string, IAuthenticationSession>
            {
                { "PLAIN", new MockPlainTextAuth(MockPlainTextAuth.Action.Null) }
            };
            var channel         = new MockSmtpChannel();
            var mockMailBuilder = new MockMailBuilder();
            var command         = new AuthenticateCommand(auth, channel, mockMailBuilder);

            command.Initialize("MECH INITIAL");
            await command.ExecuteAsync(CancellationToken.None);

            SmtpTestHelper.AssertResponse(channel, SmtpReplyCode.InvalidArguments);
            Assert.Null(channel.AuthenticatedUser);
        }
        public async Task <Result <AuthTokenDTO> > Handle(AuthenticateCommand request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByNameAsync(request.Username);

            if (user == null)
            {
                return(Result.Failure <AuthTokenDTO>("Invalid username or password."));
            }

            if (request.GrantType.Equals("password"))
            {
                var isPassowrdValid = await _userManager.CheckPasswordAsync(user, request.Password);

                if (!isPassowrdValid)
                {
                    return(Result.Failure <AuthTokenDTO>("Invalid username or password."));
                }

                var roles = await _userManager.GetRolesAsync(user);

                var token = TokenHelper.GenerateToken(user, roles.ToArray());

                await _mediator.Publish(new TokenCreatedEvent(user.Id, token), cancellationToken);

                return(Result.Ok <AuthTokenDTO>(token));
            }
            else if (request.GrantType.Equals("refresh_token"))
            {
                var refreshTokenResult = _refreshTokenRepository.CheckRefreshToken(user.Id, request.RefreshToken);
                if (refreshTokenResult.IsFailure)
                {
                    return(Result.Failure <AuthTokenDTO>(refreshTokenResult.Error));
                }

                var roles = await _userManager.GetRolesAsync(user);

                var token = TokenHelper.GenerateToken(user, roles.ToArray());

                await _mediator.Publish(new TokenCreatedEvent(user.Id, token, oldToken : request.RefreshToken), cancellationToken);

                return(Result.Ok <AuthTokenDTO>(token));
            }
            else
            {
                return(Result.Failure <AuthTokenDTO>("Invalid Grant Type."));
            }
        }
Example #28
0
        public AuthenticateCommandUnitTest()
        {
            var userRepository = new Mock <IUsersRepository>();

            userRepository.Setup(rep => rep.GetByCpf("99999999999")).ReturnsAsync(() => new User()
            {
                Cpf     = "99999999999",
                Name    = "Teste",
                Address = "Rua teste",
                Phone   = "11999999999",
                Id      = Guid.NewGuid(),
                Email   = "*****@*****.**"
            });
            _usersRepository     = userRepository.Object;
            Settings.SecurityKey = Guid.NewGuid().ToString();
            _authenticateCommand = new AuthenticateCommand(_usersRepository, _tokenService, _notifications);
        }
Example #29
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand command)
        {
            var authResult = await Mediator.Send(command).ConfigureAwait(false);

            if (!authResult.IsSuccess)
            {
                return(BadRequest(authResult.ErrorDescription));
            }

            var cryptoKeys = new CryptoKeys
            {
                FirstPartPrivateKey  = authResult.Value.PrivateKey.Item1,
                SecondPartPrivateKey = authResult.Value.PrivateKey.Item2,
            };
            var token = _jwtTokenProvider.GenerateToken(cryptoKeys);

            return(null);
        }
Example #30
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateCommand command)
        {
            var result = await _handler.Handle(command);

            if (_handler.Invalid)
            {
                return(BadRequest(_handler.Notifications));
            }

            if (result != null)
            {
                return(Ok(result));
            }
            else
            {
                return(Unauthorized());
            }
        }
        public async Task LoginAsync(UserStatus initialStatus = UserStatus.Online)
        {

            await @lock.WriterLockAsync();

            try
            {

                if (IsLoggedIn)
                    return;

                IConnection connection = null;
                ConnectionStream stream = null;
                CommandReader reader = null;
                CommandWriter writer = null;
                ResponseTracker responseTracker = null;
                IConnectableObservable<Command> commands = null;
                IDisposable commandsDisposable = null;

                int transferCount = 0;

                SocketEndPoint endPoint = SocketEndPoint.Parse("messenger.hotmail.com:1863");

                string authTicket = null;

                while (authTicket == null)
                {

                    connection = new SocketConnection();

                    await connection.ConnectAsync(endPoint);

                    stream = new ConnectionStream(connection);

                    writer = new CommandWriter(stream);
                    reader = new CommandReader(stream, new Dictionary<string, Type> {
                        { "VER", typeof(VersionCommand) },
                        { "CVR", typeof(ClientVersionCommand) },
                        { "USR", typeof(AuthenticateCommand) },
                        { "XFR", typeof(TransferCommand) },
                        { "SYN", typeof(SynchronizeCommand) },
                        { "SBS", typeof(SbsCommand) },
                        { "MSG", typeof(MessageCommand) },
                        { "LST", typeof(UserCommand) },
                        { "LSG", typeof(GroupCommand) },
                        { "BPR", typeof(UserPropertyCommand) },
                        { "BLP", typeof(PrivacySettingCommand) },
                        { "GTC", typeof(PrivacySettingCommand) },
                        { "CHG", typeof(ChangeStatusCommand) },
                        { "UBX", typeof(BroadcastCommand) },
                        { "PRP", typeof(LocalPropertyCommand) },
                        { "NLN", typeof(UserOnlineCommand) },
                        { "ILN", typeof(InitialUserOnlineCommand) },
                        { "FLN", typeof(UserOfflineCommand) },
                        { "UUX", typeof(SendBroadcastCommand) },
                        { "NOT", typeof(NotificationCommand) },
                        { "QNG", typeof(PingCommand) },
                        { "CHL", typeof(ChallengeCommand) },
                        { "ADC", typeof(AddContactCommand) },
                        { "REM", typeof(RemoveContactCommand) },
                        { "ADG", typeof(AddGroupCommand) },
                        { "RMG", typeof(RemoveGroupCommand) },
                        { "REG", typeof(RenameGroupCommand) },  
                        { "QRY", typeof(AcceptChallengeCommand) },  
                        { "RNG", typeof(RingCommand) },
                        { "SBP", typeof(ChangeUserPropertyCommand) },
                        { "IMS", typeof(EnableIMCommand) },
                    });
                    
                    commands = reader.GetReadObservable().Publish();
                    responseTracker = new ResponseTracker(writer, commands);

                    commandsDisposable = commands.Connect();

                    var versionCommand = new VersionCommand("MSNP12");
                    var versionResponse = await responseTracker.GetResponseAsync<VersionCommand>(versionCommand, defaultTimeout);

                    if (versionResponse.Versions.Length == 0)
                        throw new ProtocolNotAcceptedException();

                    var clientVersionCommand = new ClientVersionCommand
                    {
                        LocaleId = "0x0409",
                        OsType = "winnt",
                        OsVersion = "5.0",
                        Architecture = "1386",
                        LibraryName = "MSMSGS",
                        ClientVersion = "5.0.0482",
                        ClientName = "WindowsMessenger",
                        LoginName = credentials.LoginName,
                    };

                    await responseTracker.GetResponseAsync<ClientVersionCommand>(clientVersionCommand, defaultTimeout);

                    var userCommand = new AuthenticateCommand("TWN", "I", credentials.LoginName);
                    var userResponse = await responseTracker.GetResponseAsync(userCommand, new Type[] { typeof(AuthenticateCommand), typeof(TransferCommand) }, defaultTimeout);

                    if (userResponse is AuthenticateCommand)
                    {
                        authTicket = (userResponse as AuthenticateCommand).Argument;
                    }

                    else if (userResponse is TransferCommand)
                    {
                        
                        TransferCommand transferResponse = userResponse as TransferCommand;

                        if (transferCount > 3)
                            throw new InvalidOperationException("The maximum number of redirects has been reached.");

                        transferCount++;

                        endPoint = SocketEndPoint.Parse(transferResponse.Host);

                        commandsDisposable.Dispose();

                        reader.Close();
                        writer.Close();
                        connection.Dispose();

                    }

                }

                PassportAuthentication auth = new PassportAuthentication();

                string authToken = await auth.GetToken(credentials.LoginName, credentials.Password, authTicket);

                var authCommand = new AuthenticateCommand("TWN", "S", authToken);
                var authResponse = await responseTracker.GetResponseAsync<AuthenticateCommand>(authCommand, defaultTimeout);

                var synCommand = new SynchronizeCommand(syncTimeStamp1 ?? "0", syncTimeStamp2 ?? "0");
                var synResponse = await responseTracker.GetResponseAsync<SynchronizeCommand>(synCommand, defaultTimeout);

                IDisposable syncCommandsSubscription = null;
                List<Command> syncCommands = null;

                if (synResponse.TimeStamp1 != syncTimeStamp1 || synResponse.TimeStamp2 != syncTimeStamp2)
                {

                    syncCommands = new List<Command>();

                    Type[] syncTypes = new Type[] { 
                        typeof(MessageCommand), 
                        typeof(UserCommand), 
                        typeof(GroupCommand), 
                        typeof(LocalPropertyCommand), 
                        typeof(PrivacySettingCommand),
                    };

                    syncCommandsSubscription = commands
                        .Where(c => syncTypes.Contains(c.GetType()))
                        .Catch(Observable.Empty<Command>())
                        .Subscribe(c => syncCommands.Add(c));

                    //if we're expecting users/groups, wait for them before we proceed
                    if (synResponse.UserCount + synResponse.GroupCount > 0)
                    {

                        await commands
                            .Where(c => c is UserCommand || c is GroupCommand)
                            .Take(synResponse.UserCount + synResponse.GroupCount)
                            .Timeout(defaultTimeout);

                    }

                }

                UserCapabilities capabilities = 0;
                MSNObject displayPicture = MSNObject.Empty;

                if (LocalUser != null)
                {
                    capabilities = LocalUser.Capabilities;
                    displayPicture = LocalUser.DisplayPicture;
                }

                Command changeStatusCommand = new ChangeStatusCommand(User.StatusToString(UserStatus.Online), (uint)capabilities, displayPicture != MSNObject.Empty ? displayPicture.ToString() : "0");
                await responseTracker.GetResponseAsync(changeStatusCommand, defaultTimeout);

                if (syncCommandsSubscription != null)
                    syncCommandsSubscription.Dispose();

                this.writer = writer;
                this.reader = reader;
                this.stream = stream;
                this.connection = connection;
                this.responseTracker = responseTracker;
                this.commands = commands;
                this.commandsDisposable = commandsDisposable;

                if (LocalUser == null)
                {
                    LocalUser = new LocalUser(this, credentials.LoginName);
                    userCache.Add(credentials.LoginName, new WeakReference(LocalUser));
                }

                LocalUser.Status = initialStatus;

                SyncEvents syncEvents = null;

                if (syncCommands != null)
                {
                    syncTimeStamp1 = synResponse.TimeStamp1;
                    syncTimeStamp2 = synResponse.TimeStamp2;

                    syncEvents = ProcessSyncCommands(syncCommands);
                }

                var commandsSafe = commands
                    .Catch<Command, ConnectionErrorException>(tx => Observable.Empty<Command>());

                commandsSafe.OfType<MessageCommand>().Subscribe(cmd => HandleMessages(cmd, connection));
                commandsSafe.OfType<RingCommand>().Subscribe(cmd => HandleRings(cmd, connection));
                commandsSafe.OfType<BroadcastCommand>().Subscribe(cmd => HandleBroadcasts(cmd, connection));
                commandsSafe.OfType<NotificationCommand>().Subscribe(cmd => HandleNotifications(cmd, connection));
                commandsSafe.OfType<AddContactCommand>().Subscribe(cmd => HandleNewUsers(cmd, connection));
                commandsSafe.OfType<OutCommand>().Subscribe(cmd => HandleOut(cmd, connection));
                commandsSafe.OfType<ChallengeCommand>().Subscribe(cmd => HandleChallenges(cmd, connection));
                commandsSafe.OfType<UserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<InitialUserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<UserOfflineCommand>().Subscribe(cmd => HandleOfflineUsers(cmd, connection));

                connection.Error += connection_Error;

                IsLoggedIn = true;

                OnLoggedIn();

                OnUserStatusChanged(new UserStatusEventArgs(LocalUser, initialStatus, UserStatus.Offline, true));

                if (syncEvents != null)
                    RaiseSyncEvents(syncEvents);


            }
            finally
            {
                @lock.WriterRelease();
            }

        }