- package models;
- import javax.persistence.Entity;
- import javax.persistence.Column;
- import javax.persistence.Table;
- // import javax.persistence.UniqueConstraint;
- import play.libs.Codec;
- import play.db.jpa.Model;
- import play.data.validation.Email;
- import play.data.validation.Required;
- @Entity
- @Table(name="Users") // , uniqueConstraints=@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"}))
- public class User extends Model {
- protected static String UNUSABLE_PASSWORD = "!"; // hash would never match
- @Email
- @Required
- // @Column(unique=true)
- public String email;
- @Required
- public String password;
- @Required
- @Column(length=50)
- public String firstName;
- @Required
- @Column(length=50)
- public String lastName;
- public User(String email, String password, String firstName, String lastName) {
- this.email = email;
- this.firstName = firstName;
- this.lastName = lastName;
- // set the password
- setPassword(password);
- create();
- }
- @Override
- public String toString() {
- return getFullName();
- }
- public String getFullName() {
- return this.firstName + " " + this.lastName;
- }
- public void setUnusablePassword() {
- this.password = UNUSABLE_PASSWORD;
- }
- /*
- * Hash and salt the user's password
- * @param password - the plain string
- * @return void - set the password in the instance
- */
- public void setPassword(String password) {
- String salt = Codec.UUID().substring(0,5); // salts are 5 characters long (random)
- // no password -- set as unusable
- if(password.length() == 0) {
- setUnusablePassword();
- return;
- }
- // generate a password hash
- this.password = String.format("sha1$%s$%s", salt, Codec.hexSHA1(salt + password));
- }
- /*
- * Check the user's password
- * @param password - the plain string
- * @return boolean - wheter the password is correct or not
- */
- public boolean checkPassword(String password) {
- String[] passwordHash = this.password.split("\\$");
- if(passwordHash.length != 3) {
- // crashes if the password is set as unusable
- return false;
- }
- String salt = passwordHash[1];
- String passwordHashed = passwordHash[2];
- return passwordHashed.equals(Codec.hexSHA1(salt + password));
- }
- }