private void RegisterPlayer(Player player) { var registerDialog = new InputDialog("Register", "Insert your password", true, "Submit", "Cancel"); registerDialog.Show(player); registerDialog.Response += async(senderPlayer, ev) => { if (ev.DialogButton == DialogButton.Left) { var hash = PasswordHashingService.GetPasswordHash(ev.InputText); var newAccount = new PlayerAccount { Name = player.Name, Password = hash }; await AccountRepository.AddAsync(newAccount); LoginPlayer(player); } else { player.Kick(); } }; }
public ActionResult Login(LoginModel model) { var userInfo = UsersRepository.FirstOrDefault(u => u.Login == model.Login, u => new { u.Password, u.Login, u.Id, u.DisplayName }); if (userInfo is null || PasswordHashingService.Hash(model.Password) != userInfo.Password) { return(Unauthorized("Login or password is incorrect.")); } var token = JwtService.GenerateToken(new[] { new Claim("login", userInfo.Login), new Claim("id", userInfo.Id.ToString()), new Claim("isAdministrator", (ContextProvider.Context == ContextType.Admin).ToString()), }, DateTime.UtcNow.AddMinutes(30)); Logger.LogInformation($"User got {token} token."); return(Ok(new { Token = token, model.ReturnUrl, userInfo.Login, userInfo.DisplayName, userInfo.Id })); }
public async Task <bool> IsUserValid(string login, string password) { var user = (await _unitOfWork.ApplicationUserRepository.GetAllAsync()).FirstOrDefault(item => item.Login == login); return(user != null && string.Equals(PasswordHashingService.HashSha2String(password), user.Password)); }
public MockDataProvider(PasswordHashingService passwordHashingService) { PasswordHashingService = passwordHashingService; Users = new Dictionary <string, User>(); GenerateUsers(); }
public PasswordAuthenticationController( OpenAAPContext context, PasswordHashingService hasher, IOptions <HashingOptions> hashingOptions ) { ctx = context; this.hasher = hasher; this.hashingOptions = hashingOptions; }
private void GenerateUser(string id, string name, Role role = Role.User) { (string hash, byte[] salt) = PasswordHashingService.HashAndSaltPassword("test"); User user = new User() { Id = id, Password = hash, Salt = salt, Name = name, Role = role }; Users.Add(user.Id, user); }
private void GenerateUser(string id, string name, bool isAdmin = false) { (string hash, byte[] salt) = PasswordHashingService.HashAndSaltPassword("test"); User user = new User() { Id = id, Password = hash, Salt = salt, Name = name, IsAdmin = isAdmin }; Users.Add(user.Id, user); }
public void GivenAJwtForAUser() { var hasUtil = new PasswordHashingService(); _testDataUtil.AddUser(u => u.HashedPassword = hasUtil.HashPassword("some-password")); _scenarioContext.SetUsername(_testDataUtil.GetLast <User>().Username); _scenarioContext.SetPassword("some-password"); _scenarioContext.SetUserId(_testDataUtil.GetLast <User>().Id); var jwtService = new JwtService(new AuthenticationConfiguration { JwtSigningKey = NaheulbookApiServer.JwtSigningKey, JwtExpirationDelayInMinutes = 10 }, new TimeService()); var jwt = jwtService.GenerateJwtToken(_testDataUtil.GetLast <User>().Id); _scenarioContext.SetJwt(jwt); }
private void LoginPlayer(Player player) { var message = $"Insert your password. Tries left: {player.LoginTries}/{Configuration.Instance.MaximumLogins}"; var dialog = new InputDialog("Login", message, true, "Login", "Cancel"); dialog.Show(player); dialog.Response += async(sender, ev) => { if (ev.DialogButton == DialogButton.Left) { if (player.LoginTries >= Configuration.Instance.MaximumLogins) { player.SendClientMessage(Color.OrangeRed, "You exceed maximum login tries. You have been kicked!"); await Task.Delay(Configuration.Instance.KickDelay); player.Kick(); } else if (PasswordHashingService.VerifyPasswordHash(ev.InputText, player.Account.Password)) { player.IsLoggedIn = true; PlayerLogin?.Invoke(player, new PlayerLoginEventArgs { Success = true }); } else { player.LoginTries++; player.SendClientMessage(Color.Red, "Wrong password"); dialog.Message = $"Wrong password! Retype your password! Tries left: {player.LoginTries}/{Configuration.Instance.MaximumLogins}"; LoginPlayer(player); } } else { player.Kick(); } }; }
public MockDataProvider(PasswordHashingService passwordHashingService) { PasswordHashingService = passwordHashingService; Random = new Random(); Plastics = new Dictionary <string, Plastic>(); Materials = new Dictionary <int, Material>(); StorageSites = new Dictionary <Guid, StorageSite>(); BatchTransactions = new Dictionary <Guid, List <Transaction> >(); MaterialBatches = new Dictionary <Guid, MaterialBatch>(); CustomMaterialProps = new Dictionary <Guid, CustomMaterialProp>(); CustomBatchProps = new Dictionary <Guid, CustomBatchProp>(); Users = new Dictionary <string, User>(); ApiKeys = new Dictionary <Guid, ApiKey>(); GeneratePlastics(); GenerateMaterials(); GenerateLocations(); GenerateCustomBatchProps(); GenerateBatches(); GenerateCustomMaterialProps(); GenerateUsers(); }
/// <summary> /// Attempts to authenticate a user with his unique ID and password. /// </summary> /// <param name="data">The <see cref="UserLoginData"/> as a JSON string.</param> /// <param name="subject">The ID user.</param> /// <param name="roles">Roles of the successfully authenticated user.</param> /// <param name="rights">Rights of the successfully authenticated user.</param> /// <returns>Returns whether the user was successfully authenticated.</returns> /// <exception cref="MalformedAuthenticationDataException">Thrown if the passed data doesn't match the expected model.</exception> public bool TryAuthenticate(string data, out string subject, out IEnumerable <Role> roles, out IEnumerable <Right> rights) { UserLoginData userLoginData = ParseData <UserLoginData>(data); // Initialize out-parameters subject = userLoginData.Id; roles = null; rights = new List <Right>(); // Look up user User user = UserRepository.GetUser(subject); if (user == null) { return(false); } // Check for status if (user.Disabled) { return(false); } // Check password if (PasswordHashingService.HashAndSaltPassword(userLoginData.Password, user.Salt) != user.Password) { return(false); } // Set roles and return! roles = new List <Role>() { user.Role }; return(true); }
public PasswordsController(PasswordService passwordService, PasswordHashingService passwordHashingService) { this.passwordService = passwordService; this.passwordHashingService = passwordHashingService; }
/// <summary> /// Sets up this provider for user login authentication. /// </summary> /// <param name="passwordHashingService">Provides hashing functionality.</param> /// <param name="userRepository">User repository for access to user data.</param> public UserLoginAuthenticationProvider(PasswordHashingService passwordHashingService, IReadOnlyUserRepository userRepository) { PasswordHashingService = passwordHashingService; UserRepository = userRepository; }
public static void OnChangedPasswordCommand(Player sender) { var oldPasswordDialog = new InputDialog("Enter your old password", "Enter your old password:"******"Next", "Close"); oldPasswordDialog.Show(sender); oldPasswordDialog.Response += (senderObject, ev) => { if (ev.DialogButton != DialogButton.Left) { return; } if (!PasswordHashingService.VerifyPasswordHash(ev.InputText, sender.Account.Password)) { sender.SendClientMessage(Color.Red, Messages.PasswordsDontMatch); oldPasswordDialog.Show(sender); return; } var newPasswordDialog = new InputDialog("Enter your new password", "Enter your new password:"******"Next", "Close"); newPasswordDialog.Show(sender); newPasswordDialog.Response += (objectSender, e) => { if (e.DialogButton != DialogButton.Left) { return; } if (e.InputText.Length < 1) { sender.SendClientMessage(Color.Red, Messages.PasswordCanNotBeEmptyOrNull); newPasswordDialog.Show(sender); return; } if (PasswordHashingService.VerifyPasswordHash(e.InputText, sender.Account.Password)) { sender.SendClientMessage(Color.Red, Messages.PasswordCanNotBeAsTheOldOne); newPasswordDialog.Show(sender); return; } var confirmPasswordDialog = new MessageDialog("Confirm password change", "Are you sure you want to change your password?", "Yes", "No"); confirmPasswordDialog.Show(sender); confirmPasswordDialog.Response += async(objectSender1, evv) => { if (evv.DialogButton != DialogButton.Left) { return; } var account = sender.Account; account.Password = PasswordHashingService.GetPasswordHash(e.InputText); await new PlayerAccountRepository(ConnectionFactory.GetConnection).UpdateAsync(account); sender.SendClientMessage(Color.GreenYellow, Messages.PasswordChangedSuccessfully); }; }; }; }
public static void OnBankCommand(Player sender) { if (!sender.IsLoggedInBankAccount) { if (sender.BankAccount == null) { var registerNewBankAccountDialog = new InputDialog("Enter a password", "Please enter a password to register your bank account:", true, "Accept", "Cancel"); registerNewBankAccountDialog.Show(sender); registerNewBankAccountDialog.Response += async(senderObject, e) => { if (e.DialogButton != DialogButton.Left) { return; } if (e.InputText.Length < 1 || e.InputText.Length > 20) { sender.SendClientMessage(Color.Red, Messages.InvalidPasswordLength, 1, 20); registerNewBankAccountDialog.Show(sender); return; } var hash = PasswordHashingService.GetPasswordHash(e.InputText); var newBankAccount = new PlayerBankAccount { Password = hash, PlayerId = sender.Account.Id }; await new PlayerBankAccountRepository(ConnectionFactory.GetConnection).AddAsync(newBankAccount); sender.SendClientMessage(Color.GreenYellow, Messages.BankAccountCreatedSuccessfully); }; } else { var loginBankAccount = new InputDialog("Enter a password", "Enter a password to login to your bank account:", true, "Accept", "Cancel"); loginBankAccount.Show(sender); loginBankAccount.Response += (senderObject, e) => { if (e.InputText.Length < 1 || e.InputText.Length > 20) { sender.SendClientMessage(Color.Red, Messages.InvalidPasswordLength, 1, 20); loginBankAccount.Show(sender); return; } if (!PasswordHashingService.VerifyPasswordHash(e.InputText, sender.BankAccount.Password)) { sender.SendClientMessage(Color.Red, Messages.InvalidPasswordInputted); loginBankAccount.Show(sender); return; } sender.IsLoggedInBankAccount = true; sender.SendClientMessage(Color.GreenYellow, Messages.BankAccountLoggedInSuccessfully); sender.ShowBankAccountOptions(); }; } } else { sender.ShowBankAccountOptions(); } }
public void Save(User user) { user.Password = PasswordHashingService.Hash(user.Password); UsersRepository.Save(user); }
public MockDataProvider(PasswordHashingService passwordHashingService) { Users = new Dictionary <string, User>(); Blogs = new Dictionary <string, Blog>(); Posts = new Dictionary <string, Post>(); (string hash, byte[] salt) = passwordHashingService.HashAndSaltPassword("test"); User alex = new User() { Login = "******", Password = hash, Salt = salt, Name = "Alexandre", Roles = new Role[] { Role.Administrator, Role.Author }, Biography = "I am the admin!", Website = "www.github.com" }; (hash, salt) = passwordHashingService.HashAndSaltPassword("test"); User anna = new User() { Login = "******", Password = hash, Salt = salt, Name = "Anna", Roles = new Role[] { Role.Author }, Biography = "I am some random blog author!", Website = "www.github.com" }; (hash, salt) = passwordHashingService.HashAndSaltPassword("test"); User tobi = new User() { Login = "******", Password = hash, Salt = salt, Name = "Tobias", Roles = new Role[] { Role.Author }, Biography = "Rust programmer of doom!", Website = "www.github.com" }; Users.Add(alex.Login, alex); Users.Add(anna.Login, anna); Users.Add(tobi.Login, tobi); Blog mainBlog = new Blog() { Id = "main", Title = "Main Blog", Description = "This is the main blog of this Sartre installation.", Contributors = new User[] { alex, tobi } }; Blog fashionBlog = new Blog() { Id = "fashion", Title = "Anna's Fresh Fashion Blog", Description = "A fresh take on seasonal fashion trends.", Contributors = new User[] { anna } }; Blogs.Add(mainBlog.Id, mainBlog); Blogs.Add(fashionBlog.Id, fashionBlog); for (int i = 0; i < 50; i++) { string id = $"post-{i}"; if (i < 20) { IEnumerable <User> authors = null; if (i < 10) { authors = new User[] { alex }; } else { authors = new User[] { alex, tobi }; } Posts.Add(id, new Post() { Id = id, Title = id, Blog = mainBlog, Published = true, Authors = authors, Content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan lorem magna, quis imperdiet justo fermentum eu. Duis at euismod turpis. Integer facilisis pellentesque egestas. Sed aliquet, purus et laoreet ullamcorper, lectus neque tincidunt eros, eu lacinia ante neque ac quam. Cras imperdiet magna hendrerit aliquam ultricies. Nullam sollicitudin lacus at massa volutpat, sed condimentum massa tristique. Nam hendrerit a velit ac tempus. Morbi a massa nisl. Praesent a diam dolor. Fusce luctus enim non turpis suscipit, non viverra risus facilisis. Quisque tempor pellentesque orci, a scelerisque lorem consectetur eu. " }); } else { Posts.Add(id, new Post() { Id = id, Title = id, Blog = fashionBlog, Published = true, Authors = new User[] { anna }, Content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan lorem magna, quis imperdiet justo fermentum eu. Duis at euismod turpis. Integer facilisis pellentesque egestas. Sed aliquet, purus et laoreet ullamcorper, lectus neque tincidunt eros, eu lacinia ante neque ac quam. Cras imperdiet magna hendrerit aliquam ultricies. Nullam sollicitudin lacus at massa volutpat, sed condimentum massa tristique. Nam hendrerit a velit ac tempus. Morbi a massa nisl. Praesent a diam dolor. Fusce luctus enim non turpis suscipit, non viverra risus facilisis. Quisque tempor pellentesque orci, a scelerisque lorem consectetur eu. " }); } } }
/// <summary> /// Sets up the SUT and needed services, and cleans up the users table. /// </summary> public UserRepositoryTests() { Repository = new PostgreSqlUserRepository(ConfigurationProvider.GetConfiguration()); PasswordHashingService = new PasswordHashingService(new LoggerFactory()); DatabasePurger.PurgeUsers(); }
public void SetUp() { _passwordHashingService = new PasswordHashingService(); }