Commit 228d650a authored by Tom Käsler's avatar Tom Käsler

add authentication directive

cleanup userservice
delete "getallusers" since it's not a good idea
parent d3dc738e
Pipeline #7998 passed with stages
in 3 minutes and 4 seconds
......@@ -14,9 +14,6 @@ trait UserApi {
val userApi = pathPrefix("") {
pathEndOrSingleSlash {
get {
complete (UserService.findAll)
} ~
post {
entity(as[User]) { user =>
complete (UserService.create(user).map(_.toJson))
......
package de.thm.arsnova.security
import de.thm.arsnova.models.User
import de.thm.arsnova.services.UserService
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes.Unauthorized
import akka.http.scaladsl.server.{Directive1, Directives}
import spray.json.{JsObject, JsString}
object Authentication extends Directives with SprayJsonSupport {
val authenticate: Directive1[User] = {
optionalHeaderValueByName("Authorization") flatMap {
case Some(authHeader) =>
val accessToken = authHeader.split(' ').last
onSuccess(UserService.getByLoginTokenString(accessToken)).flatMap {
case user: User => provide(user)
case _ => complete(Unauthorized, JsObject(Map("status" -> JsString("Wrong Authorization header"))))
}
case _ => complete(Unauthorized, JsObject(Map("status" -> JsString("Missing Authorization header"))))
}
}
}
package de.thm.arsnova.services
import de.thm.arsnova.models.{UserId, User}
import de.thm.arsnova.models.{User, UserId}
import slick.driver.MySQLDriver.api._
import scala.concurrent.Future
object UserService extends BaseService{
def findAll: Future[Seq[User]] = usersTable.result
def findById(userId: UserId): Future[User] = usersTable.filter(_.id === userId).result.head
def create(user: User): Future[UserId] = usersTable returning usersTable.map(_.id) += user
def update(newUser: User, userId: UserId): Future[Int] = usersTable.filter(_.id === userId)
.map(user => (user.username, user.password))
.update((newUser.userName, newUser.password))
object UserService extends BaseService {
def findById(userId: UserId): Future[User] = {
usersTable.filter(_.id === userId).result.head
}
def create(user: User): Future[UserId] = {
usersTable returning usersTable.map(_.id) += user
}
def update(newUser: User, userId: UserId): Future[Int] = {
usersTable.filter(_.id === userId)
.map(user => (user.username, user.password))
.update((newUser.userName, newUser.password))
}
def delete(userId: UserId): Future[Int] = {
usersTable.filter(_.id === userId).delete
}
def delete(userId: UserId): Future[Int] = usersTable.filter(_.id === userId).delete
def getByLoginTokenString(loginTokenString: String): Future[User] = {
val qry = for {
token <- loginTokensTable filter(_.token === loginTokenString)
user <- usersTable if (token.userId === user.id)
} yield (user)
db.run(qry.result.head)
}
}
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