Skip to content

Advanced usage: request parameters

Manabu Nakamura edited this page May 11, 2013 · 2 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 => 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): Boolean =
    Message.getAuther(messageId) == 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)))
  }

}