本文整理汇总了Scala中jp.t2v.lab.play2.auth.AuthElement类的典型用法代码示例。如果您正苦于以下问题:Scala AuthElement类的具体用法?Scala AuthElement怎么用?Scala AuthElement使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AuthElement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Aggregator
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc._
import ui.{HtmlStream, Pagelet}
import akka.actor.ActorSystem
import javax.inject.{Inject, Singleton}
import jp.t2v.lab.play2.auth.AuthElement
import frontend.{RegularUser, AuthorizationConfig}
@Singleton class Aggregator @Inject()(val conf: play.api.Configuration,
//controller: TaxiController,
rebCnt: ReboundLeaders, ptsCnt: PointsPerGameLeaders, daily: DailyResults,
val system: ActorSystem) extends Controller
with AuthElement with AuthorizationConfig
with MaterializerSupport {
val log: org.slf4j.Logger = akka.event.slf4j.Logger("aggregator")
def index(stage: String) = StackAction(AuthorityKey -> RegularUser) { implicit request =>
val user = loggedIn(request)
log.info(s"aggregator ${user.login} -> ${request.uri}")
val dailyStream = Pagelet.renderStream(daily.gateway("2016-02-10", user).map(views.html.daily.results(_)), "daily")
val rebStream = Pagelet.renderStream(rebCnt.gateway(stage, user).map(views.html.leaders.reb(_)), "reb-lead")
val prsStream = Pagelet.renderStream(ptsCnt.gateway(stage, user).map(views.html.leaders.pts(_)), "pts-lead")
val body = HtmlStream.interleave(rebStream, prsStream, dailyStream)
//TODO: use akka Source instead Enumerator
import ui.HtmlStreamImplicits._
Ok.chunked(views.stream.aggregatorBody(body))
}
}
示例2: DailyResult
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import akka.actor.ActorSystem
import frontend.{Account, AuthorizationConfig}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.libs.json.JsArray
import play.api.libs.ws.WSClient
import play.api.mvc.Controller
import scala.concurrent.Future
case class DailyResult(arena: String, guestTeam: String, homeTeam: String, guestScore: String, homeScore:String,
guestScoreLine:String, homeScoreLine:String, date: String)
@Singleton class DailyResults @Inject() (val conf: play.api.Configuration,
val ws: WSClient, val system: ActorSystem) extends Controller with AuthElement
with AuthorizationConfig with GatewaySupport {
override val key = "url.daily-results"
override val log = akka.event.slf4j.Logger("daily-results")
def gateway(stage: String, user: Account): Future[Seq[DailyResult]] = {
val url = getUrl(key, stage)
log.info(s"${user.login} -> $url")
ws.url(url).withHeaders(authHeader -> user.token).get().flatMap { response =>
response.status match {
case OK => Future {
(response.json \ "view").as[JsArray].value.map { item =>
val teams = item.\("lineup").as[String].trim.split("@")
val score = item.\("score").as[String].trim.split(" - ")
val guestT = score(0).split(":")
val guestFinalScore = guestT(1)
val guestScoreLine = guestT(0)
val homeT = score(1).split(":")
val homeFinalScore = homeT(1)
val homeScoreLine = homeT(0)
DailyResult(item.\("arena").as[String], s"$picPref${teams(0).trim}.gif", s"$picPref${teams(1).trim}.gif",
guestFinalScore, homeFinalScore, guestScoreLine, homeScoreLine,
item.\("time").as[String])
}
}
case FORBIDDEN => refreshGatewayToken[DailyResult](user, stage, gateway)
case badCode => Future.successful(Seq.empty)
}
}
}
}
示例3: BaseAuthController
//设置package包名称以及导入依赖的类
package controllers
import jp.t2v.lab.play2.auth.AuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.Result
import scala.concurrent.ExecutionContext
abstract class BaseAuthController(
config: Configuration,
documents: DocumentService,
users: UserService
) extends BaseController(config, users) with AuthElement {
protected def documentPartResponse(
docId: String,
partNo: Int,
user: UserRecord,
response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Result
)(implicit ctx: ExecutionContext) = {
documentResponse(docId, user, { case (doc, accesslevel) =>
doc.fileparts.find(_.getSequenceNo == partNo) match {
case None => NotFoundPage
case Some(part) => response(doc, part, accesslevel)
}
})
}
}
示例4: PasswordSettingsData
//设置package包名称以及导入依赖的类
package controllers.my.settings
import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.user.UserService
import models.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.Controller
import scala.concurrent.{ ExecutionContext, Future }
case class PasswordSettingsData(currentPassword: String, newPassword: String, verifyPassword: String)
class PasswordSettingsController @Inject() (
val config: Configuration,
val users: UserService,
val messagesApi: MessagesApi,
implicit val ctx: ExecutionContext
) extends Controller with AuthElement with HasConfig with HasUserService with Security 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() = StackAction(AuthorityKey -> Normal) { implicit request =>
Ok(views.html.my.settings.password(passwordSettingsForm, loggedIn.user))
}
def updatePassword() = AsyncStack(AuthorityKey -> Normal) { implicit request =>
passwordSettingsForm.bindFromRequest.fold(
formWithErrors =>
Future.successful(BadRequest(views.html.my.settings.password(formWithErrors, loggedIn.user))),
f => {
users.updatePassword(loggedIn.user.getUsername, 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.")
}}
}
)
}
}
示例5: LoginData
//设置package包名称以及导入依赖的类
package controllers.landing
import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.{ Inject, Singleton }
import jp.t2v.lab.play2.auth.{ AuthElement, LoginLogout }
import models.document.DocumentService
import models.user.UserService
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Action, Controller }
import scala.concurrent.{ ExecutionContext, Future }
case class LoginData(usernameOrPassword: String, password: String)
@Singleton
class LoginLogoutController @Inject() (
val config: Configuration,
val users: UserService,
implicit val ctx: ExecutionContext,
val messagesApi: MessagesApi
) extends Controller with AuthElement with HasConfig with HasUserService with Security with LoginLogout with I18nSupport {
private val MESSAGE = "message"
private val INVALID_LOGIN = "Invalid Username or Password"
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 = Action.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) => gotoLoginSucceeded(validUser.getUsername)
case None => Future(Redirect(routes.LoginLogoutController.showLoginForm()).flashing(MESSAGE -> INVALID_LOGIN))
}
)
}
def logout = Action.async { implicit request =>
gotoLogoutSucceeded
}
}
示例6: CourseController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import dao.{CMRDAO, RoleDAO, UserDAO, CourseDAO}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Controller
import play.api.libs.concurrent.Execution.Implicits.defaultContext
class CourseController @Inject()(courseDAO: CourseDAO, cmrDAO: CMRDAO, val userDAO: UserDAO, roleDAO: RoleDAO, val messagesApi: MessagesApi)
extends Controller with AuthConfigImpl with AuthElement with I18nSupport {
//TODO: Need to search and paging and order by
def list = AsyncStack(AuthorityKey -> roleDAO.authority("course.list")) { implicit request =>
val userLogin = loggedIn
courseDAO.findByUserRole(userLogin.roleId, userLogin.userId.get).map { pageData =>
Ok(views.html.courses(pageData, userLogin))
}
}
}
示例7: UserApi
//设置package包名称以及导入依赖的类
package controllers.admin
import scala.concurrent.Future
import scala.concurrent.Future.{successful => future}
import javax.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import utilities.auth.Role
import utilities.auth.Role._
import play.api.mvc._
import play.api.libs.json._
import controllers.auth.AuthConfigAdminImpl
import services.UserAccountServiceLike
class UserApi @Inject()(val userAccountService: UserAccountServiceLike) extends Controller with AuthElement with AuthConfigAdminImpl {
val UserAccountSv = userAccountService
def normaluser = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val user = loggedIn
Ok(Json.obj("id" -> user.id, "username" -> user.name, "email" -> user.email, "role" -> user.role))
}
def adminuser = StackAction(AuthorityKey -> Administrator) { implicit request =>
val user = loggedIn
Ok(Json.obj("id" -> user.id, "username" -> user.name, "email" -> user.email, "role" -> user.role))
}
}
示例8: Companies
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.{Administrator, NormalUser}
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Company, Fare, TrainType, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.Controller
import queries.{CreateCompany, CreateFares}
import scalikejdbc._
class Companies @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import json4s._
implicit val formats = DefaultFormats + TrainTypeSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
Ok(Extraction.decompose(Company.findAll(Seq(Company.defaultAlias.id))))
}
def create() = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateCompany].fold(JSONParseError) { company =>
DB localTx { implicit session =>
val id = company.company.save()
Ok(id.toString)
}
}
}
// Fare table?????????????????
def existsFare() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(Fare.existsFare()(AutoSession)))
}
def fares(companyId: Long, trainType: Int) = StackAction(AuthorityKey -> NormalUser) { implicit req =>
import models.DefaultAliases.f
TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
val fares = Fare.findAllBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, tType.value))
Ok(Extraction.decompose(fares))
}
}
def createFares(companyId: Long, trainType: Int) = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateFares].fold(JSONParseError) { fares =>
TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
DB localTx { implicit session =>
val f = Fare.column
Fare.deleteBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, trainType))
fares.fares.map(_.fare(companyId, tType)).foreach(_.save)
}
Ok("Success")
}
}
}
}
示例9: Releases
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Diagram, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import scalikejdbc._
import play.api.mvc.Controller
import responses.{DiagramResponse, ReleaseResponse}
class Releases @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
implicit val format = DefaultFormats + TrainTypeSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
import models.DefaultAliases.d
val diagrams = Diagram.joins(Diagram.stopStationRef).findAllBy(sqls.isNotNull(d.staging))
val result = diagrams.groupBy(_.staging.get).map {
case (staging, ds) =>
ReleaseResponse(staging, ds.map(DiagramResponse.fromDiagram))
}
Ok(Extraction.decompose(result))
}
}
示例10: Accounts
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Account, AccountSerializer, Mission}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import queries.CreateAccount
import scalikejdbc._
class Accounts @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
import Responses._
implicit val formats = DefaultFormats + AccountSerializer
def show() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(loggedIn))
}
def showMin(id: Long) = Action {
Account.findById(id).fold(notFound("player")) { account =>
Ok(Extraction.decompose(account.minimal))
}
}
def createAccount() = Action(json) { req =>
req.body.extractOpt[CreateAccount].fold(JSONParseError) { account =>
account.account.save()(AutoSession)
Success
}
}
def missions(id: Long) = Action {
import models.DefaultAliases.m
val missions = Mission.findAllBy(sqls.eq(m.creator, id))
Ok(Extraction.decompose(missions.sortBy(-_.rate)))
}
}
示例11: Histories
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Diagram, History}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import queries.CreateHistory
import scalikejdbc._
class Histories @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import controllers.Responses._
import json4s._
implicit val format = DefaultFormats
def list() = Action {
import models.DefaultAliases.h
Ok(Extraction.decompose(History.findAllWithLimitOffset(limit = 20, orderings = Seq(h.id.desc))))
}
def create() = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateHistory].fold(JSONParseError) { his =>
DB.localTx { implicit session =>
his.release.foreach { r =>
Diagram.updateBy(sqls.eq(Diagram.column.staging, r)).withAttributes('staging -> None)
}
his.history().save()
Success
}
}
}
}
示例12: Validators
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models._
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.Controller
import scalikejdbc.AutoSession
import utils.MethodProfiler
import validator._
class Validators @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
implicit val format = DefaultFormats + ErrorSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
import LineStation.{lineRef, stationRef}
val profiler = MethodProfiler.Nop
val errors = profiler("all") {
val diagrams = profiler("diagrams") {
Diagram.findAllIds()(AutoSession)
}
val stops = profiler("stops") {
StopStation.findAll()
}
val trains = profiler("trains") {
Train.allDiagramIds()(AutoSession).toSet
}
val stations = profiler("lineStations") {
LineStation.joins(lineRef, stationRef).findAll()
}
profiler("diagramsValidator") {
val validator = new DiagramValidator(stops, stations)
diagrams.flatMap(validator.validate)
} ++ profiler("stationStopValidator") {
new StationStopValidator(stops).validate(stations)
} ++ profiler("lackTrainValidator") {
val validator = new LackTrainValidator(trains)
diagrams.flatMap(validator.validate)
} ++ profiler("stationGeoValidator") {
val stations = Station.joins(Station.geoRef).findAll()
StationGeoValidator.validate(stations)
}
}
Ok(Extraction.decompose(errors))
}
}
示例13: Scraper
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import net.liftweb.util.Html5
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import scrape.model.{StationPage, TrainPage}
import scala.io.Codec
import scala.xml._
class Scraper @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import Scraper._
import json4s._
implicit val formats = DefaultFormats
def station(lineId: String, pageName: String) = Action { implicit req =>
val url = s"${Host}/newdata/ekijikoku/${lineId}/${pageName}.htm"
val xml = loadXML(url)
StationPage.fromXml(xml) match {
case Left(str) => notFound(str)
case Right(station) =>
val trains = station.trains.filterNot(_.add.contains("?"))
Ok(Extraction.decompose(trains.map(_.replaceAbbr(station.abbr))))
}
}
def timeTable(lineId: String, pageName: String) = StackAction(AuthorityKey -> Administrator) { implicit req =>
???
}
def train(lineId: String, trainId: String) = StackAction(AuthorityKey -> Administrator) { implicit req =>
val address = s"/newdata/detail/${lineId}/${trainId}.htm"
TrainPage.fromXML(loadXML(s"${Host}${address}"), address) match {
case Left(str) => notFound(str)
case Right(train) => Ok(Extraction.decompose(train))
}
}
private[this] def loadXML(url: String): NodeSeq = {
val html = scala.io.Source.fromURL(url)(Codec("Shift_JIS")).mkString
Html5.parse(html) openOr NodeSeq.Empty
}
}
object Scraper {
val Host = "http://www.ekikara.jp"
}
示例14: HomeController
//设置package包名称以及导入依赖的类
package controllers
import java.io.File
import javax.inject.{Inject, Singleton}
import akka.actor.ActorSystem
import controllers.api.auth.{AuthConfigImpl, NormalUser}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.Play
import play.api.mvc.{Action, Controller, Result}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class HomeController @Inject() (actorSystem: ActorSystem) extends Controller with AuthElement with AuthConfigImpl{
implicit val myExecutionContext: ExecutionContext = actorSystem.dispatcher
def index = AsyncStack(AuthorityKey -> NormalUser) { implicit request =>
Future {loadIndex()}
}
def indexAll(path: String) = AsyncStack(AuthorityKey -> NormalUser) { implicit request =>
Future {loadIndex()}
}
def loginForm = Action.async {
Future {loadIndex()}
}
def loadIndex():Result = {
val f = new File("webConsole/front/index.html")
Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
}
def dist(path: String) = Action {
val f = new File("webConsole/front/dist/" + path)
Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
}
def favicon() = Action {
val f = new File("webConsole/front/public/favicon")
Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
}
//DI?????Router?Controller???????????????
def routes() = Action {
val myRoutes = Play.current.routes.documentation map { r =>
"%-10s %-50s %s".format(r._1, r._2, r._3)
}
Ok(myRoutes.mkString("\n"))
}
}
示例15: Message
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.Role.{Administrator, NormalUser}
import play.api.mvc.Controller
import views.html
class Message @Inject() extends Controller with AuthElement with AuthConfigImpl {
// StackAction ? ??????????? (AuthorityKey, Authority) ???????????????
// ????? RequestWithAttribute[AnyContent] => Result ?????????
// AuthElement ? loggedIn[A](implicit RequestWithAttribute[A]): User ???????????????
// ??????????/?????????????????????
def main = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val user = loggedIn
val title = "message main"
Ok(html.message.main(user.name.toString))
}
def list = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val user = loggedIn
val title = "all messages"
Ok(html.message.list(title))
}
def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val user = loggedIn
val title = "messages detail "
Ok(html.message.detail(title + id))
}
// ??Action???Administrator ????????????????
def write = StackAction(AuthorityKey -> Administrator) { implicit request =>
val user = loggedIn
val title = "write message"
Ok(html.message.write(title))
}
}