Silhouette authorization using request data - scala

I use Silhouette and Play 2.4 and I'd like to restrict actions if a SecuredRequest body contains something wrong.
I know, I should use trait Authorization as described by official docs.
I'm trying to do the following:
case class WithCheck(checkCriteria: String) extends Authorization[User, CookieAuthenticator] {
def isAuthorized[B](user: User, authenticator: CookieAuthenticator)(implicit request: Request[B], messages: Messages) = {
Future.successful(user.criteria == checkCriteria)
}
}
and than
def myAction = SecuredAction(WithCheck("bar")) { implicit request =>
val foo = ...// deserialize object from request.body
val checkCriteria = foo.criteria
// do something else here
}
How can I use the checkCriteria value in the class WithCheck?

I found a solution.
Somehow, I was blind to see that isAuthorized has the same request as an implicit parameter. So, the check could be done entirely into the isAuthorized. For example,
case class WithCheck() extends Authorization[User, CookieAuthenticator] {
def isAuthorized[B](user: User, authenticator: CookieAuthenticator)(implicit request: Request[B], messages: Messages) = {
val foo = upickle.read[Foo](request.body.toString())
Future.successful(user.criteria == foo.criteria)
}
}

Related

Is it possible to access the request body as a JsValue in action composition functions in Play Framework 2.8?

In the Play documentation the Request type is generic [A] for action composition functions.
I am trying to add a custom query object to every endpoint that is responsible for querying data, to do that I need to grab the request body as JsValue and parse it into an appropriate case class. I cant seem to add a type to the WrappedRequest or the refine method in the action, and I cant do request.body.as[JsValue] in the refine method. Is there a way accomplish the following?
I would like to do something like this with action composition in endpoints that handle querying data:
def SomeEndpointWithAQuery() = auth.protectedAction(parse.json).andThen(QueryAction)) { request:QueryRequest[JsValue] =>
val query = request.queryObject
res = // Do query stuff
Ok(res)
}
QueryRequest is a WrappedRequest that provides a query object:
class QueryRequest[A](val query: QueryParser, request: AuthUserRequest[A]) extends WrappedRequest[A](request) {
def queryObject = query.parseQuery()
}
object QueryActionObject {
def QueryAction()(implicit ec: ExecutionContext): ActionRefiner[AuthUserRequest, QueryRequest] = new ActionRefiner[AuthUserRequest, QueryRequest] {
def executionContext: ExecutionContext = ec
def refine[A](input: AuthUserRequest[A]) = Future.successful {
val qp = new QueryParser(input.body.as[JsObject])
if (qp.validate()) {
Right(new QueryRequest(qp, input))
} else {
// bad request handling ...
}
}
}
}
auth.protectedAction is an actionBuilder that adds user info based on request.session info, it shouldnt affect how this queryAction works.

deadbolt2 and implicit request

I'm trying to integrate Deadbolt2 into my play framework 2.4 application.
A have following piece of code in my controller
import be.objectify.deadbolt.scala.{ActionBuilders, AuthenticatedRequest, DeadboltActions}
import be.objectify.deadbolt.scala.cache.HandlerCache
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{AnyContent, _}
import modules.user.security.{Authenticator, HandlerKeys, MyDeadboltHandler}
class Login #Inject() (deadbolt: DeadboltActions, handlers: HandlerCache, actionBuilder: ActionBuilders) extends Controller {
//...
def login = deadbolt.SubjectNotPresent() {
Action { implicit request =>
Ok(login(loginForm))
}
}
}
And I got error missing parameter type. I'm following deadbolt examples, which helps me a lot, but I can't figure out how to pass implicit request into action.
My template begins like this:
#(loginForm: Form[LoginForm])(implicit flash: Flash)
Using Action directly without deadbolt.SubjectNotPresent() works well.
One persistent question that keeps coming up is "how do I get the subject in an authorized action?". As of Deadbolt 2.5, the request passed into an action has been replaced with an AuthenticatedRequest which contains an Option[Subject]. As users of 2.4 also want this feature, it has been included in 2.4.4 as a breaking change.
The following examples use SubjectPresent as an example, but the same change applies to all authorization constraints.
When using action builders, in place of
def index = actionBuilder.SubjectPresentAction().defaultHandler() { implicit request
Ok(accessOk())
}
we now have
def index = actionBuilder.SubjectPresentAction().defaultHandler() { authRequest =>
Future {
Ok(accessOk())
}
}
When using action composition, in place of
def index = deadbolt.SubjectPresent() { implicit request
Action {
Ok(accessOk())
}
}
we now have
def someFunctionA = deadbolt.SubjectPresent()() { authRequest =>
Future {
Ok("Content accessible")
}
}
The getSubject() function of the DeadboltHandler trait now takes an AuthenticatedRequest instead of a Request.
override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] =
request.subject match {
case Some(user) => Future {request.subject}
case None => // get from database, identity platform, cache, whatever
}
What this means for your app is
def login = deadbolt.SubjectNotPresent() {
Action { implicit request =>
Ok(login(loginForm))
}
}
becomes
def login = deadbolt.SubjectNotPresent()() { authRequest =>
Future {
Ok(login(loginForm))
}
}

making an implicit available within a play action

My app hits many different dbs, which db depends on a query string parameter. I have a DatabaseConfigLocator that takes the string and returns the config and it works great. My problem is I want to make the config for each request available implicitly in my controller. I have tried two approaches.
class MyController extends Controller{
implicit def dbConfig(implicit request: RequestHeader): DatabaseConfig[JdbcProfile] = DatabaseConfigLocator.get[JdbcProfile](request.getQueryString("dbName")
}
This dosn't compile unless I change it to an implicit val with the same type but I need to recheck the query string every request not just once so I don't think an implicit val will work
The other approach was to create an action
object IODBAction extends ActionBuilder[Request]{
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
implicit def dbConfig(implicit request: RequestHeader): DatabaseConfig[JdbcProfile] = DatabaseConfigLocator.get[JdbcProfile]("blah")
block(request)
}
}
but that implicit is not available in the scope of the block and I cant find any way to pass it in as an implicit.
My goal is to be able to do something like this
class MyController extends Controller {
def create = {
Action.async {
request =>
ApiResponse {
for {
id <- aProvider.save(validRegistrationRequest.toVisitor)
} yield id
}
}
}
}
class aProvider {
def save(v: Visitor)(implicit dbConfig: DatabaseConfig[JdbcProfile]): ApiResponse[VisitorId]
}
or if the provider can get the implicit at instantiation time all the better
class aProvider(implicit dbConfig: DatabaseConfig[JdbcPRofile]) {
def save(v: Visitor): ApiResponse[VisitorId]
}
Any advice on how to approach this or if its possible with play framework?
Unfortunately, I fear you're stuck with an action receiving a single parameter, so you need to stick to the standard play "Action Composition" pattern. This is documented pretty extensively in the play docs.
I'd define yourself a a "Context" like this:
case class Context(dbConfig: DatabaseConfig[JDBCProfile], request: Request[A])
extends WrappedRequest(request)
Then create a custom action builder like this:
object DBIOAction extends ActionBuilder[Context]{
def invokeBlock[A](request: Request[A], block: (Context[A]) => Future[Result]) = {
val dbConfig = DatabaseConfigLocator.get[JdbcProfile]("blah")
val context = Context(dbConfig, request)
block(context)
}
}
You then should be able to use it like this:
def index = DBIOAction { implicit context =>
// do some stuff. return a result
}
In order to make things simple, I'd pass the implicit context into your service methods, perhaps extracting the dbConfig from the context and passing it the rest of the way down to your DAO's.
class FunService {
def getSomeData(param1: String)(implicit context: Context) = {
// do some work, perhaps using context.dbConfig
}

I18n in Play Framework 2.4.0

Here is my routes file:
GET /:lang controller.Application.index(lang: String)
GET /:lang/news controller.Application.news(lang: String)
Note that all of them start with /:lang.
Currently, I write Application.scala as
def index(lang: String) = Action {
implicit val messages: Messages = play.api.i18n.Messages.Implicits.applicationMessages(
Lang(lang), play.api.Play.current)
Ok(views.html.index("title"))
}
In this way, I have to write as many implicit Messages as Action. Is there any better solution for this?
Passing just Lang is simpler option:
def lang(lang: String) = Action {
Ok(views.html.index("play")(Lang(lang)))
}
//template
#(text: String)(implicit lang: play.api.i18n.Lang)
#Messages("hello")
You can reuse some code by using action composition, define wrapped request and action:
case class LocalizedRequest(val lang: Lang, request: Request[AnyContent]) extends WrappedRequest(request)
def LocalizedAction(lang: String)(f: LocalizedRequest => Result) = {
Action{ request =>
f(LocalizedRequest(Lang(lang), request))
}
}
Now you are able to reuse LocalizedAction like this:
//template
#(text: String)(implicit request: controllers.LocalizedRequest)
#Messages("hello")
//controller
def lang(lang: String) = LocalizedAction(lang){implicit request =>
Ok(views.html.index("play"))
}
Finally, I solved this problem in the following way.
As #Infinity suggests, I defined wrapped request and action as:
case class LocalizedRequest(messages: Messages,
request: Request[AnyContent])
extends WrappedRequest(request)
object Actions {
def LocalizedAction(lang: String)(f: LocalizedRequest => Result) = {
Action { request =>
f(LocalizedRequest(applicationMessages(Lang(lang), current), request))
}
}
object Implicits {
implicit def localizedRequest2Messages(implicit request: LocalizedRequest): Messages = request.messages
}
}
Now I'm able to use LocalizedAction like this:
def lang(lang: String) = LocalizedAction(lang) { implicit request =>
Ok(views.html.index("play"))
}
However, in order to omit the implicit parameter of Messages, which should be a play.api.i18n.Messages, I added a line to my template as:
#import controllers.Actions.Implicits._

Play Framework 2.2 action composition returning a custom object

I am trying to create a custom play.api.mvc.Action which can be used to populate a CustomerAccount based on the request and pass the CustomerAccount into the controller.
Following the documentation for Play 2.2.x I've created an Action and ActionBuilder but I cannot seem to return the CustomerAccount from within the action.
My current code is:
case class AccountWrappedRequest[A](account: CustomerAccount, request: Request[A]) extends WrappedRequest[A](request)
case class Account[A](action: Action[A]) extends Action[A] {
lazy val parser = action.parser
def apply(request: Request[A]): Future[SimpleResult] = {
AccountService.getBySubdomain(request.host).map { account =>
// Do something to return the account like return a new AccountWrappedRequest?
action(AccountWrappedRequest(account, request))
} getOrElse {
Future.successful(NotFound(views.html.account_not_found()))
}
}
}
object AccountAction extends ActionBuilder[AccountWrappedRequest] {
def invokeBlock[A](request: Request[A], block: (AccountWrappedRequest[A]) => Future[SimpleResult]) = {
// Or here to pass it to the next request?
block(request) // block(AccountWrappedRequest(account??, request))
}
override def composeAction[A](action: Action[A]) = Account(action)
}
Note: This will not compile because the block(request) function is expecting a type of AccountWrappedRequest which I cannot populate. It will compile when using a straight Request
Additionally...
Ultimately I want to be able to combine this Account action with an Authentication action so that the CustomerAccount can be passed into the Authentication action and user authentication can be provided based on that customer's account. I would then want to pass the customer account and user into the controller.
For example:
Account(Authenticated(Action))) { request => request.account; request.user ... } or better yet as individual objects not requiring a custom request object.
I'm not sure if this is the best way to do it but I have managed to come up with a solution that seems to work pretty well.
The key was to match on the request converting it into an AccountWrappedRequest inside invokeBlock before passing it on to the next request. If another Action in the chain is expecting a value from an earlier action in the chain you can then similarly match the request converting it into the type you need to access the request parameters.
Updating the example from the original question:
case class AccountWrappedRequest[A](account: CustomerAccount, request: Request[A]) extends WrappedRequest[A](request)
case class Account[A](action: Action[A]) extends Action[A] {
lazy val parser = action.parser
def apply(request: Request[A]): Future[SimpleResult] = {
AccountService.getBySubdomain(request.host).map { account =>
action(AccountWrappedRequest(account, request))
} getOrElse {
Future.successful(NotFound(views.html.account_not_found()))
}
}
}
object AccountAction extends ActionBuilder[AccountWrappedRequest] {
def invokeBlock[A](request: Request[A], block: (AccountWrappedRequest[A]) => Future[SimpleResult]) = {
request match {
case req: AccountRequest[A] => block(req)
case _ => Future.successful(BadRequest("400 Invalid Request"))
}
}
override def composeAction[A](action: Action[A]) = Account(action)
}
Then inside the apply() method of another Action (the Authenticated action in my case) you can similarly do:
def apply(request: Request[A]): Future[SimpleResult] = {
request match {
case req: AccountRequest[A] => {
// Do something that requires req.account
val user = User(1, "New User")
action(AuthenticatedWrappedRequest(req.account, user, request))
}
case _ => Future.successful(BadRequest("400 Invalid Request"))
}
}
And you can chain the actions together in the ActionBuilder
override def composeAction[A](action: Action[A]) = Account(Authenticated(action))
If AuthenticatedWrappedRequest is then passed into the controller you would have access to request.account, request.user and all the usual request parameters.
As you can see there are a couple of cases where the response is unknown which would generate a BadRequest. In reality these should never get called as far as I can tell but they are in there just incase.
I would love to have some feedback on this solution as I'm still fairly new to Scala and I'm not sure if there might be a better way to do it with the same result but I hope this is of use to someone too.
I wrote a standalone small (ish) example that does what you're looking for:
https://github.com/aellerton/play-login-example
I gave up trying to use the Security classes that exist in the play framework proper. I'm sure they're good, but I just couldn't understand them.
Brief guide...
In the example code, a controller is declared as using the AuthenticatedRequests trait:
object UserSpecificController extends Controller with AuthenticatedRequests {
...
}
Forcing any page to require authentication (or redirect to get it) is done with the RequireAuthentication action:
def authenticatedIndex = RequireAuthentication { implicit request: AuthenticatedRequest[AnyContent] =>
Ok("This content will be accessible only after logging in)
}
Signing out is done by using the AbandonAuthentication action:
def signOut = AbandonAuthentication { implicit request =>
Ok("You're logged out.").withNewSession
}
Note that for this to work, you must override methods from the AuthenticatedRequests trait, e.g.:
override def authenticationRequired[A](request: Request[A]): Future[SimpleResult] = {
Future.successful(
Redirect(routes.LoginController.showLoginForm).withSession("goto" -> request.path)
)
}
There's more to it; best to see the code.
HTH
Andrew