Added API for listing of scans

Added API support
This commit is contained in:
Šesták Vít
2017-01-31 09:31:21 +01:00
parent cd37dda90c
commit e4b382024d
10 changed files with 144 additions and 6 deletions

View File

@@ -0,0 +1,16 @@
package controllers.api
import play.api.libs.Crypto
sealed abstract class ApiApplication {
def authenticate(appToken: String): Option[AuthenticatedApiApplication]
}
object ApiApplication{
final class Plain(token: String, authenticatedApiApplication: AuthenticatedApiApplication) extends ApiApplication{
override def authenticate(appToken: String): Option[AuthenticatedApiApplication] = {
if(Crypto.constantTimeEquals(appToken, token)) Some(authenticatedApiApplication)
else None
}
}
}

View File

@@ -0,0 +1,9 @@
package controllers.api
class ApiConfig(applications: Map[String, ApiApplication]){
def getApplication(appName: String, appToken: String): Option[AuthenticatedApiApplication] = for{
app <- applications.get(appName)
authenticatedApp <- app.authenticate(appToken)
} yield authenticatedApp
}

View File

@@ -0,0 +1,30 @@
package controllers.api
import controllers.AuthenticatedController
import play.api.mvc.{ActionBuilder, Request, Result}
import play.twirl.api.Txt
import scala.concurrent.Future
trait ApiController extends AuthenticatedController with ApiResources {
protected def apiConfig: ApiConfig
protected def ApiAction(resource: ApiResource) = new ActionBuilder[Request] {
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
val appNameOption = request.headers.get("x-app-name").orElse(request.getQueryString("app-name"))
val appTokenOption = request.headers.get("x-app-token").orElse(request.getQueryString("app-token"))
(appNameOption, appTokenOption) match {
case (Some(appName), Some(appToken)) =>
apiConfig.getApplication(appName, appToken) match {
case Some(app) =>
if(app.isAllowed(resource)) block(request)
else Future.successful(Unauthorized(Txt("The application is not allowed to access "+resource.name)))
case None => Future.successful(Unauthorized(Txt("Unknown application or bad token")))
}
case _ => Future.successful(Unauthorized(Txt("Missing auth headers x-app-name and x-app-token (or similar GET parameters).")))
}
}
}
}

View File

@@ -0,0 +1,4 @@
package controllers.api
final case class ApiResource private[api](name: String) extends AnyVal

View File

@@ -0,0 +1,11 @@
package controllers.api
trait ApiResources {
val ProjectTable = ApiResource("project-table")
}
object ApiResources extends ApiResources{
val All = Set(ProjectTable)
private val AllByName = All.map(res => res.name -> res).toMap
def byName(name: String): Option[ApiResource] = AllByName.get(name)
}

View File

@@ -0,0 +1,5 @@
package controllers.api
class AuthenticatedApiApplication(resources: Set[ApiResource]) {
def isAllowed(resource: ApiResource): Boolean = resources contains resource
}