Skip to content

Advanced usage: request parameters

Manabu Nakamura edited this page Oct 6, 2015 · 3 revisions

Changing the authorization depending on the request parameters.

For example, a Social networking application has a function to edit messages.

A user must be able to edit their own messages but not other people's messages.

To achieve this you could define Authority as a Function:

trait AuthConfigImpl extends AuthConfig {

  // Other setup is omitted. 

  type Authority = User => Future[Boolean]

  def authorize(user: User, authority: Authority): Boolean = authority(user)

}
object Application extends Controller with AuthElement with AuthConfigImpl {

  private def sameAuthor(messageId: Int)(account: Account): Future[Boolean] =
    Message.getAutherAsync(messageId).map(_ == account)

  def edit(messageId: Int) = StackAction(AuthorityKey -> sameAuthor(messageId)) { implicit request =>
    val user = loggedIn
    val target = Message.findById(messageId)
    Ok(html.message.edit(messageForm.fill(target)))
  }

}