Is there a more idiomatic way to use Casbah to check a password?

I have the following code:

def authenticateByUsername(username: String, password:String): Boolean = {
    val user = users.findOne(MongoDBObject(USERNAME -> username))
    if(user.isDefined){
        val pw = user.get.getAs(PASSWORD)
        if(pw.isDefined) 
            BCrypt.checkpw(pw.get, password)
        else false
    }else false
}

Is there a more idiomatic way of doing this? It's an if-else nightmare, which just doesn't seem right in Scala.

Answers


You're correct that there's a better way, and in general using get (or, to a slightly lesser degree, isDefined) on an Option is a red flag. In this case you can use a for-comprehension:

def authenticateByUsername(username: String, password: String): Boolean = {
  val result: Option[Boolean] = for {
    user <- users.findOne(MongoDBObject(USERNAME -> username))
    pass <- user.getAs(PASSWORD)
  } yield BCrypt.checkpw(pass, password)

  result getOrElse false
}

Or, a little more concisely:

def authenticateByUsername(username: String, password: String): Boolean =
  users.findOne(MongoDBObject(USERNAME -> username)).flatMap(
    _.getAs(PASSWORD)
  ).map(
    BCrypt.checkpw(_, password)
  ).getOrElse(false)

The latter is essentially just a desugared version of the for-comprehension.


Need Your Help

Killing Long Running Fastcgi Processes

perl fastcgi dancer

I have a Perl Dancer web application which uses the mod_fastcgi serving method from Apache2. The application has to accept uploaded files. When a user is uploading a file and presses the stop butto...

C++ read text file in accordance with the encoding

c++ file boost

I know that file encoding is hard to determine. But is there a somehow working solution for this problem in C++? Mb boost does (I did not find any appropriate)?.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.