play.api.mvc.AbstractController Scala Examples
The following examples show how to use play.api.mvc.AbstractController.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: IzanamiController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.actor.ActorSystem import controllers.actions.SecuredAction import env.Env import izanami.scaladsl.Proxy import play.api.libs.json.Json import play.api.mvc.{AbstractController, ControllerComponents} class IzanamiController(env: Env, proxy: Proxy, SecuredAction: SecuredAction, val cc: ControllerComponents)( implicit system: ActorSystem ) extends AbstractController(cc) { import cats._ import cats.implicits._ import system.dispatcher def izanamiProxy() = SecuredAction.async { req => proxy .statusAndJsonResponse( Json.obj("userId" -> req.userId).some, req.userId.some ) .map { case (status, response) => Status(status)(response) } } def markDisplayed(experiment: String) = SecuredAction.async { req => proxy.markVariantDisplayed(experiment, req.userId).map { case (status, response) => Status(status)(response) } } def markWon(experiment: String) = SecuredAction.async { req => proxy.markVariantWon(experiment, req.userId).map { case (status, response) => Status(status)(response) } } }
Example 2
Source File: ResetPasswordController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.landing import javax.inject.{Inject, Singleton} import services.user.UserService import services.generated.tables.records.UserRecord import play.api.data.Form import play.api.data.Forms._ import play.api.i18n.I18nSupport import play.api.libs.mailer._ import play.api.mvc.{Action, AbstractController, ControllerComponents} import scala.concurrent.{ExecutionContext, Future} case class ResetPasswordData(email: String) @Singleton class ResetPasswordController @Inject() ( val components: ControllerComponents, val users: UserService, val mailerClient: MailerClient, implicit val ctx: ExecutionContext ) extends AbstractController(components) with I18nSupport { val resetPasswordForm = Form( mapping("email" -> email)(ResetPasswordData.apply)(ResetPasswordData.unapply) ) private def sendMail(user: UserRecord, newPassword: String) = Future { val name = Option(user.getRealName).getOrElse(user.getUsername) val message = s"""Dear $name, | |Your Recogito password was reset to | | $newPassword | |Please log in to Recogito with this password. You can change it |in your personal Account Settings. | |Cheers, |the Recogito Team""".stripMargin // TODO this now hard-wires "[email protected]" as reply address // TODO see if we can take this directly from the config file instead val email = Email( "Your Recogito password was reset", "Recogito Team <[email protected]>", Seq(users.decryptEmail(user.getEmail)), Some(message) ) mailerClient.send(email) } recover { case t: Throwable => t.printStackTrace } def showResetForm = Action { implicit request => Ok(views.html.landing.resetPassword(resetPasswordForm)) } def resetPassword = Action.async { implicit request => resetPasswordForm.bindFromRequest.fold( formWithErrors => Future.successful(BadRequest(views.html.landing.resetPassword(formWithErrors))), resetData => users.findByEmail(resetData.email).flatMap { case Some(user) => users.resetPassword(user.getUsername).map { password => sendMail(user, password) Ok(views.html.landing.resetPasswordOk()) } case None => Future.successful(Redirect(routes.ResetPasswordController.showResetForm()).flashing("error" -> "Can't find that e-mail, sorry.")) } ) } }
Example 3
Source File: LoginLogoutController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.landing import com.mohiva.play.silhouette.api.{LoginInfo, Silhouette} import controllers.{HasConfig, HasUserService, Security} import java.util.UUID import javax.inject.{Inject, Singleton} import services.announcement.AnnouncementService import services.user.UserService import play.api.Configuration import play.api.data.Form import play.api.data.Forms._ import play.api.i18n.I18nSupport import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.{ ExecutionContext, Future } case class LoginData(usernameOrPassword: String, password: String) @Singleton class LoginLogoutController @Inject() ( val announcements: AnnouncementService, val components: ControllerComponents, val config: Configuration, val silhouette: Silhouette[Security.Env], val users: UserService, implicit val ctx: ExecutionContext ) extends AbstractController(components) with HasConfig with HasUserService with I18nSupport { private val MESSAGE = "message" private val INVALID_LOGIN = "Invalid Username or Password" private val auth = silhouette.env.authenticatorService val loginForm = Form( mapping( "username" -> nonEmptyText, "password" -> nonEmptyText )(LoginData.apply)(LoginData.unapply) ) def showLoginForm(destination: Option[String]) = Action { implicit request => destination match { case None => Ok(views.html.landing.login(loginForm)) case Some(dest) => Ok(views.html.landing.login(loginForm)).withSession("access_uri" -> dest) } } def processLogin = silhouette.UserAwareAction.async { implicit request => loginForm.bindFromRequest.fold( formWithErrors => Future(BadRequest(views.html.landing.login(formWithErrors))), loginData => users.validateUser(loginData.usernameOrPassword, loginData.password).flatMap { case Some(validUser) => val destination = request.session.get("access_uri").getOrElse(routes.LandingController.index.toString) users.updateLastLogin(validUser.getUsername) val fAuthentication = auth.create(LoginInfo(Security.PROVIDER_ID, validUser.getUsername)) .flatMap(auth.init(_)) fAuthentication.flatMap { authentication => auth.embed(authentication, Redirect(destination).withSession(request.session - "access_uri")) } case None => Future(Redirect(routes.LoginLogoutController.showLoginForm()).flashing(MESSAGE -> INVALID_LOGIN)) } ) } def confirmServiceAnnouncement(id: UUID, response: String, destination: Option[String]) = silhouette.SecuredAction.async { implicit request => announcements.confirm(id, request.identity.username, response).map { success => if (success) destination.map(Redirect(_)).getOrElse(Redirect(routes.LandingController.index)) else InternalServerError } } def logout = silhouette.SecuredAction.async { implicit request => auth.discard(request.authenticator, Redirect(routes.LandingController.index)) } }
Example 4
Source File: LandingController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.landing import com.mohiva.play.silhouette.api.Silhouette import controllers.{ HasConfig, HasUserService, HasVisitLogging, HasPrettyPrintJSON, Security } import java.io.FileInputStream import javax.inject.{ Inject, Singleton } import java.net.URI import org.webjars.play.WebJarsUtil import play.api.Configuration import play.api.i18n.I18nSupport import play.api.libs.json.{Json, JsObject} import play.api.mvc.{Action, AbstractController, ControllerComponents} import scala.concurrent.ExecutionContext import services.annotation.AnnotationService import services.contribution.ContributionService import services.document.DocumentService import services.user.UserService import services.visit.VisitService @Singleton class LandingController @Inject() ( val components: ControllerComponents, val config: Configuration, val annotations: AnnotationService, val contributions: ContributionService, val documents: DocumentService, val users: UserService, val silhouette: Silhouette[Security.Env], implicit val ctx: ExecutionContext, implicit val visits: VisitService, implicit val webjars: WebJarsUtil ) extends AbstractController(components) with HasConfig with HasUserService with HasVisitLogging with HasPrettyPrintJSON with I18nSupport { def index = silhouette.UserAwareAction { implicit request => // Temporary hack only request.queryString.get("lang").flatMap(_.headOption) match { case Some(lang) => Redirect(routes.LandingController.index).withLang(play.api.i18n.Lang(lang)) case None => request.identity match { case Some(user) => Redirect(controllers.my.routes.WorkspaceController.workspace(user.username)) case None => logPageView() Ok(views.html.landing.index()) } } } def getStats() = silhouette.UnsecuredAction.async { implicit request => val fAnnotations = annotations.countTotal() val fEdits = contributions.countLast24hrs() val fUsers = users.countUsers() val f = for { annotations <- fAnnotations edits <- fEdits users <- fUsers } yield (annotations, edits, users) f.map { case (annotations, edits, users) => jsonOk(Json.obj( "annotations" -> annotations, "edits" -> edits, "users" -> users )) } } def sitemap() = Action.async { implicit request => documents.listOwnersWithPublicDocuments().map { users => val baseURL = routes.LandingController.index().absoluteURL() val sitemap = users.map(user => s"${baseURL}${user}").mkString("\n") Ok(sitemap).as("text/plain") } } def robots() = Action { implicit request => val sitemapURL = routes.LandingController.sitemap().absoluteURL() Ok(s"SITEMAP: ${sitemapURL}").as("text/plain") } def swaggerConfig() = Action { implicit request => val json = Json.parse(new FileInputStream("conf/swagger.json")) val baseURL = new URI(routes.LandingController.index.absoluteURL) val host = if (baseURL.getPort == -1) baseURL.getHost else s"${baseURL.getHost}:${baseURL.getPort}" jsonOk(json.as[JsObject] ++ Json.obj("host" -> host)) } }
Example 5
Source File: StatusController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.landing import javax.inject.{Inject, Singleton} import play.api.mvc.{AbstractController, Action, ControllerComponents} import scala.concurrent.ExecutionContext import services.user.UserService import services.contribution.ContributionService @Singleton class StatusController @Inject()( val components: ControllerComponents, val users: UserService, val edits: ContributionService, implicit val ctx: ExecutionContext ) extends AbstractController(components) { def index = Action.async { request => val fDBOnline = users.countUsers() .map { _ => true } .recover { case t: Throwable => false } val fIndexOnline = edits.countLast24hrs() .map { _ => true } .recover { case t: Throwable => false } val f = for { dbOnline <- fDBOnline idxOnline <- fIndexOnline } yield (dbOnline, idxOnline) f.map { case (dbOnline, idxOnline) => Ok(views.html.landing.status(dbOnline, idxOnline)) } } }
Example 6
Source File: SearchController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.my.directory.search import controllers.{Security, HasPrettyPrintJSON} import controllers.my.directory.ConfiguredPresentation import com.mohiva.play.silhouette.api.Silhouette import javax.inject.{Inject, Singleton} import org.joda.time.DateTime import play.api.libs.json._ import play.api.libs.functional.syntax._ import play.api.mvc.{AnyContent, Request, AbstractController, ControllerComponents} import scala.concurrent.{ExecutionContext, Future} import scala.util.Try import services.HasDate import services.document.DocumentService import services.document.search._ @Singleton class SearchController @Inject() ( components: ControllerComponents, silhouette: Silhouette[Security.Env], documentService: DocumentService, implicit val ctx: ExecutionContext ) extends AbstractController(components) with HasPrettyPrintJSON with HasDate { import ConfiguredPresentation._ implicit val searchOptionsReads: Reads[SearchArgs] = ( (JsPath \ "q").readNullable[String] and (JsPath \ "in").readNullable[String] .map(_.flatMap(Scope.withName).getOrElse(Scope.ALL)) and (JsPath \ "type").readNullable[String] .map(_.flatMap(DocumentType.withName)) and (JsPath \ "owner").readNullable[String] and (JsPath \ "max_age").readNullable[DateTime] )(SearchArgs.apply _) private def parseQueryString(params: Map[String, String]) = params.get("q").map { q => // Require at least a query phrase SearchArgs( Some(q), params.get("in").flatMap(Scope.withName).getOrElse(Scope.ALL), params.get("type").flatMap(DocumentType.withName), params.get("owner"), params.get("max_age").flatMap(parseDate) ) } def parseSearchArgs(request: Request[AnyContent]) = request.body.asJson match { case Some(json) => Try(Json.fromJson[SearchArgs](json).get).toOption case None => // Try query string instead val asMap = request.queryString .mapValues(_.headOption) .filter(_._2.isDefined) .mapValues(_.get) parseQueryString(asMap) } def search = silhouette.UserAwareAction.async { implicit request => parseSearchArgs(request) match { case Some(args) => documentService.search(request.identity.map(_.username), args).map { documents => val presentation = ConfiguredPresentation.forMyDocument(documents, None, None) jsonOk(Json.toJson(presentation)) } case None => Future.successful(BadRequest) } } }
Example 7
Source File: RestoreController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.my.settings import akka.actor.ActorSystem import com.mohiva.play.silhouette.api.Silhouette import controllers.{HasUserService, HasConfig, Security } import controllers.document.{BackupReader, HasBackupValidation} import java.io.File import javax.inject.Inject import services.annotation.AnnotationService import services.document.DocumentService import services.user.Roles._ import services.user.UserService import play.api.{Configuration, Logger} import play.api.i18n.{I18nSupport, MessagesApi} import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.{ExecutionContext, Future} import storage.db.DB import transform.tiling.TilingService class RestoreController @Inject() ( val components: ControllerComponents, val config: Configuration, val users: UserService, val silhouette: Silhouette[Security.Env], implicit val annotations: AnnotationService, implicit val db: DB, implicit val documents: DocumentService, implicit val tiling: TilingService, implicit val ctx: ExecutionContext, implicit val system: ActorSystem ) extends AbstractController(components) with HasUserService with HasConfig with I18nSupport with BackupReader { def index() = silhouette.SecuredAction { implicit request => Ok(views.html.my.settings.restore(request.identity)) } def restore() = silhouette.SecuredAction.async { implicit request => request.body.asMultipartFormData.map { tempfile => tempfile.file("backup") match { case Some(filepart) => // Forces the owner of the backup to the currently logged in user restoreBackup( filepart.ref.path.toFile, runAsAdmin = false, forcedOwner = Some(request.identity.username) ).map { _ => Redirect(routes.RestoreController.index).flashing("success" -> "The document was restored successfully.") }.recover { case e: HasBackupValidation.InvalidSignatureException => Redirect(routes.RestoreController.index).flashing("error" -> "The authenticity of your backup could not be verified.") case t: Throwable => t.printStackTrace() Redirect(routes.RestoreController.index).flashing("error" -> "There was an error restoring your document.") } case None => Logger.warn("Personal document restore POST without file attached") Future.successful(BadRequest) } }.getOrElse { Logger.warn("Personal document restore POST without form data") Future.successful(BadRequest) } } }
Example 8
Source File: AccountSettingsController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.my.settings import com.mohiva.play.silhouette.api.{Silhouette, LoginInfo} import controllers.{HasUserService, HasConfig, Security} import javax.inject.Inject import services.announcement.AnnouncementService import services.annotation.AnnotationService import services.contribution.ContributionService import services.user.Roles._ import services.user.UserService import services.upload.UploadService import services.document.DocumentService import org.webjars.play.WebJarsUtil import play.api.Configuration import play.api.data.Form import play.api.data.Forms._ import play.api.i18n.I18nSupport import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.{Await, ExecutionContext, Future} import scala.concurrent.duration._ import controllers.HasAccountRemoval case class AccountSettingsData( email : String, name : Option[String], bio : Option[String], website: Option[String]) class AccountSettingsController @Inject() ( val components: ControllerComponents, val config: Configuration, val silhouette: Silhouette[Security.Env], implicit val announcements: AnnouncementService, implicit val annotations: AnnotationService, implicit val contributions: ContributionService, implicit val ctx: ExecutionContext, implicit val documents: DocumentService, implicit val uploads: UploadService, implicit val users: UserService, implicit val webjars: WebJarsUtil ) extends AbstractController(components) with HasUserService with HasConfig with HasAccountRemoval with I18nSupport { val accountSettingsForm = Form( mapping( "email" -> email, "name" -> optional(text(maxLength=80)), "bio" -> optional(text(maxLength=256)), "website" -> optional(text(maxLength=256)) )(AccountSettingsData.apply)(AccountSettingsData.unapply) ) def index() = silhouette.SecuredAction { implicit request => val u = request.identity val form = accountSettingsForm.fill(AccountSettingsData( users.decryptEmail(u.email), u.realName, u.bio, u.website)) Ok(views.html.my.settings.account(form, u)) } def updateAccountSettings() = silhouette.SecuredAction.async { implicit request => accountSettingsForm.bindFromRequest.fold( formWithErrors => Future.successful(BadRequest(views.html.my.settings.account(formWithErrors, request.identity))), f => users.updateUserSettings(request.identity.username, f.email, f.name, f.bio, f.website) .map { success => if (success) Redirect(routes.AccountSettingsController.index).flashing("success" -> "Your settings have been saved.") else Redirect(routes.AccountSettingsController.index).flashing("error" -> "There was an error while saving your settings.") }.recover { case t:Throwable => { t.printStackTrace() Redirect(routes.AccountSettingsController.index).flashing("error" -> "There was an error while saving your settings.") }} ) } def deleteAccount() = silhouette.SecuredAction.async { implicit request => deleteUserAccount(request.identity.username).flatMap { _ => silhouette.env.authenticatorService.discard( request.authenticator, Redirect(controllers.landing.routes.LandingController.index)) } } }
Example 9
Source File: PasswordSettingsController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.my.settings import com.mohiva.play.silhouette.api.Silhouette import controllers.{ HasConfig, HasUserService, Security } import javax.inject.Inject import services.user.UserService import services.user.Roles._ import play.api.Configuration import play.api.data.Form import play.api.data.Forms._ import play.api.data.validation._ import play.api.i18n.{ I18nSupport, MessagesApi } import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.{ ExecutionContext, Future } case class PasswordSettingsData(currentPassword: String, newPassword: String, verifyPassword: String) class PasswordSettingsController @Inject() ( val components: ControllerComponents, val config: Configuration, val users: UserService, val silhouette: Silhouette[Security.Env], implicit val ctx: ExecutionContext ) extends AbstractController(components) with HasConfig with HasUserService with I18nSupport { private val matchingPasswords: Constraint[PasswordSettingsData] = Constraint("constraints.valid") { d => if (d.newPassword == d.verifyPassword) Valid else Invalid("Passwords must match") } val passwordSettingsForm = Form( mapping( "current" -> nonEmptyText, "new" -> nonEmptyText, "verify" -> nonEmptyText )(PasswordSettingsData.apply)(PasswordSettingsData.unapply).verifying(matchingPasswords) ) def index() = silhouette.SecuredAction { implicit request => Ok(views.html.my.settings.password(passwordSettingsForm, request.identity)) } def updatePassword() = silhouette.SecuredAction.async { implicit request => passwordSettingsForm.bindFromRequest.fold( formWithErrors => Future.successful(BadRequest(views.html.my.settings.password(formWithErrors, request.identity))), f => { users.updatePassword(request.identity.username, f.currentPassword, f.newPassword) .map { _ match { case Right(_) => Redirect(routes.PasswordSettingsController.index).flashing("success" -> "Your password has been updated.") case Left(errorMessage) => Redirect(routes.PasswordSettingsController.index).flashing("error" -> errorMessage) }}.recover { case t:Throwable => { t.printStackTrace() Redirect(routes.PasswordSettingsController.index).flashing("error" -> "There was an error while updating your password.") }} } ) } }
Example 10
Source File: HelpController.scala From recogito2 with Apache License 2.0 | 5 votes |
package controllers.help import controllers.HasVisitLogging import javax.inject.{Inject, Singleton} import services.visit.VisitService import org.webjars.play.WebJarsUtil import play.api.{Configuration, Environment} import play.api.mvc.{Action, AbstractController, ControllerComponents, RequestHeader} import play.twirl.api.HtmlFormat import scala.concurrent.ExecutionContext import scala.io.Source import scala.util.Try import services.entity.{AuthorityFileService, EntityType} @Singleton class HelpController @Inject() ( val authorities: AuthorityFileService, val components: ControllerComponents, val config: Configuration, val env: Environment, implicit val ctx: ExecutionContext, implicit val visits: VisitService, implicit val webjars: WebJarsUtil ) extends AbstractController(components) with HasVisitLogging { private val adminEmail = config.get[String]("admin.email") private val imprint = Try(Source.fromFile(env.getFile("conf/imprint"))).toOption.map { _.getLines.mkString("\n") } private def result(template: HtmlFormat.Appendable)(implicit request: RequestHeader) = { logPageView() Ok(template) } def localizedTutorial(lang: String) = Action { implicit request => lang.toUpperCase match { case "DE" => result(views.html.help.tutorial.tutorial_de()) case "ES" => result(views.html.help.tutorial.tutorial_es()) case "FA" => result(views.html.help.tutorial.tutorial_fa()) case "FR" => result(views.html.help.tutorial.tutorial_fr()) case "IT" => result(views.html.help.tutorial.tutorial_it()) case "NL" => result(views.html.help.tutorial.tutorial_nl()) case "TR" => result(views.html.help.tutorial.tutorial_tr()) case _ => NotFound(views.html.error404()) } } def faq = Action.async { implicit request => authorities.listAll(Some(EntityType.PLACE)).map { gazetteers => result(views.html.help.faq(gazetteers)) } } def index = Action { implicit request => result(views.html.help.index()) } def about = Action { implicit request => result(views.html.help.general.about(imprint, adminEmail)) } def privacy = Action { implicit request => result(views.html.help.general.privacy(adminEmail)) } def relations = Action { implicit request => result(views.html.help.relations()) } def cloning = Action { implicit request => result(views.html.help.cloning()) } def sharingLinks = Action { implicit request => result(views.html.help.sharing_links()) } def terms = Action { implicit request => result(views.html.help.general.terms()) } def tutorial = Action { implicit request => result(views.html.help.tutorial.tutorial()) } def workspace = Action { implicit request => result(views.html.help.workspace()) } def swaggerUi = Action { Redirect(url = "/webjars/swagger-ui/2.2.0/index.html", queryString = Map("url" -> Seq("/swagger.json"))) } }
Example 11
Source File: MeController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.actor.ActorSystem import akka.http.scaladsl.util.FastFuture import controllers.actions.SecuredAction import domains.me.MeService import env.Env import izanami.scaladsl.FeatureClient import play.api.libs.json.Json import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.Future class MeController(env: Env, meService: MeService[Future], featureClient: FeatureClient, SecuredAction: SecuredAction, cc: ControllerComponents)( implicit system: ActorSystem ) extends AbstractController(cc) { import cats._ import cats.implicits._ import system.dispatcher import domains.me.Me._ def me() = SecuredAction.async { implicit req => meService.get(req.userId).map { me => Ok(Json.toJson(me)) } } def addTvShow(id: String) = SecuredAction.async { implicit req => meService.addTvShow(req.userId, id).map { me => Ok(Json.toJson(me)) } } def removeTvShow(id: String) = SecuredAction.async { implicit req => meService.removeTvShow(req.userId, id).map { me => Ok(Json.toJson(me)) } } def markEpisode(showId: String, episodeId: String, watched: Boolean) = SecuredAction.async { implicit req => meService.markEpisode(req.userId, showId, episodeId, watched).map { me => Ok(Json.toJson(me)) } } def markSeason(showId: String, season: Int, watched: Boolean) = SecuredAction.async { implicit req => featureClient.featureOrElseAsync("mytvshows:season:markaswatched") { meService.markSeason(req.userId, showId, season, watched).map { me => Ok(Json.toJson(me)) } } { FastFuture.successful(BadRequest(Json.obj())) } } }
Example 12
Source File: HomeController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import env.{AppConfig, Env} import play.api.libs.json.{JsError, Json} import play.api.mvc.{AbstractController, ControllerComponents, Cookie, Cookies} case class LoginForm(email: String) object LoginForm { implicit val format = Json.format[LoginForm] } class HomeController(env: Env, config: AppConfig, val cc: ControllerComponents) extends AbstractController(cc) { def index() = Action { config.front match { case "react" => Ok(views.html.index(env)) case _ => Ok(views.html.indexangular(env)) } } def indexOtherRoutes(path: String) = index() def login() = Action(parse.json) { req => req.body .validate[LoginForm] .fold( e => BadRequest(JsError.toJson(e)), form => Ok(Json.obj()).withCookies(Cookie("clientId", form.email)) ) } }
Example 13
Source File: SearchController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.actor.ActorSystem import akka.stream.scaladsl.{GraphDSL, Interleave, Sink, Source} import akka.stream.{ActorMaterializer, SourceShape} import controllers.actions.SecuredAuthContext import domains.abtesting.ExperimentService import domains.config.ConfigService import domains.feature.FeatureService import domains.script.GlobalScriptService import domains.configuration.GlobalContext import play.api.libs.json.{JsArray, JsValue, Json} import play.api.mvc.{AbstractController, ActionBuilder, AnyContent, ControllerComponents} import store.Query import zio.{Runtime, ZIO} import libs.http.HttpContext class SearchController(AuthAction: ActionBuilder[SecuredAuthContext, AnyContent], cc: ControllerComponents)( implicit system: ActorSystem, R: HttpContext[GlobalContext] ) extends AbstractController(cc) { import libs.http._ def search(pattern: String, features: Boolean, configs: Boolean, experiments: Boolean, scripts: Boolean) = AuthAction.asyncTask[GlobalContext] { ctx => val query: Query = Query.oneOf(ctx.authorizedPatterns).and(pattern.split(",").toList) for { featuresRes <- if (features) FeatureService .findByQuery(query, 1, 10) .map(_.results.map(value => Json.obj("type" -> "features", "id" -> Json.toJson(value.id)))) .map(value => Source(value.toList)) else ZIO.succeed(Source.empty[JsValue]) configsRes <- if (configs) ConfigService .findByQuery(query, 1, 10) .map( _.results.map(value => Json.obj("type" -> "configurations", "id" -> Json.toJson(value.id))) ) .map(value => Source(value.toList)) else ZIO.succeed(Source.empty[JsValue]) experimentsRes <- if (experiments) ExperimentService .findByQuery(query, 1, 10) .map( _.results.map(value => Json.obj("type" -> "experiments", "id" -> Json.toJson(value.id))) ) .map(value => Source(value.toList)) else ZIO.succeed(Source.empty[JsValue]) scriptsRes <- if (scripts) GlobalScriptService .findByQuery(query, 1, 10) .map(_.results.map(value => Json.obj("type" -> "scripts", "id" -> Json.toJson(value.id)))) .map(value => Source(value.toList)) else ZIO.succeed(Source.empty[JsValue]) res <- ZIO.fromFuture { implicit ec => val all = Source.fromGraph(GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ val interleave = builder.add(Interleave[JsValue](4, 1)) featuresRes ~> interleave.in(0) configsRes ~> interleave.in(1) experimentsRes ~> interleave.in(2) scriptsRes ~> interleave.in(3) SourceShape(interleave.out) }) all.take(10).runWith(Sink.seq) map { jsons => Ok(JsArray(jsons)) } } } yield res } }
Example 14
Source File: EventsController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.actor.ActorSystem import controllers.actions.SecuredAuthContext import domains.Domain.Domain import domains.events.{EventStore, EventStoreContext} import play.api.libs.EventSource import play.api.libs.EventSource.{EventDataExtractor, EventIdExtractor, EventNameExtractor} import play.api.libs.json.{JsString, Json} import play.api.mvc.{AbstractController, ActionBuilder, AnyContent, ControllerComponents} import libs.http.HttpContext import akka.stream.scaladsl.Flow import scala.util.Success import scala.util.Failure import libs.logs.IzanamiLogger import java.time.LocalDateTime import play.api.libs.json.JsValue import scala.concurrent.duration.DurationDouble import domains.auth.AuthInfo import domains.Key class EventsController(system: ActorSystem, AuthAction: ActionBuilder[SecuredAuthContext, AnyContent], cc: ControllerComponents)(implicit r: HttpContext[EventStoreContext]) extends AbstractController(cc) { import libs.http._ import domains.events.Events._ import system.dispatcher private implicit val nameExtractor = EventNameExtractor[IzanamiEvent](_ => None) //Some(event.`type`)) private implicit val idExtractor = EventIdExtractor[IzanamiEvent](event => Some(s"${event._id}")) //Some(event.key.key)) private implicit val dataExtractor = EventDataExtractor[IzanamiEvent](event => Json.stringify(event.toJson)) def allEvents(patterns: String, domains: String) = events(domains.split(",").toIndexedSeq, patterns) def eventsForADomain(domain: String, patterns: String) = events(domain.split(",").toIndexedSeq, patterns) val logEvent = Flow[IzanamiEvent].map { event => event } case class KeepAliveEvent() extends IzanamiEvent { val _id: Long = 0 val domain: Domain = domains.Domain.Unknown val authInfo: Option[AuthInfo.Service] = None val key: Key = Key("na") def timestamp: LocalDateTime = LocalDateTime.now() val `type`: String = "KEEP_ALIVE" val payload: JsValue = Json.obj() } val keepAlive = Flow[IzanamiEvent].keepAlive(30.seconds, () => KeepAliveEvent()) // TODO abilitations private def events[T <: IzanamiEvent](domains: Seq[String], patterns: String) = AuthAction.asyncTask[EventStoreContext] { ctx => val allPatterns: Seq[String] = ctx.authorizedPatterns ++ patterns .split(",") .toList val lastEventId = ctx.request.headers.get("Last-Event-ID").map(_.toLong) val allDomains = domains.map(JsString).flatMap(_.validate[Domain].asOpt) EventStore .events(allDomains, allPatterns, lastEventId) .map { source => val eventSource = (source via keepAlive via logEvent via EventSource.flow).watchTermination() { (_, fDone) => fDone.onComplete { case Success(_) => IzanamiLogger.debug("SSE disconnected") case Failure(e) => IzanamiLogger.error("Error during SSE ", e) } fDone } Ok.chunked(eventSource).as("text/event-stream") } } }
Example 15
Source File: OAuthController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import akka.util.ByteString import com.auth0.jwt.algorithms.Algorithm import controllers.dto.error.ApiErrors import domains.auth.{OAuthModule, OAuthServiceModule, Oauth2Service} import domains.user.User import env.{Env, Oauth2Config} import play.api.libs.json.Json import play.api.mvc.{AbstractController, ControllerComponents, Cookie} import zio.{Runtime, ZIO} import libs.http.HttpContext class OAuthController(_env: Env, mayBeOauth2Config: Option[Oauth2Config], cc: ControllerComponents)( implicit R: HttpContext[OAuthServiceModule] ) extends AbstractController(cc) { import libs.http._ lazy val _config = _env.izanamiConfig.filter match { case env.Default(config) => config case _ => throw new RuntimeException("Wrong config") } lazy val algorithm: Algorithm = Algorithm.HMAC512(_config.sharedKey) def appLoginPage() = Action { implicit request => mayBeOauth2Config match { case Some(openIdConnectConfig) => val clientId = openIdConnectConfig.clientId val responseType = "code" val scope = openIdConnectConfig.scope.map(s => s"scope=${s}&").getOrElse("") val claims = Option(openIdConnectConfig.claims).filterNot(_.isEmpty).map(v => s"claims=$v&").getOrElse("") val queryParam = if (openIdConnectConfig.useCookie) "" else s"?desc=izanami" val redirectUri = if (_env.baseURL.startsWith("http")) { s"${_env.baseURL}/${controllers.routes.OAuthController.appCallback().url}${queryParam}" } else { s"${controllers.routes.OAuthController.appCallback().absoluteURL()}${queryParam}" } val loginUrl = s"${openIdConnectConfig.loginUrl}?${scope}&${claims}client_id=$clientId&response_type=$responseType&redirect_uri=$redirectUri" Redirect(loginUrl) case None => BadRequest(Json.toJson(ApiErrors.error("Open Id Connect module not configured"))) } } def appLogout() = Action { req => val redirectToOpt: Option[String] = req.queryString.get("redirectTo").map(_.last) redirectToOpt match { case Some(redirectTo) => Redirect(redirectTo).discardingCookies() case _ => BadRequest(Json.toJson(ApiErrors.error("Missing parameters"))) } } def appCallback() = Action.asyncZio[OAuthServiceModule] { implicit ctx => mayBeOauth2Config match { case Some(openIdConnectConfig) => Oauth2Service .paCallback(_env.baseURL, openIdConnectConfig) .map { user => Redirect(controllers.routes.HomeController.index()) .withCookies(Cookie(name = _env.cookieName, value = User.buildToken(user, _config.issuer, algorithm))) } .mapError { err => BadRequest(Json.toJson(ApiErrors.fromErrors(err.toList))) } case None => ZIO.succeed(BadRequest(Json.toJson(ApiErrors.error("Open Id Connect module not configured")))) } } }
Example 16
Source File: BackOfficeController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import ch.qos.logback.classic.{Level, LoggerContext} import controllers.actions.SecuredAuthContext import domains.user.User import org.slf4j.LoggerFactory import play.api.libs.json.{JsArray, Json} import play.api.mvc.{AbstractController, ActionBuilder, AnyContent, ControllerComponents} class BackOfficeController(AuthAction: ActionBuilder[SecuredAuthContext, AnyContent], cc: ControllerComponents) extends AbstractController(cc) { def changeLogLevel(name: String, newLevel: Option[String]) = AuthAction { ctx => if (isAdmin(ctx)) { val loggerContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext] val _logger = loggerContext.getLogger(name) val oldLevel = Option(_logger.getLevel).map(_.levelStr).getOrElse(Level.OFF.levelStr) _logger.setLevel(newLevel.map(v => Level.valueOf(v)).getOrElse(Level.ERROR)) Ok(Json.obj("name" -> name, "oldLevel" -> oldLevel, "newLevel" -> _logger.getLevel.levelStr)) } else { Unauthorized } } def getLogLevel(name: String) = AuthAction { ctx => if (isAdmin(ctx)) { val loggerContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext] val _logger = loggerContext.getLogger(name) Ok(Json.obj("name" -> name, "level" -> _logger.getLevel.levelStr)) } else { Unauthorized } } def getAllLoggers() = AuthAction { ctx => if (isAdmin(ctx)) { import scala.jdk.CollectionConverters._ val loggerContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext] val rawLoggers = loggerContext.getLoggerList.asScala.toIndexedSeq val loggers = JsArray(rawLoggers.map(logger => { val level: String = Option(logger.getLevel).map(_.levelStr).getOrElse("OFF") Json.obj("name" -> logger.getName, "level" -> level) })) Ok(loggers) } else { Unauthorized } } private def isAdmin(ctx: SecuredAuthContext[AnyContent]) = ctx.auth.exists { case u: User => u.admin case _ => false } }
Example 17
Source File: HealthCheckController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import controllers.actions.AuthContext import controllers.dto.error.ApiErrors import domains.configuration.GlobalContext import play.api.libs.json.Json import play.api.mvc.{AbstractController, ActionBuilder, AnyContent, ControllerComponents} import store.Healthcheck import libs.http.HttpContext class HealthCheckController( AuthAction: ActionBuilder[AuthContext, AnyContent], cc: ControllerComponents )(implicit R: HttpContext[GlobalContext]) extends AbstractController(cc) { import libs.http._ def check() = AuthAction.asyncZio[GlobalContext] { _ => Healthcheck .check() .map(_ => Ok(Json.obj())) .mapError { ApiErrors.toHttpResult } } }
Example 18
Source File: UserController.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package controllers import java.util.UUID import com.mohiva.play.silhouette.api.Silhouette import javax.inject.Inject import models.services.AuthenticateService import play.api.libs.json.Json import play.api.mvc.{AbstractController, ControllerComponents} import utils.auth.DefaultEnv import scala.concurrent.{ExecutionContext, Future} class UserController @Inject()(silhouette: Silhouette[DefaultEnv], authenticateService: AuthenticateService, components: ControllerComponents)(implicit ec: ExecutionContext) extends AbstractController(components) { def fetchLinkedAccounts(userId: UUID) = silhouette.SecuredAction.async { implicit req => if (userId == req.identity.userID) { authenticateService.getAuthenticationProviders(req.identity.email.get).map(providers => Ok(Json.toJson(providers))) } else { Future.successful(Forbidden) } } }
Example 19
Source File: ProfilesController.scala From crm-seed with Apache License 2.0 | 5 votes |
package com.dataengi.crm.profiles.controllers import com.dataengi.crm.identities.actions.SecuredFilteredAction import cats.instances.all._ import com.google.inject.{Inject, Singleton} import com.mohiva.play.silhouette.api.Silhouette import com.dataengi.crm.common.context.types._ import com.dataengi.crm.common.controllers.ApplicationController import play.api.mvc.{AbstractController, ControllerComponents} import com.dataengi.crm.profiles.formatters.ProfilesFormatter._ import com.dataengi.crm.profiles.services.ProfilesService import com.dataengi.crm.identities.utils.auth.DefaultEnv import scala.concurrent.ExecutionContext @Singleton class ProfilesController @Inject()(profilesService: ProfilesService, val silhouette: Silhouette[DefaultEnv], components: ControllerComponents, implicit val executionContext: ExecutionContext) extends ApplicationController(components) with SecuredFilteredAction { def update = SecuredAccessAction.async(parse.json(updateProfileFormatter)) { implicit request => profilesService.update(request.body, request.identity) } def get = SecuredAccessAction.async { implicit request => profilesService.get(request.identity) } def getProfilesByUsers = SecuredAccessAction.async(parse.json(getUsersProfilesDataFormatter)) { implicit request => profilesService.get(request.body) } def checkNickname(nickname: String) = SecuredAccessAction.async { implicit request => profilesService.existProfileWithNickname(nickname) } }
Example 20
Source File: ThingsController.scala From swagger-check with MIT License | 5 votes |
package controllers import java.util.UUID import javax.inject.Inject import dal.ThingsRepository import models.{Link, ThingType, ThingsPage, ThingsPageLinks} import play.api.libs.json.Json import play.api.mvc.{AbstractController, ControllerComponents} import scala.concurrent.ExecutionContext class ThingsController @Inject()( thingRepository: ThingsRepository, components: ControllerComponents)(implicit ec: ExecutionContext) extends AbstractController(components) { def getPage(thingType: Option[ThingType.Type], offset: Int, limit: Int) = Action.async { implicit request => thingRepository.getPage(thingType, offset, limit).map { things => val page = ThingsPage( things, ThingsPageLinks( Link.fromCall( routes.ThingsController.getPage(thingType, offset, limit)), None, None)) Ok(Json.toJson(page)) } } def createThing = Action { Created } def getThing(id: UUID) = Action.async { implicit request => thingRepository.getById(id).map { case Some(thing) => Ok(Json.toJson(thing)) case None => NotFound } } }
Example 21
Source File: StatusCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import scala.concurrent.ExecutionContext import play.api.Configuration import play.api.http.Status import play.api.libs.json.Json.toJsFieldJsValueWrapper import play.api.libs.json.{JsBoolean, JsString, Json} import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import com.sksamuel.elastic4s.http.ElasticDsl import javax.inject.{Inject, Singleton} import org.elasticsearch.client.Node import org.thp.cortex.models.Worker import org.elastic4play.database.DBIndex import org.elastic4play.services.AuthSrv import org.elastic4play.services.auth.MultiAuthSrv @Singleton class StatusCtrl @Inject()( configuration: Configuration, authSrv: AuthSrv, dbIndex: DBIndex, components: ControllerComponents, implicit val ec: ExecutionContext ) extends AbstractController(components) with Status { private[controllers] def getVersion(c: Class[_]) = Option(c.getPackage.getImplementationVersion).getOrElse("SNAPSHOT") def get: Action[AnyContent] = Action { Ok( Json.obj( "versions" → Json.obj( "Cortex" → getVersion(classOf[Worker]), "Elastic4Play" → getVersion(classOf[AuthSrv]), "Play" → getVersion(classOf[AbstractController]), "Elastic4s" → getVersion(classOf[ElasticDsl]), "ElasticSearch client" → getVersion(classOf[Node]) ), "config" → Json.obj( "protectDownloadsWith" → configuration.get[String]("datastore.attachment.password"), "authType" → (authSrv match { case multiAuthSrv: MultiAuthSrv ⇒ multiAuthSrv.authProviders.map { a ⇒ JsString(a.name) } case _ ⇒ JsString(authSrv.name) }), "capabilities" → authSrv.capabilities.map(c ⇒ JsString(c.toString)), "ssoAutoLogin" → JsBoolean(configuration.getOptional[Boolean]("auth.sso.autologin").getOrElse(false)) ) ) ) } def health: Action[AnyContent] = TODO }
Example 22
Source File: AnalyzerConfigCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import javax.inject.{Inject, Singleton} import scala.concurrent.{ExecutionContext, Future} import play.api.libs.json.JsObject import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import org.thp.cortex.models.{BaseConfig, Roles} import org.thp.cortex.services.{AnalyzerConfigSrv, UserSrv} import org.elastic4play.BadRequestError import org.elastic4play.controllers.{Authenticated, Fields, FieldsBodyParser, Renderer} @Singleton class AnalyzerConfigCtrl @Inject()( analyzerConfigSrv: AnalyzerConfigSrv, userSrv: UserSrv, authenticated: Authenticated, fieldsBodyParser: FieldsBodyParser, renderer: Renderer, components: ControllerComponents, implicit val ec: ExecutionContext ) extends AbstractController(components) { def get(analyzerConfigName: String): Action[AnyContent] = authenticated(Roles.orgAdmin).async { request ⇒ analyzerConfigSrv .getForUser(request.userId, analyzerConfigName) .map(renderer.toOutput(OK, _)) } def list(): Action[AnyContent] = authenticated(Roles.orgAdmin).async { request ⇒ analyzerConfigSrv .listConfigForUser(request.userId) .map { bc ⇒ renderer.toOutput( OK, bc.sortWith { case (BaseConfig("global", _, _, _), _) ⇒ true case (_, BaseConfig("global", _, _, _)) ⇒ false case (BaseConfig(a, _, _, _), BaseConfig(b, _, _, _)) ⇒ a.compareTo(b) < 0 } ) } } def update(analyzerConfigName: String): Action[Fields] = authenticated(Roles.orgAdmin).async(fieldsBodyParser) { implicit request ⇒ request.body.getValue("config").flatMap(_.asOpt[JsObject]) match { case Some(config) ⇒ analyzerConfigSrv .updateOrCreate(request.userId, analyzerConfigName, config) .map(renderer.toOutput(OK, _)) case None ⇒ Future.failed(BadRequestError("attribute config has invalid format")) } } }
Example 23
Source File: AnalyzerCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import scala.concurrent.{ExecutionContext, Future} import play.api.libs.json.{JsObject, JsString, Json} import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import akka.stream.Materializer import javax.inject.{Inject, Singleton} import org.thp.cortex.models.{Roles, Worker} import org.thp.cortex.services.{UserSrv, WorkerSrv} import org.elastic4play.controllers.{Authenticated, Fields, FieldsBodyParser, Renderer} import org.elastic4play.services.JsonFormat.queryReads import org.elastic4play.services.{QueryDSL, QueryDef} @Singleton class AnalyzerCtrl @Inject()( workerSrv: WorkerSrv, userSrv: UserSrv, authenticated: Authenticated, fieldsBodyParser: FieldsBodyParser, renderer: Renderer, components: ControllerComponents, implicit val ec: ExecutionContext, implicit val mat: Materializer ) extends AbstractController(components) { def find: Action[Fields] = authenticated(Roles.read).async(fieldsBodyParser) { request ⇒ val query = request.body.getValue("query").fold[QueryDef](QueryDSL.any)(_.as[QueryDef]) val range = request.body.getString("range") val sort = request.body.getStrings("sort").getOrElse(Nil) val isAdmin = request.roles.contains(Roles.orgAdmin) val (analyzers, analyzerTotal) = workerSrv.findAnalyzersForUser(request.userId, query, range, sort) renderer.toOutput(OK, analyzers.map(analyzerJson(isAdmin)), analyzerTotal) } def get(analyzerId: String): Action[AnyContent] = authenticated(Roles.read).async { request ⇒ val isAdmin = request.roles.contains(Roles.orgAdmin) workerSrv .getForUser(request.userId, analyzerId) .map(a ⇒ renderer.toOutput(OK, analyzerJson(isAdmin)(a))) } private def analyzerJson(isAdmin: Boolean)(analyzer: Worker): JsObject = if (isAdmin) analyzer.toJson + ("configuration" → Json.parse(analyzer.configuration())) + ("analyzerDefinitionId" → JsString(analyzer.workerDefinitionId())) else analyzer.toJson + ("analyzerDefinitionId" → JsString(analyzer.workerDefinitionId())) def listForType(dataType: String): Action[AnyContent] = authenticated(Roles.read).async { request ⇒ import org.elastic4play.services.QueryDSL._ val (responderList, responderCount) = workerSrv.findAnalyzersForUser(request.userId, "dataTypeList" ~= dataType, Some("all"), Nil) renderer.toOutput(OK, responderList.map(analyzerJson(isAdmin = false)), responderCount) } def create(analyzerDefinitionId: String): Action[Fields] = authenticated(Roles.orgAdmin).async(fieldsBodyParser) { implicit request ⇒ for { organizationId ← userSrv.getOrganizationId(request.userId) workerDefinition ← Future.fromTry(workerSrv.getDefinition(analyzerDefinitionId)) analyzer ← workerSrv.create(organizationId, workerDefinition, request.body) } yield renderer.toOutput(CREATED, analyzerJson(isAdmin = false)(analyzer)) } def listDefinitions: Action[AnyContent] = authenticated(Roles.orgAdmin, Roles.superAdmin).async { _ ⇒ val (analyzers, analyzerTotal) = workerSrv.listAnalyzerDefinitions renderer.toOutput(OK, analyzers, analyzerTotal) } def scan: Action[AnyContent] = authenticated(Roles.orgAdmin, Roles.superAdmin) { _ ⇒ workerSrv.rescan() NoContent } def delete(analyzerId: String): Action[AnyContent] = authenticated(Roles.orgAdmin, Roles.superAdmin).async { implicit request ⇒ for { analyzer ← workerSrv.getForUser(request.userId, analyzerId) _ ← workerSrv.delete(analyzer) } yield NoContent } def update(analyzerId: String): Action[Fields] = authenticated(Roles.orgAdmin).async(fieldsBodyParser) { implicit request ⇒ for { analyzer ← workerSrv.getForUser(request.userId, analyzerId) updatedAnalyzer ← workerSrv.update(analyzer, request.body) } yield renderer.toOutput(OK, analyzerJson(isAdmin = true)(updatedAnalyzer)) } }
Example 24
Source File: ResponderConfigCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import scala.concurrent.{ExecutionContext, Future} import play.api.libs.json.JsObject import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import javax.inject.{Inject, Singleton} import org.thp.cortex.models.{BaseConfig, Roles} import org.thp.cortex.services.{ResponderConfigSrv, UserSrv} import org.elastic4play.BadRequestError import org.elastic4play.controllers.{Authenticated, Fields, FieldsBodyParser, Renderer} @Singleton class ResponderConfigCtrl @Inject()( responderConfigSrv: ResponderConfigSrv, userSrv: UserSrv, authenticated: Authenticated, fieldsBodyParser: FieldsBodyParser, renderer: Renderer, components: ControllerComponents, implicit val ec: ExecutionContext ) extends AbstractController(components) { def get(analyzerConfigName: String): Action[AnyContent] = authenticated(Roles.orgAdmin).async { request ⇒ responderConfigSrv .getForUser(request.userId, analyzerConfigName) .map(renderer.toOutput(OK, _)) } def list(): Action[AnyContent] = authenticated(Roles.orgAdmin).async { request ⇒ responderConfigSrv .listConfigForUser(request.userId) .map { bc ⇒ renderer.toOutput( OK, bc.sortWith { case (BaseConfig("global", _, _, _), _) ⇒ true case (_, BaseConfig("global", _, _, _)) ⇒ false case (BaseConfig(a, _, _, _), BaseConfig(b, _, _, _)) ⇒ a.compareTo(b) < 0 } ) } } def update(analyzerConfigName: String): Action[Fields] = authenticated(Roles.orgAdmin).async(fieldsBodyParser) { implicit request ⇒ request.body.getValue("config").flatMap(_.asOpt[JsObject]) match { case Some(config) ⇒ responderConfigSrv .updateOrCreate(request.userId, analyzerConfigName, config) .map(renderer.toOutput(OK, _)) case None ⇒ Future.failed(BadRequestError("attribute config has invalid format")) } } }
Example 25
Source File: OAuth2ProviderActionBuildersSpec.scala From play2-oauth2-provider with MIT License | 5 votes |
package scalaoauth2.provider import javax.inject.Inject import org.scalatest._ import org.scalatest.Matchers._ import play.api.mvc.{AbstractController, ControllerComponents} import play.api.test._ import play.api.test.Helpers._ import play.api.test.FakeRequest class OAuth2ProviderActionBuildersSpec extends FlatSpec { class MyController @Inject() (components: ControllerComponents) extends AbstractController(components) with OAuth2ProviderActionBuilders { val action = AuthorizedAction(new MockDataHandler) { request => Ok(request.authInfo.user.name) } } it should "return BadRequest" in { val controller = new MyController(Helpers.stubControllerComponents()) val result = controller.action(FakeRequest()) status(result) should be(400) contentAsString(result) should be("") } }
Example 26
Source File: RealWorldAbstractController.scala From scala-play-realworld-example-app with MIT License | 5 votes |
package commons.controllers import commons.exceptions.ValidationException import commons.models.ValidationResultWrapper import play.api.libs.json.{JsError, Json, Reads} import play.api.mvc.{AbstractController, BodyParser, ControllerComponents, Result} import scala.concurrent.ExecutionContext abstract class RealWorldAbstractController(controllerComponents: ControllerComponents) extends AbstractController(controllerComponents) { implicit protected val executionContext: ExecutionContext = defaultExecutionContext protected def validateJson[A: Reads]: BodyParser[A] = parse.json.validate( _.validate[A].asEither.left.map(e => BadRequest(JsError.toJson(e))) ) protected def handleFailedValidation: PartialFunction[Throwable, Result] = { case e: ValidationException => val errors = e.violations .groupBy(_.property) .view .mapValues(_.map(propertyViolation => propertyViolation.violation.message)) .toMap val wrapper: ValidationResultWrapper = ValidationResultWrapper(errors) UnprocessableEntity(Json.toJson(wrapper)) } }
Example 27
Source File: WebSockets.scala From Scala-Programming-Projects with MIT License | 5 votes |
package controllers import actors.{BrowserManagerActor, BrowserActor} import akka.actor.{ActorRef, ActorSystem} import akka.stream.Materializer import javax.inject._ import play.api.Logger import play.api.libs.streams.ActorFlow import play.api.mvc.{AbstractController, ControllerComponents, WebSocket} @Singleton class WebSockets @Inject()( implicit actorSystem: ActorSystem, materializer: Materializer, cc: ControllerComponents) extends AbstractController(cc) { val managerActor: ActorRef = actorSystem.actorOf(BrowserManagerActor.props(), "manager-actor") def cartEventWS: WebSocket = WebSocket.accept[String, String] { implicit request => ActorFlow.actorRef { out => Logger.info(s"Got a new websocket connection from ${request.host}") managerActor ! BrowserManagerActor.AddBrowser(out) BrowserActor.props(managerActor) } } }
Example 28
Source File: ChangePasswordController.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package controllers import javax.inject.Inject import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.api.actions.SecuredRequest import com.mohiva.play.silhouette.api.exceptions.ProviderException import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository import com.mohiva.play.silhouette.api.util.{Credentials, PasswordHasherRegistry, PasswordInfo} import com.mohiva.play.silhouette.impl.providers.CredentialsProvider import forms.ChangePasswordForm import play.api.i18n.{I18nSupport, Messages} import play.api.libs.json.Json import play.api.mvc.{AbstractController, AnyContent, ControllerComponents} import utils.auth.{DefaultEnv, HasSignUpMethod} import scala.concurrent.{ExecutionContext, Future} def submit = silhouette.SecuredAction(hasSignUpMethod[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request: SecuredRequest[DefaultEnv, AnyContent] => ChangePasswordForm.form.bindFromRequest.fold( form => Future.successful(BadRequest), password => { val (currentPassword, newPassword) = password val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword) credentialsProvider.authenticate(credentials).flatMap { loginInfo => val passwordInfo = passwordHasherRegistry.current.hash(newPassword) authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ => Ok(Json.obj("success" -> Messages("password.changed"))) } }.recover { case _: ProviderException => BadRequest(Json.obj("message" -> Messages("current.password.invalid"))) } } ) } }
Example 29
Source File: ResetPasswordController.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package controllers import java.util.UUID import javax.inject.Inject import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository import com.mohiva.play.silhouette.api.util.{PasswordHasherRegistry, PasswordInfo} import com.mohiva.play.silhouette.impl.providers.CredentialsProvider import forms.ResetPasswordForm import models.services.{AuthTokenService, UserService} import play.api.libs.json.Json import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request} import utils.auth.DefaultEnv import scala.concurrent.{ExecutionContext, Future} def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] => authTokenService.validate(token).flatMap { case Some(authToken) => ResetPasswordForm.form.bindFromRequest.fold( _ => Future.successful(BadRequest), password => userService.retrieveUserLoginInfo(authToken.userID, CredentialsProvider.ID).flatMap { case Some((user, loginInfo)) => val passwordInfo = passwordHasherRegistry.current.hash(password) authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ => Ok } case _ => Future.successful(BadRequest(Json.obj("message" -> "Reset token is either invalid or has expired. Please reset your password again."))) } ) case None => Future.successful(BadRequest(Json.obj("message" -> "Reset token is either invalid or has expired. Please reset your password again."))) } } }
Example 30
Source File: SignUpController.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package controllers import java.util.UUID import javax.inject.Inject import com.mohiva.play.silhouette.api._ import forms.SignUpForm import models.services._ import play.api.i18n.I18nSupport import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request} import utils.auth.DefaultEnv import scala.concurrent.{ExecutionContext, Future} def submit = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] => SignUpForm.form.bindFromRequest.fold( _ => Future.successful(BadRequest), data => { val activationUrlProvider: UUID => String = authTokenId => routes.ActivateAccountController.activate(authTokenId).absoluteURL() signUpService.signUpByCredentials(data, request.remoteAddress, activationUrlProvider).map { case UserCreated(user) => silhouette.env.eventBus.publish(SignUpEvent(user, request)) Ok case UserAlreadyExists => Conflict case InvalidRecaptchaCode => BadRequest("Captcha code is not correct") } } ) } }
Example 31
Source File: ActivateAccountController.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package controllers import java.net.URLDecoder import java.util.UUID import javax.inject.Inject import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.impl.providers.CredentialsProvider import models.services.{AuthTokenService, MailService, UserService} import play.api.mvc.{AbstractController, ControllerComponents} import utils.auth.DefaultEnv import scala.concurrent.{ExecutionContext, Future} def activate(token: UUID) = silhouette.UnsecuredAction.async { authTokenService.validate(token).flatMap { case Some(authToken) => userService.retrieveUserLoginInfo(authToken.userID, CredentialsProvider.ID).flatMap { case Some((user, _)) => userService.setEmailActivated(user).map { _ => Redirect("/signin?message=emailVerified") } case _ => Future.successful(Redirect("/error?message=activationTokenInvalid")) } case None => Future.successful(Redirect("/error?message=activationTokenInvalid")) } } }
Example 32
Source File: MyController.scala From play-grpc with Apache License 2.0 | 5 votes |
// #using-client package controllers import example.myapp.helloworld.grpc.helloworld.GreeterServiceClient import example.myapp.helloworld.grpc.helloworld.HelloRequest import javax.inject.Inject import javax.inject.Singleton import play.api.mvc.AbstractController import play.api.mvc.ControllerComponents import scala.concurrent.ExecutionContext @Singleton class MyController @Inject() ( implicit greeterClient: GreeterServiceClient, cc: ControllerComponents, exec: ExecutionContext, ) extends AbstractController(cc) { def sayHello(name: String) = Action.async { greeterClient .sayHello(HelloRequest(name)) .map { reply => Ok(s"response: ${reply.message}") } } } // #using-client
Example 33
Source File: HealthController.scala From vinyldns with Apache License 2.0 | 5 votes |
package controllers import javax.inject.{Inject, Singleton} import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import vinyldns.core.health.HealthService @Singleton class HealthController @Inject() (components: ControllerComponents, healthService: HealthService) extends AbstractController(components) with CacheHeader { def health(): Action[AnyContent] = Action { implicit request => healthService .checkHealth() .map { case Nil => Ok("OK").withHeaders(cacheHeaders: _*) case _ => InternalServerError("There was an internal server error.").withHeaders(cacheHeaders: _*) } .unsafeRunSync() } }
Example 34
Source File: YamlContent.scala From metronome with Apache License 2.0 | 5 votes |
package dcos.metronome package api import net.jcazevedo.moultingyaml.{YamlValue, _} import play.api.http.{ContentTypeOf, MimeTypes, Writeable} import play.api.mvc.{Accepting, BodyParser, Codec, AbstractController} import scala.concurrent.Future trait YamlContent { self: AbstractController => import scala.concurrent.ExecutionContext.Implicits.global val AcceptJson = Accepting(MimeTypes.JSON) val AcceptYaml = Accepting("application/x-yaml") implicit val YamlContentType = ContentTypeOf[YamlValue](Some("application/x-yaml")) implicit def writeableOfYamlValue(implicit codec: Codec): Writeable[YamlValue] = { Writeable(yaml => codec.encode(yaml.prettyPrint)) } def parseYaml: BodyParser[YamlValue] = parse.when( _.contentType.exists(m => m.equalsIgnoreCase("text/yaml") || m.equalsIgnoreCase("application/x-yaml")), parse.tolerantText.map(_.parseYaml), _ => Future.successful(BadRequest("Expecting text/yaml or application/x-yaml body")) ) }