2014-01-08 91 views
0

我在數據庫表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字段在None,但PasswordHash有一個值。

我發PasswordPasswordHash是選項,因爲我認爲他們應該是Options,不應該嗎?不過,我不確定這是對還是錯。

問題是我的這是一個好方法?

回答

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 
) 
+0

也許,我不因爲我需要它僅適用於創建新用戶需要輸入密碼。在checkPassword中,你的意思是passwordHash? –

+0

我想我會刪除密碼字段,並保持passwordHash只。我會將創建的簽名更改爲與您的一樣。 –

+0

「在checkPassword中,你的意思是passwordHash?」不,我的意思是您從登錄表單中獲得的密碼,請參閱編輯。 –