casualjim
12/8/2010 - 6:45 PM

DataCollection.scala

trait User extends DataCollection {
  protected val collectionName = "users"

  def validatePassword(loginOrEmail: String, password: String) = {
    val l = loginOrEmail.toLowerCase(ENGLISH)
    val u = collection.findOne(
      MongoDBObject("$or" -> Map("login" -> l, "email" -> l)),
      MongoDBObject("encrypted_password" -> 1))

    u.isDefined && isValidPassword(u.get("encrypted_password").toString, password)
  }

  private def isValidPassword(password: String, toValidate: String) = {
    try {
      Password(password).validate(Password.pepper(toValidate))
    } catch {
      case e => {
        log.error(e, "Problem when verifying password")
        false
      }
    }
  }

  def login(login: String, password: String, remoteAddress: String): Option[DBObject] = {
      val u = findByLoginOrEmail(login)

      if(u.isDefined && isValidPassword(u.get("encrypted_password").toString, password)) u
      else None
  }

  def validateRememberToken(token: String): Option[DBObject] = { None }
  def rememberMe(id: String): Option[String] = { None }

  def rememberedPassword(login: String, remoteAddress: String) {}
  def forgetMe(id: String) {}

  def findById(id: String) = collection.findOne(MongoDBObject("_id" -> new ObjectId(id)))
  def findByLoginOrEmail(loginOrEmail: String) = {
    val l = loginOrEmail.toLowerCase(ENGLISH)
    collection.findOne(MongoDBObject("$or" -> Map("login" -> l, "email" -> l)))
  }
}

object User extends User
case class MongoConfig(host: String, port: Int, database: String, user: Option[String], password: Option[String]) {
      var _db: MongoDB = null
      var _conn: MongoConnection = null
      def connection = {
        if(_conn == null) {
          _conn = MongoConnection(host, port)
        }
        _conn
      }

      def db = {
        if (_db == null) {
          val db = connection(database)
          user foreach { u => db.authenticate(u, password getOrElse "") }
          _db = db
        }
        _db
      }

      def authenticated_? = user.isDefined
    }
import com.mongodb.casbah.Imports._
import akka.util.Logging
import com.mongodb.DBRef
import org.bson.types.ObjectId

trait DataCollection extends Logging with BackchatJsonFormat {
  private var _collection: MongoCollection = null
  protected val collectionName: String

  def db: MongoDB = Config.mongo.db

  def collection = {
    if(_collection == null){
      collection_=(db(collectionName))
    }
    _collection
  }

  def collection_=(coll: MongoCollection) = {
    _collection = coll
    ensureIndexes
  }

  def ensureIndexes: Unit = { }

  def getRef(obj: MongoDBObject) = new DBRef(collection.db.underlying, collectionName, obj("_id").asInstanceOf[ObjectId])
}