PageRenderTime 23ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/scala/com/spamihilator/setupwizard/db/UserDAO.scala

https://github.com/michel-kraemer/spamihilator-setup-wizard
Scala | 70 lines | 31 code | 10 blank | 29 comment | 0 complexity | b2eaacc6596aa131048bfee83f5b7fef MD5 | raw file
  1. // Copyright 2011 Michel Kraemer
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package com.spamihilator.setupwizard.db
  15. import com.spamihilator.setupwizard.model.User
  16. import com.mongodb.casbah.Imports._
  17. /** A data access object for user account objects
  18. * @param db the handle to the MongoDB database
  19. * @author Michel Kraemer */
  20. class UserDAO(db: MongoDB) extends DAO[User] {
  21. private lazy val coll = db("users")
  22. coll.ensureIndex("userName")
  23. /** Converts a database object to a user
  24. * @param o the database object
  25. * @return the user */
  26. private def toUser(o: DBObject) = User(
  27. o.getAs[ObjectId]("_id").get,
  28. o.getAs[String]("userName") getOrElse "",
  29. o.getAs[String]("passwordHash") getOrElse "",
  30. o.getAs[String]("realName") getOrElse "",
  31. o.getAs[String]("email") getOrElse "",
  32. o.getAs[String]("role") getOrElse "ROLE_USER"
  33. )
  34. /** Converts a user to a database object
  35. * @param user the user to convert
  36. * @return the database object */
  37. private implicit def userToDBObject(user: User): DBObject = MongoDBObject(
  38. "userName" -> user.userName,
  39. "passwordHash" -> user.passwordHash,
  40. "realName" -> user.realName,
  41. "email" -> user.email,
  42. "role" -> user.role
  43. )
  44. override def find(): Iterable[User] = coll map toUser
  45. /** Finds a user with the given name
  46. * @param userName the user's name
  47. * @return the user or <code>None</code> if there is no user
  48. * with such a name */
  49. def find(userName: String): Option[User] =
  50. coll.findOne(MongoDBObject("userName" -> userName)) map toUser
  51. def insert(user: User) {
  52. coll += user
  53. }
  54. /** Updates a user already stored in the database
  55. * @param user a user object containing the information to update. The
  56. * user's ID must refer to an existing database item. */
  57. def update(user: User) {
  58. coll.update(MongoDBObject("_id" -> user.id), user)
  59. }
  60. }