Commit 809fe891 authored by Mathieu's avatar Mathieu
Browse files

Starts with admin routes

parent 5af11df5
package org.openmoleconnect.adminclient
import java.nio.ByteBuffer
import org.scalajs.dom
import scaladget.bootstrapnative.bsn._
import org.scalajs.dom.raw.{Event, HTMLFormElement}
import scalatags.JsDom.all._
import scalatags.JsDom.tags
import scala.concurrent.Future
import scala.scalajs.js.annotation.JSExportTopLevel
import boopickle.Default._
import shared.AdminApi
import autowire._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js.typedarray.{ArrayBuffer, TypedArrayBuffer}
object AdminPanel {
@JSExportTopLevel("admin")
def admin() = {
println("admin ...")
Post[AdminApi].users().call().foreach {u=>
println("users " +u)
}
dom.document.body.appendChild(div("Admin").render)
}
}
object Post extends autowire.Client[ByteBuffer, Pickler, Pickler] {
override def doCall(req: Request): Future[ByteBuffer] = {
dom.ext.Ajax.post(
url = req.path.mkString("/"),
data = Pickle.intoBytes(req.args),
responseType = "arraybuffer",
headers = Map("Content-Type" -> "application/octet-stream")
).map(r => TypedArrayBuffer.wrap(r.response.asInstanceOf[ArrayBuffer]))
}
override def read[Result: Pickler](p: ByteBuffer) = Unpickle[Result].fromBytes(p)
override def write[Result: Pickler](r: Result) = Pickle.intoBytes(r)
}
//}
\ No newline at end of file
......@@ -43,6 +43,6 @@ object Application extends App {
server.start()
}
DB.addUser(DB.Email("moo@moo.com"), DB.Password("moo"))
DB.addUser(DB.Email("moo@moo.com"), DB.Password("moo"), DB.simpleUser)
}
......@@ -16,6 +16,8 @@ val skuberVersion = "2.2.0"
val httpComponentsVersion = "4.5.9"
val slickVersion = "3.3.1"
val h2Version = "1.4.200"
val autowireVersion = "0.2.6"
val boopickleVersion = "1.2.6"
val Resolvers = Seq(Resolver.sonatypeRepo("snapshots"),
"Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
......@@ -49,7 +51,9 @@ lazy val adminclient = project.in(file("adminclient")) enablePlugins (ExecNpmPlu
"com.lihaoyi" %%% "scalatags" % scalatagsVersion,
"fr.iscpif.scaladget" %%% "tools" % scaladgetVersion,
"fr.iscpif.scaladget" %%% "bootstrapnative" % scaladgetVersion,
"org.scala-js" %%% "scalajs-dom" % scalajsDomVersion
"org.scala-js" %%% "scalajs-dom" % scalajsDomVersion,
"com.lihaoyi" %%% "autowire" % autowireVersion,
"io.suzaku" %%% "boopickle" % boopickleVersion
)
) dependsOn (shared)
......@@ -67,7 +71,9 @@ lazy val server = project.in(file("server")) settings (defaultSettings) settings
"org.apache.httpcomponents" % "httpclient" % httpComponentsVersion,
"org.apache.httpcomponents" % "httpmime" % httpComponentsVersion,
"com.typesafe.slick" %% "slick" % slickVersion,
"com.h2database" % "h2" % h2Version
"com.h2database" % "h2" % h2Version,
"io.suzaku" %% "boopickle" % boopickleVersion,
"com.lihaoyi" %% "autowire" % autowireVersion
)
) dependsOn (shared) enablePlugins (ScalatraPlugin)
......
package org.openmoleconnect.server
object AdminApiImpl extends shared.AdminApi {
def users() = {
println("in users server")
val u = DBQueries.users
println("users " + u)
u
}
}
//object AdminRequest {
// private val requestPrefix = "shared/AdminApi"
//
// private val requests = Seq(
// s"$requestPrefix/users"
// )
//
// def isAdminRequest(path: String) = requests.contains(path)
//}
\ No newline at end of file
package org.openmoleconnect.server
import shared._
object ApiImpl extends Api {
def connect() = {
println("Connect")
}
}
\ No newline at end of file
package org.openmoleconnect.server
import java.net.URI
import java.nio.ByteBuffer
import org.openmoleconnect.server.JWT._
import org.scalatra._
......@@ -10,15 +11,21 @@ import scalatags.Text.all._
import scalatags.Text.{all => tags}
import scala.concurrent.duration._
import shared.Data._
import shared._
import monix.execution.Scheduler.Implicits.global
import org.apache.commons.io.IOUtils
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.client.utils.URIBuilder
import org.apache.http.entity.InputStreamEntity
import org.apache.http.impl.client.HttpClients
import shared.Data.UserData
import boopickle.Default._
import scala.reflect.ClassTag
import java.nio.ByteBuffer
import scala.concurrent.Await
import autowire._
class ConnectServlet(arguments: ConnectServer.ServletArguments) extends ScalatraServlet {
......@@ -51,6 +58,15 @@ class ConnectServlet(arguments: ConnectServer.ServletArguments) extends Scalatra
}
}
def withAdminRights(action: TokenData=> ActionResult): Serializable = {
withAccesToken { tokenData =>
DBQueries.isAdmin(tokenData.email) match {
case true=> action(tokenData)
case false=> Unauthorized("You seem unauthorized to do this !")
}
}
}
def withRefreshToken(action: TokenData => ActionResult): Serializable = {
Authentication.tokenData(request, TokenType.refreshToken) match {
case Some(tokenData: TokenData) => action(tokenData)
......@@ -109,19 +125,31 @@ class ConnectServlet(arguments: ConnectServer.ServletArguments) extends Scalatra
}
}
case class ListFilesData(list: Seq[TreeNodeData], nbFilesOnServer: Int)
case class DirData(isEmpty: Boolean)
post(s"/${Data.adminRoutePrefix}/*") {
withAdminRights { _ =>
val req = Await.result({
val is = request.getInputStream
val bytes: Array[Byte] = Iterator.continually(is.read()).takeWhile(_ != -1).map(_.asInstanceOf[Byte]).toArray[Byte]
val bb = ByteBuffer.wrap(bytes)
case class TreeNodeData(
name: String,
dirData: Option[DirData],
size: Long,
time: Long
)
AutowireServer.route[shared.AdminApi](AdminApiImpl)(
autowire.Core.Request(
Data.adminRoutePrefix.split("/").toSeq ++ multiParams("splat").head.split("/"),
Unpickle[Map[String, ByteBuffer]].fromBytes(bb)
)
)
},
Duration.Inf
)
val data = Array.ofDim[Byte](req.remaining)
req.get(data)
Ok(data)
}
}
post(connectionRoute) {
post(Data.connectionRoute) {
Authentication.isValid(request, TokenType.accessToken) match {
case false =>
val email = params.getOrElse("email", "")
......@@ -221,6 +249,7 @@ class ConnectServlet(arguments: ConnectServer.ServletArguments) extends Scalatra
}
def connectionHtml = someHtml("connect", "connection();")
def adminHtml = someHtml("admin", "admin();")
......@@ -262,4 +291,11 @@ class ConnectServlet(arguments: ConnectServer.ServletArguments) extends Scalatra
}
}
\ No newline at end of file
}
object AutowireServer extends autowire.Server[ByteBuffer, Pickler, Pickler] {
override def read[R: Pickler](p: ByteBuffer) = Unpickle[R].fromBytes(p)
override def write[R: Pickler](r: R) = Pickle.intoBytes(r)
}
......@@ -6,6 +6,7 @@ import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import slick.jdbc.H2Profile.api._
import shared._
object DB {
......@@ -23,6 +24,7 @@ object DB {
case class User(email: Email, password: Password, role: Role = simpleUser, uuid: UUID = UUID(""))
implicit def userToUserData(users: Seq[User]): Seq[Data.UserData] = users.map{u=> Data.UserData(u.email.value, u.password.value, u.role.value, u.uuid.value)}
class Users(tag: Tag) extends Table[(UUID, Email, Password, Role)](tag, "USERS") {
def uuid = column[UUID]("UUID", O.PrimaryKey)
......@@ -73,14 +75,18 @@ object DB {
def initDB = {
runTransaction(userTable.schema.createIfNotExists)
if (DB.users.isEmpty) {
DB.addUser(DB.Email("admin@admin.com"), DB.Password("admin"), DB.admin)
DB.addUser(DB.Email("admin@admin.com"), DB.Password("admin"), DB.admin, UUID("foo-123-567-foo"))
}
}
def addUser(email: Email, password: Password, role: Role = simpleUser) = {
def addUser(email: Email, password: Password, role: Role = simpleUser): Unit = {
addUser(email, password, role, UUID(util.UUID.randomUUID().toString))
}
def addUser(email: Email, password: Password, role: Role, uuid: UUID): Unit = {
if (!DBQueries.exists(email)) {
runTransaction(
userTable += (UUID(util.UUID.randomUUID().toString), email, password, role)
userTable += (uuid, email, password, role)
)
}
}
......
......@@ -7,6 +7,7 @@ import slick.jdbc.H2Profile.api._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import shared._
object DBQueries {
type UserQuery = Query[Users, (UUID, Email, Password, Role), Seq]
......@@ -20,7 +21,7 @@ object DBQueries {
def exists(email: Email) = get(email).isDefined
def isAdmin(email: Email) = get(email).map{_.role} == Some(DB.admin)
def isAdmin(email: Email) = get(email).map{_.role} == Some(admin)
def get(email: Email) = {
runQuery(
......@@ -30,4 +31,10 @@ object DBQueries {
).headOption
}
def users = runQuery(
for {
u <- userTable
} yield (u)
)
}
package shared
trait Api {
def connect()
}
\ No newline at end of file
package shared
import shared.Data.UserData
trait AdminApi {
def users(): Seq[UserData]
}
\ No newline at end of file
package shared
object Data {
val connectionRoute = "/connection"
val adminRoutePrefix = "shared/AdminApi"
case class UserData(email: String, password: String, role: String, uuid: String)
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment