Skip to content

Commit

Permalink
Fix playlist deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
malliina committed Oct 16, 2024
1 parent 808ddbe commit bc6c474
Show file tree
Hide file tree
Showing 12 changed files with 30 additions and 27 deletions.
10 changes: 8 additions & 2 deletions musicpimp/app/com/malliina/musicpimp/db/DoobiePlaylists.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ package com.malliina.musicpimp.db
import cats.effect.Async
import cats.implicits.{toFunctorOps, toTraverseOps}
import com.malliina.database.DoobieDatabase
import com.malliina.musicpimp.db.DoobiePlaylists.collect
import com.malliina.musicpimp.db.DoobiePlaylists.{collect, log}
import com.malliina.musicpimp.exception.UnauthorizedException
import com.malliina.musicpimp.library.{PlaylistService, PlaylistSubmission}
import com.malliina.musicpimp.models.{PlaylistID, SavedPlaylist}
import com.malliina.util.AppLogger
import com.malliina.values.Username
import doobie.free.connection.{pure, raiseError}
import doobie.implicits.toSqlInterpolator
import doobie.util.fragments

object DoobiePlaylists:
private val log = AppLogger(getClass)

def collect(rows: List[PlaylistInfo]): Seq[SavedPlaylist] =
rows.foldLeft(Vector.empty[SavedPlaylist]): (acc, row) =>
val idx = acc.indexWhere(_.id == row.id)
Expand Down Expand Up @@ -71,7 +74,10 @@ class DoobiePlaylists[F[_]: Async](db: DoobieDatabase[F])
else raiseError(UnauthorizedException(s"User $user is unauthorized"))

def delete(id: PlaylistID, user: Username): F[Unit] = db.run:
sql"""delete from PLAYLISTS where USER = $user and ID = $id""".update.run.map(_ => ())
sql"""delete from PLAYLISTS where USER = $user and ID = $id""".update.run.map: rowsDeleted =>
if rowsDeleted != 0 then
log.info(s"Deleted playlist $id by '$user'. $rowsDeleted affected rows.")
else log.info(s"Attempted to delete playlist $id by '$user', but no rows were affected.")

private def loadPlaylists(user: Username, id: Option[PlaylistID]): F[Seq[SavedPlaylist]] = db.run:
val idCondition = id.fold(fr"true")(pid => fr"P.ID = $pid")
Expand Down
9 changes: 4 additions & 5 deletions musicpimp/app/controllers/musicpimp/Playlists.scala
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ class Playlists(tags: PimpHtml, service: PlaylistService[IO], auth: AuthDeps) ex
submission => IO.pure(Redirect(routes.Playlists.playlists))
)

protected def recoveredAsync(f: CookiedRequest[AnyContent, Username] => IO[Result]) =
parsedRecoveredAsync(parsers.anyContent)(req => f(req))
private def recoveredAsync(f: CookiedRequest[Unit, Username] => IO[Result]) =
parsedRecoveredAsync(parsers.ignore(()))(req => f(req))

protected def parsedRecoveredAsync[T](
private def parsedRecoveredAsync[T](
parser: BodyParser[T]
)(f: CookiedRequest[T, Username] => IO[Result]) =
pimpParsedActionAsyncIO(parser)(auth => f(auth).recover(errorHandler))

override def errorHandler: PartialFunction[Throwable, Result] = {
override def errorHandler: PartialFunction[Throwable, Result] =
case ue: UnauthorizedException =>
log.error(s"Unauthorized", ue)
Errors.withStatus(Results.Unauthorized, "Access denied")
Expand All @@ -106,4 +106,3 @@ class Playlists(tags: PimpHtml, service: PlaylistService[IO], auth: AuthDeps) ex
case t: Throwable =>
log.error(s"Server error", t)
serverErrorGeneric
}
4 changes: 3 additions & 1 deletion musicpimp/app/controllers/musicpimp/SecureBase.scala
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ class SecureBase(auth: AuthDeps)
parser: BodyParser[T]
)(f: CookiedRequest[T, Username] => Future[Result]): EssentialAction =
authenticatedLogged: (auth: AuthedRequest) =>
log.info(s"authed $auth")
comps.actionBuilder.async(parser): req =>
log.info(s"$req with body ${req.body}")
val resultFuture = f(new CookiedRequest(auth.user, req, auth.cookie))
resultFuture.map(r => maybeWithCookie(auth, r))

Expand All @@ -143,5 +145,5 @@ class SecureBase(auth: AuthDeps)
*/
private def maybeWithCookie(auth: AuthedRequest, result: Result): Result =
auth.cookie.fold(result): c =>
log debug s"Sending updated cookie in response to user ${auth.user}..."
log.debug(s"Sending updated cookie in response to user ${auth.user}...")
result withCookies c withSession (Auth.DefaultSessionKey -> auth.user.name)
1 change: 0 additions & 1 deletion musicpimp/conf/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@
<logger name="play.core.server.netty.NettyModelConversion" level="ERROR"/>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<!-- <appender-ref ref="AKKA"/>-->
</root>
</configuration>
4 changes: 0 additions & 4 deletions musicpimp/test/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="AKKA" class="com.malliina.logback.PimpAppender">
<timeFormat>yyyy-MM-dd HH:mm:ss</timeFormat>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT"/>
<appender-ref ref="AKKA"/>
</root>
</configuration>
4 changes: 3 additions & 1 deletion pimpcloud/app/com/malliina/pimpcloud/CloudLoader.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.malliina.pimpcloud

import _root_.pimpcloud.Routes
import com.malliina.http.OkClient
import com.malliina.logback.PimpAppender
import org.apache.pekko.stream.Materializer
import com.malliina.musicpimp.messaging.cloud.{PushResult, PushTask}
import com.malliina.musicpimp.messaging.{ProdPusher, Pusher}
Expand Down Expand Up @@ -51,7 +52,8 @@ class CloudLoader extends ApplicationLoader:
override def load(context: Context): Application =
val environment = context.environment
LoggerConfigurator(environment.classLoader)
.foreach(_.configure(environment))
.foreach(_.configure(environment, context.initialConfiguration, Map.empty))
PimpAppender.install()
new CloudComponents(context, AppConf.forMode(environment.mode)).application

object NoPusher extends Pusher:
Expand Down
4 changes: 4 additions & 0 deletions pimpcloud/app/controllers/pimpcloud/auths.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import play.api.http.Writeable
import play.api.mvc.*
import play.api.mvc.Results.Ok
import cats.effect.unsafe.implicits.global
import com.malliina.util.AppLogger

class ProdAuth(ctrl: OAuthCtrl) extends PimpAuth:
override def logged(action: EssentialAction) =
Expand All @@ -38,13 +39,16 @@ class OAuthCtrl(val oauth: AdminOAuth, mat: Materializer)
extends BaseSecurity(oauth.actions, OAuthCtrl.bundle(oauth), mat)

object OAuthCtrl:
private val log = AppLogger(getClass)

def bundle(oauth: AdminOAuth) = new AuthBundle[AuthedRequest]:
override def authenticator: Authenticator[AuthedRequest] =
UserAuthenticator
.session(oauth.sessionKey)
.transform((req, user) => Right(AuthedRequest(user, req)))

override def onUnauthorized(failure: AuthFailure): Result =
log.info(s"Unauthorized $failure")
Results.Redirect(routes.AdminOAuth.googleStart)

class AdminOAuth(val actions: ActionBuilder[Request, AnyContent], creds: GoogleOAuthCredentials):
Expand Down
4 changes: 0 additions & 4 deletions pimpcloud/conf/logback.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
<configuration>
<conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel"/>
<appender name="AKKA" class="com.malliina.logback.PimpAppender">
<timeFormat>yyyy-MM-dd HH:mm:ss</timeFormat>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
Expand All @@ -22,7 +19,6 @@
<logger name="com" level="INFO"/>
<logger name="play.core.server.netty.NettyModelConversion" level="ERROR"/>
<root level="INFO">
<appender-ref ref="AKKA"/>
<appender-ref ref="STDOUT"/>
<!--<appender-ref ref="LOGSTREAMS"/>-->
</root>
Expand Down
4 changes: 0 additions & 4 deletions pimpcloud/test/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="AKKA" class="com.malliina.logback.PimpAppender">
<timeFormat>yyyy-MM-dd HH:mm:ss</timeFormat>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT"/>
<appender-ref ref="AKKA"/>
</root>
</configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ object PimpAuths:
override def onUnauthorized(failure: AuthFailure): Result =
val request = failure.rh
val remoteAddress = Proxies.realAddress(request)
log warn s"Unauthorized request '${request.uri}' from '$remoteAddress'."
log.warn(s"Unauthorized request '${request.uri}' from '$remoteAddress'.")
PimpContentController.pimpResult(request)(
html = Results.Redirect(redir).withSession(IntendedUri -> request.uri),
json = Errors.accessDenied
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ object AuthBundle:
val rh = failure.rh
val ip = Proxies.realAddress(rh)
val resource = rh.path
log warn s"Unauthorized request to '$resource' from '$ip'."
log.warn(s"Unauthorized request to '$resource' from '$ip'.")
Unauthorized

def oauthUser(initiateFlow: Call, sessionKey: String)(implicit
Expand All @@ -41,5 +41,6 @@ object AuthBundle:
.session(sessionKey)
.transform((r, u) => Right(map(r, u)))

override def onUnauthorized(failure: AuthFailure) =
override def onUnauthorized(failure: AuthFailure): Result =
log.info(s"Unauthorized oauth: '$failure'.")
Results.Redirect(initiateFlow)
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@ class BaseSecurity[A <: AuthInfo](
logAuth(user, rh)
f(user).apply(rh)

def logAuth(user: A, rh: RequestHeader): Unit =
log.info(s"User '${user.user}' from '${Proxies.realAddress(rh)}' requests '${rh.uri}'.")
private def logAuth(user: A, rh: RequestHeader): Unit =
log.info(
s"User '${user.user}' from '${Proxies.realAddress(rh)}' requests ${rh.method} '${rh.uri}'."
)

def logged(action: EssentialAction): EssentialAction =
BaseSecurity.logged(action)
Expand Down

0 comments on commit bc6c474

Please sign in to comment.