Enterprise Integration Zone is brought to you in partnership with:

Enterprise Architect in HCL Technologies a $7Billion IT services organization. My role is to work as a Technology Partner for large enterprise customers providing them low cost opensource solutions around Java, Spring and vFabric stack. I am also working on various projects involving, Cloud base solution, Mobile application and Business Analytics around Spring and vFabric space. Over 23 yrs, I have build repository of technologies and tools I liked and used extensively in my day to day work. In this blog, I am putting all these best practices and tools so that it will help the people who visit my website. Krishna is a DZone MVB and is not an employee of DZone and has posted 64 posts at DZone. You can read more from them at their website. View Full User Profile

Incorporating Authorization into Play 2.x (Scala) application

04.08.2013
| 4219 views |
  • submit to reddit

For people in hurry here is the code and the steps.

In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how to use play20-auth to adopt to coffee example.

As a first step for this example we need to add dependency in Build.scala as below,

"jp.t2v" %% "play2.auth"      % "0.9",
"jp.t2v" %% "play2.auth.test" % "0.9" % "test",

We need to define a Account.scala domain object with permissions as below,

object Account extends Table[Account]("ACCOUNT") {
  lazy val database = Database.forDataSource(DB.getDataSource())
 
  def id = column[Int]("ID")
  def email = column[String]("EMAIL")
  def password = column[String]("PASSWORD")
  def name = column[String]("NAME")
  def permission = column[Permission]("PERMISSION")
  // Every table needs a * projection with the same type as the table's type parameter
  def * = id ~ email ~ password ~ name ~ permission <> (Account.apply _, Account.unapply _)

In order for Account object to accept Permission.scala object as one of the column we need to implement MappedTypeMapper for the Permission as below,

implicit val PermissionTimeMapper = MappedTypeMapper.base[Permission, String](
  d => Permission.stringValueOf(d),
  t => Permission.valueOf(t))
 
def valueOf(value: String): Permission = value match {
  case "Administrator" => Administrator
  case "NormalUser" => NormalUser
  case _ => throw new IllegalArgumentException()
}
 
def stringValueOf(value: Permission): String = value match {
  case Administrator => "Administrator"
  case NormalUser => "NormalUser"
  case _ => throw new IllegalArgumentException()
}

Next step is, we need to implement a trait AuthConfigImpl extending AuthConfig in Application.scala indicating what is the User class to authenticate, what is the column that contains the Permission information and what is the redirecting page as below,

trait AuthConfigImpl extends AuthConfig {
 
  type Id = Int
 
  type User = Account
 
  type Authority = Permission
 
  val idTag = classTag[Id]
 
  val sessionTimeoutInSeconds = 3600
 
  def resolveUser(id: Id) = Account.findById(id)
 
  def loginSucceeded(request: RequestHeader) = Redirect(routes.CoffeesController.index)
 
  def logoutSucceeded(request: RequestHeader) = Redirect(routes.Application.login)
 
  def authenticationFailed(request: RequestHeader) = Redirect(routes.Application.login)
 
  def authorizationFailed(request: RequestHeader) = Forbidden("no permission")
 
  def authorize(user: User, authority: Authority) = (user.permission, authority) match {
    case (Administrator, _) => true
    case (NormalUser, NormalUser) => true
    case _ => false
  }
}

Now we need to submit the loginForm to authenticate a user in Application.scala as below,

val loginForm = Form {
  mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, "")))
    .verifying("Invalid email or password", result => result.isDefined)
}

Account.scala authenticate method looks as below,

def authenticate(email: String, password: String): Option[Account] = {
  findByEmail(email).filter { account => password.equals(account.password) }
}

For details about integration with the action in the controller refer CoffeesController.scala as below,

object CoffeesController extends Controller with AuthElement with AuthConfigImpl {
  def delete(pk: String) = StackAction(AuthorityKey -> Administrator) { implicit request =>
    database withSession {
      Home.flashing(Coffees.findByPK(pk).delete match {
        case 0 => "failure" -> "Entity has Not been deleted"
        case x => "success" -> s"Entity has been deleted (deleted $x row(s))"
      })
    }
  }
}

Notice how we use StackAction and validate for Administrator permission in the controller.




 

Published at DZone with permission of Krishna Prasad, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)