模型和db表中的密码和密码哈希

时间:2014-01-08 05:55:14

标签: scala postgresql-9.2 playframework-2.2 anorm

我在db中有一个表User(id, password_hash, ....)和一个模型:

case class User(
  id: Pk[Long] = NotAssigned,
  email: String,
  password: Option[String] = None,
  passwordHash: Option[String] = None
)


object User {

  def create(newUser: User): Option[Long] = //.....

  //on("password_hash" -> generatePasswordHash(newUser.password)

  def generatePasswordHash(p: String) = //....
 }

要点是Password字段仅存在模型User并且仅填写我注册新用户:

val newUser = User(email = emailFromForm, password = Some(passwordFromForm))

我只向db发送密码的哈希值。显然,当我从数据库中检索它时,Password字段为空,但PasswordHash有一个值。

我将PasswordPasswordHash作为选项,因为我认为它们应该是Options,不是吗?不过,我不确定这是对还是错。

问题是我这是一个好方法吗?

1 个答案:

答案 0 :(得分:1)

为什么你想要User.password

case class User(
  id: Pk[Long] = NotAssigned,
  email: String,
  passwordHash: String 
)

object User {
  // or maybe Option[User] or Try[User]
  def create(email: String, password: String): Option[Long] = {
    val passwordHash = hashPassword(hash)
    val newUser = User(email, passwordHash)
    // save newUser to DB
  }

  // you may want to distinguish between "no such email" and "wrong password"
  // in which case you'd have something like Either[PasswordCheckFailure, User]
  def checkPassword(email: String, password: String): Option[User] = {
    val possibleUser: Option[User] = // get user by email
    possibleUser.filter(_.passwordHash = hashPassword(password))
  }

  private def hashPassword(password: String): String = ...
}

您也可能想要加盐,例如https://crackstation.net/hashing-security.htm。在这种情况下,您可以将其存储在与密码相同的字段中,也可以添加另一个字段:

case class User(
  id: Pk[Long] = NotAssigned,
  email: String,
  passwordHash: String,
  passwordSalt: String = // generate random string
)