public async Task <ActionResult> RegisterAssistant([FromBody] Credentials data) { if (await this._assistantRepository.Where(assistant => assistant.Username.Equals(data.Username)) != null) { throw new GenericRequestException { Title = "Failed to create a new assistant account", Error = "Username is already in use", StatusCode = 400 }; } var doctorId = (long)HttpContext.Items["Id"]; var assistant = new Assistant { Username = data.Username, Password = SecurityUtils.CreatePasswordHash(data.Password), DoctorId = doctorId }; await this._assistantRepository.Save(assistant); return(Ok()); }
public async Task Update(AppUser userParam, string password = null) { var user = await _context.Users.FindAsync(userParam.AppUserId); if (user == null) { throw new Exception("User not found"); } if (userParam.Username != user.Username) { // username has changed so check if the new username is already taken if (await _context.Users.AnyAsync(x => x.Username == userParam.Username)) { throw new Exception("Username " + userParam.Username + " is already taken"); } } // update user properties user.FirstName = userParam.FirstName; user.LastName = userParam.LastName; user.Username = userParam.Username; // update password if it was entered if (!string.IsNullOrWhiteSpace(password)) { SecurityUtils.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; } _context.Users.Update(user); await _context.SaveChangesAsync(); }
public void CreatePasswordHash_ShouldReturnInvalidHash(string plain, string salt, string expected) { // Act var hash = SecurityUtils.CreatePasswordHash(plain, Convert.FromHexString(salt)); // Assert Assert.AreNotEqual(expected, hash); }
public User CreateUserFromEmail(User user) { userJdbc.RemoveUserIfActivationExpired((string)user.Emails[0]); user.Password = SecurityUtils.CreatePasswordHash(user.Password); int userId = userJdbc.CreateUserFromEmail(user); if (userId > 0) { user.Id = userId; SendActivationMail(user); } else { user = new User(); } return(user); }
public User ResetPassword(User user, string code) { if (userJdbc.GetUserIdByEmail((string)user.Emails[0]) <= 0) { return(null); } userJdbc.RemoveUserIfActivationExpired((string)user.Emails[0]); user.Password = SecurityUtils.CreatePasswordHash(user.Password); if (userJdbc.ResetUserPassword((string)user.Emails[0], code, user.Password)) { return(userJdbc.GetUserByEmail((string)user.Emails[0])); } else { return(null); } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { SecurityUtils.CreatePasswordHash(_rootAccount.Password, out var passwordHash, out var passwordSalt); var now = DateTime.Now; modelBuilder.Entity <AppUser>().HasData(new AppUser() { AppUserId = 9999, FirstName = "", Email = "*****@*****.**", LastName = "", Username = _rootAccount.Username, AppUserRole = AppUserRole.Admin, PasswordHash = passwordHash, PasswordSalt = passwordSalt, CreatedAt = now, CreatedBy = "system", LastUpdatedAt = now, LastUpdatedBy = "system" }); }
public async Task <ActionResult> Register([FromBody] Credentials credentials) { if (await this._repository.Where(doctor => doctor.Username.Equals(credentials.Username)) != null) { throw new GenericRequestException { Title = "Failed to create a new doctor account", Error = "Username is already in use", StatusCode = 400 }; } var doctor = new Doctor { Username = credentials.Username, Password = SecurityUtils.CreatePasswordHash(credentials.Password), }; await _repository.Save(doctor); return(Ok()); }
public AppUser Create(AppUser user, string password) { if (string.IsNullOrWhiteSpace(password)) { throw new Exception("Password is required"); } if (_context.Users.Any(x => x.Username == user.Username)) { throw new Exception("Username \"" + user.Username + "\" is already taken"); } SecurityUtils.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.AppUserRole = AppUserRole.None; _context.Users.Add(user); _context.SaveChanges(); return(user); }
public async Task <IActionResult> Login([FromBody] LoginModel loginModel) { Guid userId; string userName; if (!ModelState.IsValid) { return(BadRequest(new ErrorMessageModel("Required parameter(s) are not present."))); } // Check if this user exists in database. var users = await _credStorage.GetItemsAsync(k => k.UserName == loginModel.Username); if (users.Any()) { var dbUser = users.First(); if (!SecurityUtils.ValidatePassword(loginModel.Password, dbUser.Salt, dbUser.Password)) { return(BadRequest(new ErrorMessageModel("Invalid credential."))); } // Otherwise validation succeeded userId = dbUser.UserId; userName = dbUser.UserName; } else { // Create user userId = Guid.NewGuid(); userName = loginModel.Username; var salt = SecurityUtils.GenerateSalt(); await _credStorage.CreateItemAsync(new CredentialModel { UserId = userId, UserName = loginModel.Username, Password = SecurityUtils.CreatePasswordHash(loginModel.Password, salt), Salt = salt }); } var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Value.SigningToken)); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); var claimsIdentity = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.NameIdentifier, userId.ToString()), }, JwtBearerDefaults.AuthenticationScheme); var securityTokenDescriptor = new SecurityTokenDescriptor() { Audience = _jwtConfig.Value.Audience, Issuer = _jwtConfig.Value.Issuer, Subject = claimsIdentity, SigningCredentials = signingCredentials, }; var tokenHandler = new JwtSecurityTokenHandler(); var plainToken = tokenHandler.CreateToken(securityTokenDescriptor); var signedAndEncodedToken = tokenHandler.WriteToken(plainToken); return(Ok(new JwtTokenModel(signedAndEncodedToken))); }
public User ConnectViaSocialNetwork(User user, string socialNetworkName) { var _socialNetworkClientId = ""; var _socialNetworkUserId = ""; var _issuedTo = ""; if (object.Equals(socialNetworkName, "Google")) { _socialNetworkClientId = ConfigurationManager.AppSettings["GoogleClientKey"]; var tokeninfo_request = new Oauth2Service().Tokeninfo(); tokeninfo_request.IdToken = user.SocialNetworkIdToken; var tokeninfo = tokeninfo_request.Execute(); _socialNetworkUserId = tokeninfo.UserId; _issuedTo = tokeninfo.IssuedTo; } else { //Social network does not exist return(null); } if (object.Equals(user.SocialNetworkUserId, _socialNetworkUserId) && object.Equals(_socialNetworkClientId, _issuedTo)) { // Credentials match. // Check if google user ID already exists in the system. string currentEmail = userJdbc.GetEmailBySocialNetworkUserId(socialNetworkName, user.SocialNetworkUserId); if (String.IsNullOrWhiteSpace(currentEmail)) { // Google user ID does not exist in the system. // If email already exists but has not been confirmed, delete it. userJdbc.RemoveUserIfActivationExpired((string)user.Emails[0]); //Generate random alphanumeric password const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); string randomPass = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()); user.Password = SecurityUtils.CreatePasswordHash(randomPass); //Make sure username is not null if (String.IsNullOrWhiteSpace(user.Username)) { var mail = new MailAddress((string)user.Emails[0]); user.Username = mail.User; } //Set profile pic if (String.IsNullOrWhiteSpace(user.ProfilePicURL)) { user.ProfilePicURL = Utilities.WS_API_URL + "images/profile_pics/profile_default.jpg"; } //Create New User (or update existing one) int userId = userJdbc.CreateUserViaSocialNetwork(user, socialNetworkName); if (userId <= 0) { return(null); } } else if (!object.Equals(currentEmail, user.Emails[0])) { // Google user ID already exists in the system but email has changed (probably a user changed email on social network). // If new email already exists but has not been confirmed, delete it. userJdbc.RemoveUserIfActivationExpired((string)user.Emails[0]); // Add another email to the user. userJdbc.UpdateSocialNetworkEmail(socialNetworkName, user.SocialNetworkUserId, (string)user.Emails[0]); } // Return user. return(userJdbc.GetUserByEmail((string)user.Emails[0])); } else { // Credentials did not match. return(null); } }