I’m writing a 3-tier application using NHibernate where account passwords are saved as hash in a database.
The presentation layer calls a save method, that wants an account entity, in my service, where the password gets hashed before giving it to the repository.
So, first time an account gets saved, the password gets correctly hashed and everything is fine.
But once I have to update an account, without changing the password, the value of the password property in the account entity, is already hashed, when it gets passed through the save method of my service, it will hashed again.
My entity looks like this:
public class AccountEntity : EntityBase {
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string Email { get; set; }
public virtual bool Enabled { get; set; }
}
And my service with the save method:
public class AccountService {
private readonly IRepository<AccountEntity> _accountRepository;
private readonly IHashingProvider _hashingProvider;
public AccountService(IRepository<AccountEntity> accountRepository, IHashingProvider hashingProvider) {
_accountRepository = accountRepository;
_hashingProvider = hashingProvider;
}
public void Save(AccountEntity accountEntity) {
accountEntity.Password = _hashingProvider.Hash(accountEntity.Password);
_accountRepository.Save(accountEntity);
}
}
How can I tell NHibernate to NOT update the password? What other possibilities do I have?
I’d suggest tackling this in a way that doesn’t deal with the NHibernate layer. Simply separate the “first-time creation” operation (which requires hashing) from the “general save of any updates” operation (which doesn’t need hashing).
For example, add a
Create()method to your AccountService for creating the account the first time, which can do the hashing and delegate toSave(). The generalSave()can then just persist the object normally.You could also add a method for persisting a change in password, which can run the newly-requested password through the hash and calling
Save().