Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add webhooks #1034

Draft
wants to merge 8 commits into
base: refactor/vue-user-frontend
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 78 additions & 61 deletions apiV2/app/controllers/apiv2/AbstractApiV2Controller.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,24 @@ import play.api.inject.ApplicationLifecycle
import play.api.mvc._

import controllers.apiv2.helpers.{APIScope, ApiError, ApiErrors}
import controllers.sugar.CircePlayController
import controllers.sugar.Requests.{ApiAuthInfo, ApiRequest}
import controllers.sugar.{CircePlayController, ResolvedAPIScope}
import controllers.sugar.Requests.ApiRequest
import controllers.{OreBaseController, OreControllerComponents}
import db.impl.query.APIV2Queries
import ore.db.impl.OrePostgresDriver.api._
import ore.db.impl.schema.{OrganizationTable, ProjectTable, UserTable}
import ore.models.api.ApiSession
import ore.models.project.Webhook
import ore.permission.Permission
import ore.permission.scope.{GlobalScope, OrganizationScope, ProjectScope, Scope}
import ore.WebhookJobAdder

import ackcord.data.OutgoingEmbed
import akka.http.scaladsl.model.ErrorInfo
import akka.http.scaladsl.model.headers.{Authorization, HttpCredentials}
import cats.data.NonEmptyList
import cats.syntax.all._
import io.circe.Encoder
import io.circe.syntax._
import zio.interop.catz._
import zio.{IO, Task, UIO, ZIO}

Expand Down Expand Up @@ -83,39 +87,37 @@ abstract class AbstractApiV2Controller(lifecycle: ApplicationLifecycle)(
} yield res
}

def apiAction(scope: APIScope): ActionRefiner[Request, ApiRequest] = new ActionRefiner[Request, ApiRequest] {
def executionContext: ExecutionContext = ec

override protected def refine[A](request: Request[A]): Future[Either[Result, ApiRequest[A]]] = {
def unAuth(msg: String) = Unauthorized(ApiError(msg)).withHeaders(WWW_AUTHENTICATE -> "OreApi")

val authRequest = for {
creds <- parseAuthHeader(request).mapError(_.toResult)
token <- ZIO
.fromOption(creds.params.get("session"))
.orElseFail(unAuth("No session specified"))
info <- service
.runDbCon(APIV2Queries.getApiAuthInfo(token).option)
.get
.orElseFail(unAuth("Invalid session"))
scopePerms <- {
val res: IO[Result, Permission] =
apiScopeToRealScope(scope).flatMap(info.permissionIn(_)).orElseFail(NotFound)
res
}
res <- {
if (info.expires.isBefore(OffsetDateTime.now())) {
service.deleteWhere(ApiSession)(_.token === token) *> IO.fail(unAuth("Api session expired"))
} else ZIO.succeed(ApiRequest(info, scopePerms, request))
}
} yield res

zioToFuture(authRequest.either)
def apiAction[S <: ResolvedAPIScope](scope: APIScope[S]): ActionRefiner[Request, ApiRequest[S, *]] =
new ActionRefiner[Request, ApiRequest[S, *]] {
def executionContext: ExecutionContext = ec

override protected def refine[A](request: Request[A]): Future[Either[Result, ApiRequest[S, A]]] = {
def unAuth(msg: String) = Unauthorized(ApiError(msg)).withHeaders(WWW_AUTHENTICATE -> "OreApi")

val authRequest = for {
creds <- parseAuthHeader(request).mapError(_.toResult)
token <- ZIO
.fromOption(creds.params.get("session"))
.orElseFail(unAuth("No session specified"))
info <- service
.runDbCon(APIV2Queries.getApiAuthInfo(token).option)
.get
.orElseFail(unAuth("Invalid session"))
resolvedScope <- apiScopeToResolvedScope(scope).orElseFail(NotFound)
scopePerms <- info.permissionIn(resolvedScope)
res <- {
if (info.expires.isBefore(OffsetDateTime.now())) {
service.deleteWhere(ApiSession)(_.token === token) *> IO.fail(unAuth("Api session expired"))
} else ZIO.succeed(ApiRequest(info, scopePerms, resolvedScope, request))
}
} yield res

zioToFuture(authRequest.either)
}
}
}

def apiScopeToRealScope(scope: APIScope): IO[Unit, Scope] = scope match {
case APIScope.GlobalScope => UIO.succeed(GlobalScope)
def apiScopeToResolvedScope[S <: ResolvedAPIScope](scope: APIScope[S]): IO[Unit, S] = scope match {
case APIScope.GlobalScope => UIO.succeed(ResolvedAPIScope.GlobalScope.asInstanceOf[S])
case APIScope.ProjectScope(projectOwner, projectSlug) =>
service
.runDBIO(
Expand All @@ -127,7 +129,7 @@ abstract class AbstractApiV2Controller(lifecycle: ApplicationLifecycle)(
)
.get
.orElseFail(())
.map(ProjectScope)
.map(ResolvedAPIScope.ProjectScope(projectOwner, projectSlug, _).asInstanceOf[S])
case APIScope.OrganizationScope(organizationName) =>
val q = for {
u <- TableQuery[UserTable]
Expand All @@ -139,14 +141,14 @@ abstract class AbstractApiV2Controller(lifecycle: ApplicationLifecycle)(
.runDBIO(q.result.headOption)
.get
.orElseFail(())
.map(OrganizationScope)
.map(ResolvedAPIScope.OrganizationScope(organizationName, _).asInstanceOf[S])
}

def createApiScope(
projectOwner: Option[String],
projectSlug: Option[String],
organizationName: Option[String]
): Either[Result, APIScope] = {
): Either[Result, APIScope[_ <: ResolvedAPIScope]] = {
val projectOwnerName = projectOwner.zip(projectSlug)

if ((projectOwner.isDefined || projectSlug.isDefined) && projectOwnerName.isEmpty) {
Expand All @@ -162,32 +164,23 @@ abstract class AbstractApiV2Controller(lifecycle: ApplicationLifecycle)(
}
}

def permissionsInApiScope(
projectOwner: Option[String],
projectSlug: Option[String],
organizationName: Option[String]
)(
implicit request: ApiRequest[_]
): IO[Result, (APIScope, Permission)] =
for {
apiScope <- ZIO.fromEither(createApiScope(projectOwner, projectSlug, organizationName))
scope <- apiScopeToRealScope(apiScope).orElseFail(NotFound)
perms <- request.permissionIn(scope)
} yield (apiScope, perms)

def permApiAction(perms: Permission): ActionFilter[ApiRequest] = new ActionFilter[ApiRequest] {
override protected def executionContext: ExecutionContext = ec
def permApiAction[S <: ResolvedAPIScope](perms: Permission): ActionFilter[ApiRequest[S, *]] =
new ActionFilter[ApiRequest[S, *]] {
override protected def executionContext: ExecutionContext = ec

override protected def filter[A](request: ApiRequest[A]): Future[Option[Result]] =
if (request.scopePermission.has(perms)) Future.successful(None)
else Future.successful(Some(Forbidden))
}
override protected def filter[A](request: ApiRequest[S, A]): Future[Option[Result]] =
if (request.scopePermission.has(perms)) Future.successful(None)
else Future.successful(Some(Forbidden))
}

def cachingAction: ActionFunction[ApiRequest, ApiRequest] =
new ActionFunction[ApiRequest, ApiRequest] {
def cachingAction[S <: ResolvedAPIScope]: ActionFunction[ApiRequest[S, *], ApiRequest[S, *]] =
new ActionFunction[ApiRequest[S, *], ApiRequest[S, *]] {
override protected def executionContext: ExecutionContext = ec

override def invokeBlock[A](request: ApiRequest[A], block: ApiRequest[A] => Future[Result]): Future[Result] = {
override def invokeBlock[A](
request: ApiRequest[S, A],
block: ApiRequest[S, A] => Future[Result]
): Future[Result] = {
import scalacache.modes.scalaFuture._
require(request.method == "GET")

Expand All @@ -204,9 +197,33 @@ abstract class AbstractApiV2Controller(lifecycle: ApplicationLifecycle)(
}
}

def ApiAction(perms: Permission, scope: APIScope): ActionBuilder[ApiRequest, AnyContent] =
def ApiAction[S <: ResolvedAPIScope](
perms: Permission,
scope: APIScope[S]
): ActionBuilder[ApiRequest[S, *], AnyContent] =
Action.andThen(apiAction(scope)).andThen(permApiAction(perms))

def CachingApiAction(perms: Permission, scope: APIScope): ActionBuilder[ApiRequest, AnyContent] =
def CachingApiAction[S <: ResolvedAPIScope](
perms: Permission,
scope: APIScope[S]
): ActionBuilder[ApiRequest[S, *], AnyContent] =
ApiAction(perms, scope).andThen(cachingAction)

def addWebhookJob[A: Encoder](
webhookEvent: Webhook.WebhookEventType,
data: A,
discordData: OutgoingEmbed
)(
implicit request: ApiRequest[ResolvedAPIScope.ProjectScope, _]
): UIO[Unit] = {
ackcord.requests.CreateMessage
WebhookJobAdder.add(
request.scope.id,
request.scope.projectOwner,
request.scope.projectSlug,
webhookEvent,
data.asJson.noSpaces,
discordData
)
}
}
23 changes: 12 additions & 11 deletions apiV2/app/controllers/apiv2/Organizations.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import ore.permission.Permission

import io.circe.syntax._
import zio.interop.catz._
import zio._

class Organizations(
val errorHandler: HttpErrorHandler,
Expand All @@ -33,20 +32,22 @@ class Organizations(

def showMembers(organization: String, limit: Option[Long], offset: Long): Action[AnyContent] =
CachingApiAction(Permission.ViewPublicInfo, APIScope.OrganizationScope(organization)).asyncF { implicit r =>
Members.membersAction(APIV2Queries.orgaMembers(organization, _, _), limit, offset)
Members.membersAction(APIV2Queries.orgaMembers(r.scope.id, _, _), limit, offset).map(Ok(_))
}

def updateMembers(organization: String): Action[List[Members.MemberUpdate]] =
ApiAction(Permission.ManageOrganizationMembers, APIScope.OrganizationScope(organization))
.asyncF(parseCirce.decodeJson[List[Members.MemberUpdate]]) { implicit r =>
Members.updateMembers[Organization, OrganizationUserRole, OrganizationRoleTable](
getSubject = organizations.withName(organization).someOrFail(NotFound),
allowOrgMembers = false,
getMembersQuery = APIV2Queries.orgaMembers(organization, _, _),
createRole = OrganizationUserRole(_, _, _),
roleCompanion = OrganizationUserRole,
notificationType = NotificationType.OrganizationInvite,
notificationLocalization = "notification.organization.invite"
)
for {
res <- Members.updateMembers[Organization, OrganizationUserRole, OrganizationRoleTable](
getSubject = r.organization,
allowOrgMembers = false,
getMembersQuery = APIV2Queries.orgaMembers(r.scope.id, _, _),
createRole = OrganizationUserRole(_, _, _),
roleCompanion = OrganizationUserRole,
notificationType = NotificationType.OrganizationInvite,
notificationLocalization = "notification.organization.invite"
)
} yield Ok(res)
}
}
Loading