Skip to content

Commit

Permalink
remove oauth dependency to user
Browse files Browse the repository at this point in the history
with Scoped[U: UserIdOf]
  • Loading branch information
ornicar committed Apr 5, 2024
1 parent 1e4a5de commit e2d633c
Show file tree
Hide file tree
Showing 23 changed files with 110 additions and 104 deletions.
4 changes: 2 additions & 2 deletions app/controllers/Account.scala
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,8 @@ final class Account(
for
_ <- env.security.api.dedup(me, req)
sessions <- env.security.api.locatedOpenSessions(me, 50)
clients <- env.oAuth.tokenApi.listClients(me, 50)
personalAccessTokens <- env.oAuth.tokenApi.countPersonal(me)
clients <- env.oAuth.tokenApi.listClients(50)
personalAccessTokens <- env.oAuth.tokenApi.countPersonal
currentSessionId = ~env.security.api.reqSessionId(req)
page <- renderPage:
html.account.security(me, sessions, currentSessionId, clients, personalAccessTokens)
Expand Down
24 changes: 13 additions & 11 deletions app/controllers/Challenge.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,18 @@ import lila.challenge.Challenge.Id as ChallengeId

import lila.core.{ Bearer, IpAddress, Preload }
import lila.game.{ AnonCookie, Pov }
import lila.oauth.{ EndpointScopes, OAuthScope }
import lila.oauth.{ EndpointScopes, OAuthScope, OAuthServer }
import lila.setup.ApiConfig
import lila.core.socket.SocketVersion
import lila.user.User as UserModel
import lila.user.{ Me, User as UserModel }

final class Challenge(
env: Env,
apiC: Api
) extends LilaController(env):

def api = env.challenge.api
def api = env.challenge.api
private given OAuthServer.FetchUser[Me] = env.user.repo.me

def all = Auth { ctx ?=> me ?=>
XhrOrRedirectHome:
Expand Down Expand Up @@ -214,8 +215,8 @@ final class Challenge(
Bearer.from(get("opponentToken")) match
case Some(bearer) =>
val required = OAuthScope.select(_.Challenge.Write).into(EndpointScopes)
env.oAuth.server.auth(bearer, required, ctx.req.some).map {
case Right(access) if pov.opponent.isUser(access.user) =>
env.oAuth.server.auth[Me](bearer, required, ctx.req.some).map {
case Right(access) if pov.opponent.isUser(access.me) =>
lila.common.Bus.publish(Tell(id.value, AbortForce), "roundSocket")
jsonOkResult
case Right(_) => BadRequest(jsonError("Not the opponent token"))
Expand All @@ -237,20 +238,21 @@ final class Challenge(
val accepted = OAuthScope.select(_.Challenge.Write).into(EndpointScopes)
(Bearer.from(get("token1")), Bearer.from(get("token2")))
.mapN:
env.oAuth.server.authBoth(accepted, req)
env.oAuth.server.authBoth[Me](accepted, req)
.so:
_.flatMap:
case Left(e) => handleScopedFail(accepted, e)
case Right((u1, u2)) =>
env.game.gameRepo
.game(id)
.flatMapz { g =>
env.round.proxyRepo.upgradeIfPresent(g).dmap(some).dmap(_.filter(_.hasUserIds(u1.id, u2.id)))
}
.orNotFound { game =>
.flatMapz: g =>
env.round.proxyRepo
.upgradeIfPresent(g)
.dmap(some)
.dmap(_.filter(_.hasUserIds(u1.userId, u2.userId)))
.orNotFound: game =>
env.round.tellRound(game.id, lila.core.round.StartClock)
jsonOkResult
}

private val ChallengeIpRateLimit = lila.memo.RateLimit[IpAddress](
500,
Expand Down
5 changes: 2 additions & 3 deletions app/controllers/DgtCtrl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ final class DgtCtrl(env: Env) extends LilaController(env):
description = "DGT board automatic token",
scopes = dgtScopes.value.map(_.key)
),
me,
isStudent = false
) >>
env.pref.api.saveTag(me, _.dgt, true)
Expand All @@ -47,5 +46,5 @@ final class DgtCtrl(env: Env) extends LilaController(env):
_.Board.Play
)

private def findToken(using me: Me) =
env.oAuth.tokenApi.findCompatiblePersonal(me, dgtScopes)
private def findToken(using Me) =
env.oAuth.tokenApi.findCompatiblePersonal(dgtScopes)
4 changes: 2 additions & 2 deletions app/controllers/Game.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ final class Game(env: Env, apiC: => Api) extends LilaController(env):
WithVs: vs =>
env.security.ipTrust
.throttle(MaxPerSecond:
if ctx.is(lila.user.User.explorerId) then env.apiExplorerGamesPerSecond.get()
if ctx.is(UserId.explorer) then env.apiExplorerGamesPerSecond.get()
else if ctx.is(user) then 60
else if ctx.isOAuth then 30 // bonus for oauth logged in only (not for CSRF)
else 25
Expand All @@ -91,7 +91,7 @@ final class Game(env: Env, apiC: => Api) extends LilaController(env):
ongoing = getBool("ongoing") || !finished,
finished = finished
)
if ctx.is(lila.user.User.explorerId) then
if ctx.is(UserId.explorer) then
Ok.chunked(env.api.gameApiV2.exportByUser(config))
.pipe(noProxyBuffer)
.as(gameContentType(config))
Expand Down
3 changes: 2 additions & 1 deletion app/controllers/LilaController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import lila.common.{ HTTPRequest, config }
import lila.i18n.LangPicker
import lila.oauth.{ EndpointScopes, OAuthScope, OAuthScopes, OAuthServer, TokenScopes }
import lila.security.Permission
import lila.user.Me

abstract private[controllers] class LilaController(val env: Env)
extends BaseController
Expand Down Expand Up @@ -227,7 +228,7 @@ abstract private[controllers] class LilaController(val env: Env)
f(using ctx)(using scoped.me)

private def handleScopedCommon(selectors: Seq[OAuthScope.Selector])(using req: RequestHeader)(
f: OAuthScope.Scoped => Fu[Result]
f: OAuthScope.Scoped[Me] => Fu[Result]
) =
val accepted = OAuthScope.select(selectors).into(EndpointScopes)
env.security.api.oauthScoped(req, accepted).flatMap {
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/OAuth.scala
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,12 @@ final class OAuth(env: Env, apiC: => Api) extends LilaController(env):

private val revokeClientForm = Form(single("origin" -> text))

def revokeClient = AuthBody { ctx ?=> me ?=>
def revokeClient = AuthBody { ctx ?=> _ ?=>
revokeClientForm
.bindFromRequest()
.fold(
_ => BadRequest,
origin => env.oAuth.tokenApi.revokeByClientOrigin(origin, me).inject(NoContent)
origin => env.oAuth.tokenApi.revokeByClientOrigin(origin).inject(NoContent)
)
}

Expand Down
8 changes: 4 additions & 4 deletions app/controllers/OAuthToken.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class OAuthToken(env: Env) extends LilaController(env):

def index = Auth { ctx ?=> me ?=>
Ok.pageAsync:
tokenApi.listPersonal(me).map(html.oAuth.token.index(_))
tokenApi.listPersonal.map(html.oAuth.token.index(_))
}

def create = Auth { ctx ?=> me ?=>
Expand All @@ -31,11 +31,11 @@ final class OAuthToken(env: Env) extends LilaController(env):
err => BadRequest.page(html.oAuth.token.create(err, me)),
setup =>
tokenApi
.create(setup, me, env.clas.studentCache.isStudent(me))
.create(setup, env.clas.studentCache.isStudent(me))
.inject(Redirect(routes.OAuthToken.index).flashSuccess)
)
}

def delete(id: String) = Auth { _ ?=> me ?=>
tokenApi.revokeById(AccessToken.Id(id), me).inject(Redirect(routes.OAuthToken.index).flashSuccess)
def delete(id: String) = Auth { _ ?=> _ ?=>
tokenApi.revokeById(AccessToken.Id(id)).inject(Redirect(routes.OAuthToken.index).flashSuccess)
}
2 changes: 1 addition & 1 deletion app/controllers/User.scala
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ final class User(
.inject(html.user.mod.assessments(user, as))
}

val boardTokens = env.oAuth.tokenApi.usedBoardApi(user).map(html.user.mod.boardTokens)
val boardTokens = env.oAuth.tokenApi.usedBoardApi.map(html.user.mod.boardTokens)

val teacher = env.clas.api.clas.countOf(user).map(html.user.mod.teacher(user))

Expand Down
4 changes: 2 additions & 2 deletions app/http/RequestContext.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ trait RequestContext(using Executor):
pref <- env.pref.api.get(userCtx.me, req)
yield BodyContext(req, lang, userCtx, pref)

def oauthContext(scoped: OAuthScope.Scoped)(using req: RequestHeader): Fu[Context] =
def oauthContext(scoped: OAuthScope.Scoped[Me])(using req: RequestHeader): Fu[Context] =
val lang = getAndSaveLang(req, scoped.me.some)
val userCtx = LoginContext(scoped.me.some, false, none, scoped.scopes.some)
env.pref.api
.get(scoped.me, req)
.map:
Context(req, lang, userCtx, _)

def oauthBodyContext[A](scoped: OAuthScope.Scoped)(using req: Request[A]): Fu[BodyContext[A]] =
def oauthBodyContext[A](scoped: OAuthScope.Scoped[Me])(using req: Request[A]): Fu[BodyContext[A]] =
val lang = getAndSaveLang(req, scoped.me.some)
val userCtx = LoginContext(scoped.me.some, false, none, scoped.scopes.some)
env.pref.api
Expand Down
4 changes: 2 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -315,12 +315,12 @@ lazy val irwin = module("irwin",
)

lazy val oauth = module("oauth",
Seq(user),
Seq(memo),
reactivemongo.bundle
)

lazy val security = module("security",
Seq(oauth, mailer),
Seq(oauth, user, mailer),
Seq(maxmind, hasher, uaparser) ++ tests.bundle ++ reactivemongo.bundle
)

Expand Down
22 changes: 13 additions & 9 deletions modules/challenge/src/main/ChallengeBulkSetup.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import lila.game.IdGenerator
import lila.core.game.GameRule
import lila.oauth.{ EndpointScopes, OAuthScope, OAuthServer }
import lila.core.perf.PerfType
import lila.user.User
import lila.user.{ User, Me }

final class ChallengeBulkSetup(setupForm: lila.core.setup.SetupForm):

Expand Down Expand Up @@ -80,10 +80,11 @@ final class ChallengeBulkSetup(setupForm: lila.core.setup.SetupForm):
)
)

final class ChallengeBulkSetupApi(oauthServer: OAuthServer, idGenerator: IdGenerator)(using
Executor,
akka.stream.Materializer
):
final class ChallengeBulkSetupApi(
oauthServer: OAuthServer,
idGenerator: IdGenerator,
userRepo: lila.user.UserRepo
)(using Executor, akka.stream.Materializer):

import ChallengeBulkSetup.*

Expand All @@ -96,18 +97,21 @@ final class ChallengeBulkSetupApi(oauthServer: OAuthServer, idGenerator: IdGener
)

def apply(data: BulkFormData, me: User): Fu[Result] =
given OAuthServer.FetchUser[Me] = userRepo.me
Source(extractTokenPairs(data.tokens))
.mapConcat: (whiteToken, blackToken) =>
List(whiteToken, blackToken) // flatten now, re-pair later!
.mapAsync(8): token =>
oauthServer.auth(token, OAuthScope.select(_.Challenge.Write).into(EndpointScopes), none).map {
_.left.map { BadToken(token, _) }
}
oauthServer
.auth[Me](token, OAuthScope.select(_.Challenge.Write).into(EndpointScopes), none)
.map {
_.left.map { BadToken(token, _) }
}
.runFold[Either[List[BadToken], List[UserId]]](Right(Nil)):
case (Left(bads), Left(bad)) => Left(bad :: bads)
case (Left(bads), _) => Left(bads)
case (Right(_), Left(bad)) => Left(bad :: Nil)
case (Right(users), Right(scoped)) => Right(scoped.me :: users)
case (Right(users), Right(scoped)) => Right(scoped.me.userId :: users)
.flatMap:
case Left(errors) => fuccess(Left(ScheduleError.BadTokens(errors.reverse)))
case Right(allPlayers) =>
Expand Down
1 change: 1 addition & 0 deletions modules/core/src/main/lilaism/LilaUserId.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ trait LilaUserId:
val lichess: UserId = "lichess"
val lichessAsMe: MyId = lichess.into(MyId)
val ghost: UserId = "ghost"
val explorer: UserId = "openingexplorer"

// specialized UserIds like Coach.Id
trait OpaqueUserId[A] extends OpaqueString[A]:
Expand Down
2 changes: 2 additions & 0 deletions modules/core/src/main/user.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ trait UserApi:
def isKid[U: UserIdOf](id: U): Fu[Boolean]
def isTroll(id: UserId): Fu[Boolean]
def isBot(id: UserId): Fu[Boolean]
def filterDisabled(userIds: Iterable[UserId]): Fu[Set[UserId]]
def isManaged(id: UserId): Fu[Boolean]

trait LightUserApiMinimal:
val async: LightUser.Getter
Expand Down
Loading

0 comments on commit e2d633c

Please sign in to comment.