The correct way to simultaneously use sleep mode and check

I have a situation with hibernate saving with hibernate checking and although I was thinking of several hack-ish approaches, I don’t know how best to solve this problem using hibernate saving and checking.

Simply put, I have a User object and I want to save it. But before I save it, I want to check it out. Pretty standard stuff.

The User object now has a password, and we have rules regarding valid passwords. For example: at least 8 characters, include at least 1 number, etc. I want to check out these things.

But when I continue, I need to encrypt / salt / hash the password. But after I do the salting / hashing, it is obvious that there is no reasonable way to perform the above password checks.

So, I thought I could use @PrePersist and @PreUpdate annotations for this. My thought was in the User class. I have a method called onCreate (). I marked it with @PrePersist and I am doing something like this (I have something similar to onUpdate ()):

@PrePersist protected void onCreate() { encryptPassword(); } 

I thought that when I call entityManager.persist (), it will first call checks, then call onCreate (), and then save. Thus, the checks will confirm the original, non-salt / hashed password. And salting / hashing will happen later.

When I ran my tests and debugged, I found that the methods marked with @PrePersist are called before the checks are done, that I can no longer confirm my password.

How do I properly hack / hash the password in the entityManager.persist () life cycle so that I can correctly check the salt and hash after that, and finally persist?

Thanks.

+2
java-ee hibernate hibernate-validator
source share
1 answer

Use two bean properties, one for saving and one for validation / conversion. Something like that:

 @Entity @MyCustomConstraint(...) public class User implements Serializable { // place persistence annotations here, for example @Lob @Column(...) private byte[] hashedPassword; // place validation constraints here, for example @Size(min = 8, max = 16) @Transient private String password; public byte[] getHashedPassword() { return this.hashedPassword; } protected void setHashedPassword(byte[] hashedPassword) { this.hashedPassword = hashedPassword; } public void setPassword(String password) { this.password = password; this.setHashedPassword(this.hashAndSaltMyPassword(this.password)); } protected String getPassword() { return this.password; } protected byte[] hashAndSaltMyPassword(String password) { ... } } 

Done.

+1
source share

All Articles