public void TryAutoLogIn() { _mainViewModel.IsLoadingData = true; Thread.Sleep(1200); new Task(() => { try { string username = _registryService.GetUsername(); string hash = _registryService.GetPasswordHash(); string message = string.Empty; if (_authenticationService.LogIn(username, hash, ref message)) { UserLoggedIn?.Invoke(this, username); } else { _logger.Warning($"Failed auto log in. Message: {message}."); } } catch (AuthenticationException ex) { } catch (Exception ex) { _logger.Error($"Auto log in error"); _logger.Error(ex); } _mainViewModel.IsLoadingData = false; }).Start(); }
private void Save_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(FirstName.Text) || string.IsNullOrEmpty(Username.Text) || string.IsNullOrEmpty(Password.Password) || string.IsNullOrEmpty(User.Text)) { errM.Message = "All Feilds mark with asterisk(*) Are Required"; errM.Show(); } else { if (Password.Password != ConfirmPassword.Password) { errM.Message = "New password and confirm password does not match."; errM.Show(); } else { if (Password.Password.Length < 5) { errM.Message = "Password length must not be less than five characters."; errM.Show(); } else { { UserLoggedIn.AddUser(FirstName.Text, LastName.Text, Username.Text, Password.Password, User.SelectedItem.ToString()); Hide(); } } } } }
private async Task SetToken(LoginResponse tokenResponse, LoginDuration keepLoggedIn = LoginDuration.Temporary) { LoginResponseExtended token = new LoginResponseExtended(tokenResponse); switch (keepLoggedIn) { case LoginDuration.Temporary: token.SessionExpirationDate = DateTime.Now.AddHours(3); await _localStorage.SetItemAsync("Token", token); break; case LoginDuration.KeepLoggedIn: token.SessionExpirationDate = DateTime.MaxValue; await _localStorage.SetItemAsync("Token", token); break; case LoginDuration.None: break; } await _sessionStorage.SetItemAsync("Token", token); bool isLoggedIn = await IsLoggedInAsync(); if (isLoggedIn) { UserLoggedIn?.Invoke(null, null); await PopulateUserObject(); } }
private async Task InvokeUserLoggedInAsync(bool isAutoLogin) { await RequestNewKeysAndCertificateOnLoginAsync(isAutoLogin); LoggedIn = true; UserLoggedIn?.Invoke(this, new UserLoggedInEventArgs(isAutoLogin)); }
public void Apply(UserLoggedIn @event) { AuthenticationType = @event.AuthenticationType; Email = @event.Email; ExternalId = @event.ExternalId; Name = @event.Name; }
private void ActionNode13_resultCallback(PlayFab.ClientModels.LoginResult result) { ActionNode13_result = result; // PublishEventNode var PublishEventNode15_Event = new UserLoggedIn(); System.Publish(PublishEventNode15_Event); PublishEventNode15_Result = PublishEventNode15_Event; }
public Task LoginUser(LoginUser message) { var @event = new UserLoggedIn(message.UserId, message.AuthenticationType, message.ExternalId, message.Name, message.Email); RaiseEvent(@event); return(Task.CompletedTask); }
void OnLoggedIn(UserModelView userModelView) { IsLoggedIn = true; UserLoggedIn?.Invoke(); CurrentUserModelView = userModelView; _network?.Connect(CurrentUserModelView.UserName); }
public UserLoggedInView(UserLoggedIn data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } this.Data = data; }
private async Task <Option <Unit, Error> > PublishEventAsync(Guid streamId, UserLoggedIn @event) { _session.Events.Append(streamId, @event); await _session.SaveChangesAsync(); await _eventBus.Publish(@event); return(Unit.Value.Some <Unit, Error>()); }
public IObservable <IRxn> Process(UserLoggedIn @event) { return(RxObservable.Create(() => { var mainPage = _defaultPages.MainPage(); PushRoot(mainPage, (IRxnPageModel)mainPage.BindingContext, _defaultPages.MainPageHasNav); }) .Select(_ => (IRxn)null)); }
/// <summary> /// Logs in or registers a user whose email has not already been registered. /// If successful, calls the UserLoggedIn event handler and sets the user in ApiHelper /// </summary> /// <param name="info">Information needed by the api to log a user in</param> /// <returns></returns> public static async void LoginOrRegisterAsync() { AuthenticationResult result = null; try { PublicClientApplication pca = App.AuthClient; result = await pca.AcquireTokenAsync(Globals.DefaultScopes); ApiHelper.setToken(result.AccessToken); LoginInitiated?.Invoke(DateTime.Now, null); Models.User user = await ApiHelper.GetAsync <Models.User>("User"); if (user == null || user.Email == null) { user = await ApiHelper.PostAsync <Models.User>("User"); } if (user != null && !String.IsNullOrWhiteSpace(user.Email)) { UserLoggedIn?.Invoke(DateTime.Now, user); } else { AuthError?.Invoke(DateTime.Now, "No connection to server."); } } catch (MsalException ex) { if (ex.ErrorCode != "authentication_canceled") { string message = ex.Message; if (ex.InnerException != null) { message += "\nInner Exception: " + ex.InnerException.Message; } AuthError?.Invoke(DateTime.Now, message); } } catch (System.Net.Http.HttpRequestException ex) { // Launch warning popup ContentDialog notLoggedInDialog = new ContentDialog() { Title = "Could not login", Content = "Please check your wifi signal.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); } }
public ServiceProcessor(UserLoggedIn action) { _userController = new UserController(RepositoryService.UsersRepository, RepositoryService.ChatsRepository, RepositoryService.AssistantDBRepository); _userLoggedAction = action; _lastChatsData = new Dictionary <string, LastChatData>(); _publicChatEventsHandler = new PublicChatEventsHandler(_userController); RegisterAppHandlers(); }
public static User Login(string username, string password) { int id = Context.Users.SingleOrDefault(x => x.ValidateCredentials(username, password))?.ID ?? -1; if (TryGetUser(id, out User user)) { UserLoggedIn?.Invoke(user); } return(user); }
/// <summary> /// Attempts to log in or register the user using the given provider info. /// If successful, saves their credentials for future use. /// </summary> private static async Task LoginOrRegisterAsync(ProviderInfo info) { var exists = await App.Api.GetAsync <User>("Users", info); string action = null != exists ? "Login" : "Register"; var user = await App.Api.PostAsync <ProviderInfo, User>(action, info); if (null != user && !String.IsNullOrWhiteSpace(user.Email)) { UserLoggedIn?.Invoke(DateTime.Now, user); StoreUserInfo(user.Auth); } }
//public object temp; private SlugChessService(string adress, int port) { _channel = new Channel(adress, port, ChannelCredentials.Insecure); Call = new ChessCom.ChessCom.ChessComClient(_channel); _heartbeatTimer.AutoReset = true; _heartbeatTimer.Elapsed += (o, e) => { try { if (!Call.Alive(new Heartbeat { Alive = true, Usertoken = UserData?.Usertoken ?? "" }).Alive) { UserLoggedIn.OnNext(false); UserData = new UserData(); } } catch (Grpc.Core.RpcException ex) { // EX here means Heartbeat failed for some reason. #pragma warning disable CA2200 throw ex; #pragma warning restore CA2200 } }; UserLoggedIn.Subscribe(loggedIn => { if (loggedIn) { _heartbeatTimer.Start(); Task.Run(() => { var stream = Call.ChatMessageListener(UserData); while (stream.ResponseStream.MoveNext().Result) // Gets inner exeption with status code 'Unavailable' when server closes with players logged in { //Send the message to UI thread to avoid weird race conditions. Rx should be single threaded. Dispatcher.UIThread.InvokeAsync(() => { MessageToLocal(stream.ResponseStream.Current.Message, stream.ResponseStream.Current.SenderUsername); }).Wait(); //Wait to process one before starting to process the next } stream.Dispose(); }); } else { _heartbeatTimer.Stop(); } }); }
public void LogUserIn() { if (string.IsNullOrEmpty(Username.Text) || string.IsNullOrEmpty(Password.Password)) { errM.Message = "All Fields Are Required, check your username and password."; errM.Show(); //MessageBox.Show("All Details Are Required", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); Password.Password = ""; Username.Text = ""; Username.Focus(); // } //catch (Exception ) { } } else { valid = UserLoggedIn.VerifyUser(Username.Text, Password.Password); CurrentUserLoggedInData userData = new CurrentUserLoggedInData(); if (valid == 1) { ID = UserLoggedIn.USerType(Username.Text, Password.Password); FullName = UserLoggedIn.Username(Username.Text, Password.Password); Dashboard cashier = new Dashboard(); SalePerson sales = new SalePerson(); if (Id == 1) { cashier.Show(); } else if (Id == 2) { sales.Show(); } Hide(); } else { errM.Message = "Invalid Username or Password provided, try again."; errM.ShowDialog(); Password.Password = ""; Username.Text = ""; Username.Focus(); } } }
public bool Login(string userName, string password) { var result = _dbManager.UserCollection.Find <User>(u => u.UserName == userName && u.Password == password); var foundUser = result.SingleOrDefault(); if (foundUser != null) { CurrentUser = foundUser; UserLoggedIn?.Invoke(); _dbManager.StartChatWatcher(CurrentUser.UserID); _dbManager.StartContactListWatcher(CurrentUser.UserID); return(true); } else { return(false); //! Error login error } }
public async Task ConnectAsync() { _connection = new HubConnection(url); _hubProxy = _connection.CreateHubProxy("OrderBook"); _hubProxy.On <User>("UserLogin", (u) => UserLoggedIn?.Invoke(u)); _hubProxy.On <string>("UserLogout", (n) => UserLoggedOut?.Invoke(n)); _hubProxy.On <string>("UserDisconnection", (n) => UserDisconnected?.Invoke(n)); _hubProxy.On <string>("UserReconnection", (n) => UserReconnected?.Invoke(n)); _hubProxy.On <IEnumerable <Order> >("BroadcastOrders", (n) => ReceiveNewOrder?.Invoke(n)); _hubProxy.On <string, MessageType>("NotifyUser", (n, m) => ReceiveNotification?.Invoke(n, m)); _hubProxy.On <string>("SendBidDepth", (x) => ReceiveBidDepth?.Invoke(x)); _hubProxy.On <string>("SendAskDepth", (x => ReceiveAskDepth?.Invoke(x))); _connection.Reconnecting += Reconnecting; _connection.Reconnected += Reconnected; _connection.Closed += Disconnected; ServicePointManager.DefaultConnectionLimit = 10; await _connection.Start(); }
public async Task <bool> IsLoggedInAsync() { LoginResponse token = await GetToken(); if (token != null) { if (token.AccessToken != null && token.TokenType != null) { if (CurrentlyLoggedInUser == null) { loggedIn = true; UserLoggedIn?.Invoke(null, null); await PopulateUserObject(); } return(true); } } return(false); }
private async Task <bool> CheckToken() { UserResponse currentUser = await _sessionApi.GetCurrentUserData(await GetToken()); if (currentUser == null) { return(false); } if (String.IsNullOrEmpty(currentUser.Username)) { return(false); } if (currentUser != CurrentlyLoggedInUser) { return(false); } loggedIn = true; UserLoggedIn?.Invoke(null, null); return(true); }
private void Save_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(Username.Text) || string.IsNullOrEmpty(NewPassword.Password) || string.IsNullOrEmpty(ConfirmNewPassword.Password)) { errM.Message = "All Feilds mark with asterisk(*) Are Required"; errM.Show(); } else { if (NewPassword.Password != ConfirmNewPassword.Password) { errM.Message = "New password and confirm password does not match."; errM.Show(); } else { if (NewPassword.Password.Length < 5) { errM.Message = "Password length must not be less than five characters."; errM.Show(); } else { if (UserLoggedIn.ChangePassword(Username.Text, NewPassword.Password)) { sm.Message = "New password is successfully created."; sm.Show(); Hide(); } else { errM.Message = "Incorrect username, try again."; errM.Show(); } } } } }
public IActionResult Login(UserLogin userLogin) { if (userLogin is null || !ModelState.IsValid) { return(BadRequest()); } d.UserEntity userApp = _repo.Login(userLogin.Login, userLogin.Password); if (userApp is null) { return(new ForbidResult()); } if (userApp.Disable_Until > DateTime.Now) { return(new ForbidResult($"Utilisateur bani jusqu'au {userApp.Disable_Until} : {userApp.Reason}")); } // Generate Token UserLoggedIn usrLogin = userApp.ToApiLogin(); usrLogin.Usertoken = _tokenManager.GenerateJWT(userApp); return(Ok(usrLogin)); }
public void RaiseUserLoggedIn() { UserLoggedIn?.Invoke(this, new EventArgs()); }
protected Task OnUserLoggedIn(IUser user) { return(UserLoggedIn?.Invoke(user)); }
public void HandleEvent(UserLoggedIn evt) { }
public void UserLoggedInEventHandler(UserLoggedIn e) { // Nothing todo. }
private void MetroWindow_Loaded(object sender, RoutedEventArgs e) { FirstName.Focus(); User.ItemsSource = UserLoggedIn.UserRole(); }
private void Handle(UserLoggedIn @event) { _state.LoggedIn = true; Version = @event.Version; }
private void InvokeUserLoggedIn(bool autoLogin) { LoggedIn = true; UserLoggedIn?.Invoke(this, new UserLoggedInEventArgs(autoLogin)); }
public async Task <IActionResult> Login([FromBody] UserCredentials credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // get the user to verify // NOTE: the find is case INsensitive so "Kip" will find "kip" // result is cased correctly for subsequent calls. var userToVerify = await _userManager.FindByNameAsync(credentials.UserName); if (userToVerify == null) { _logger.LogWarning("Login attempt from invalid user ({0})", credentials.UserName); return(Unauthorized()); } // check the credentials if (await _userManager.CheckPasswordAsync(userToVerify, credentials.Password)) { // thumbs up, create the Jawt var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.SECRET_KEY)); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, userToVerify.UserName) }; // TODO probably would be better to use a role manager etc, but none are available for Marten/Postgres yet. if (userToVerify.IsAGod) { claims.Add(new Claim(ClaimTypes.Role, Consts.CLAIM_GOD)); } var token = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, expires: DateTime.Now.AddMinutes(3600), // TODO: Is this a decent timeout? signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(token); _logger.LogInformation($"Login success for unchecked user ({credentials.UserName}) exact user ({userToVerify.UserName})"); var userLeagues = await _leagueService.ReadUserLeagues(userToVerify.UserName); var pickemUser = new UserLoggedIn { DefaultLeagueCode = userToVerify.DefaultLeagueCode, Email = userToVerify.Email, UserName = userToVerify.UserName, Token = tokenString, Leagues = userLeagues }; return(new OkObjectResult(pickemUser)); } else { _logger.LogWarning("Login attempt failure from user ({0})", credentials.UserName); return(Unauthorized()); } }