Skip to content

Instantly share code, notes, and snippets.

@julienrf
Last active September 28, 2015 06:08
Show Gist options
  • Save julienrf/1396370 to your computer and use it in GitHub Desktop.
Save julienrf/1396370 to your computer and use it in GitHub Desktop.
Dependency injection in Scala with Play 2: it’s free
object MyApp extends Controller {
// Home page
val index = Action {
Ok(views.html.index())
}
// Login action: here I just bind a (non empty) username from the query and put it in the session
val login = Action { implicit request =>
Form(mapping("username" -> nonEmptyText)(identity)(Some(_))).bindFromRequest.fold(
noUser => redirectToIndex,
username => redirectToIndex.withSession("username" -> username)
)
}
// Logout action: clear the session and redirect to the home page
val logout = Action {
redirectToIndex.withNewSession
}
// Convenient shortcut
val redirectToIndex = Redirect(routes.MyApp.index)
}
object Secured {
// Authentication check: executes the wrapped action only if a username is found in the session
def Authenticated[A](action: Action[A]): Action[A] = Action(action.parser) { request =>
request.session.get("username") match {
case Some(user) => action(request)
case None => Unauthorized(views.html.unauthorized())
}
}
}
val index = Secured.Authenticated {
Action {
Ok(views.html.index())
}
}
object MockSecured {
def Authenticated[A](action: Action[A]) = action
}
trait Security {
def Authenticated[A](action: Action[A]): Action[A]
}
trait Secured extends Security {
override def Authenticated[A](action: Action[A]) = Action(action.parser) { request =>
// …
}
}
trait MockedSecured extends Security {
override def Authenticated[A](action: Action[A]) = action
}
trait MyApp extends Controller {
this: Security =>
val index = Authenticated {
Action {
Ok(views.html.index())
}
}
// … login and logout actions are not changed
}
package object myApp {
import play.api.Play._
val MyApp = if (isDev) {
new controllers.MyApp with controllers.MockSecured
} else {
new controllers.MyApp with controllers.Secured
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment