本文整理汇总了Scala中jp.t2v.lab.play2.auth.AuthElement类的典型用法代码示例。如果您正苦于以下问题:Scala AuthElement类的具体用法?Scala AuthElement怎么用?Scala AuthElement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AuthElement类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
}
}
开发者ID:haghard,项目名称:scenter-frontend,代码行数:37,代码来源:Aggregator.scala
示例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)
}
}
}
}
开发者ID:haghard,项目名称:scenter-frontend,代码行数:54,代码来源:DailyResults.scala
示例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)
}
})
}
}
开发者ID:pelagios,项目名称:recogito2,代码行数:34,代码来源:BaseAuthController.scala
示例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.")
}}
}
)
}
}
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:PasswordSettingsController.scala
示例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
}
}
开发者ID:pelagios,项目名称:recogito2,代码行数:61,代码来源:LoginLogoutController.scala
示例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))
}
}
}
开发者ID:chinhnk00494,项目名称:cw-CMR,代码行数:23,代码来源:CourseController.scala
示例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))
}
}
开发者ID:bananapianist,项目名称:playfw_sample,代码行数:28,代码来源:UserApi.scala
示例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")
}
}
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:58,代码来源:Companies.scala
示例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))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:29,代码来源:Releases.scala
示例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)))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:44,代码来源:Accounts.scala
示例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
}
}
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:37,代码来源:Histories.scala
示例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))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:52,代码来源:Validators.scala
示例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"
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:55,代码来源:Scraper.scala
示例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"))
}
}
开发者ID:tm-sukehiro,项目名称:play2-sandbox,代码行数:56,代码来源:HomeController.scala
示例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))
}
}
开发者ID:sakamotodesu,项目名称:play24auth,代码行数:45,代码来源:Message.scala
示例16: UserController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.native.Json4s
import jp.t2v.lab.play2.auth.AuthElement
import models.User
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc._
import queries.CreateUser
import scalikejdbc._
@Singleton
class UserController @Inject()(json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
import Responses._
implicit def formats = DefaultFormats
def show() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(loggedIn.minimal))
}
def list(public: Boolean) = Action {
import models.Aliases.u
val users = if(public) User.findAllBy(sqls.eq(u.public, true))
else User.findAll()
Ok(Extraction.decompose(users.map(_.minimal)))
}
def showMin(id: Long) = Action {
User.findById(id).fold(notFound("player")) { user =>
Ok(Extraction.decompose(user.minimal))
}
}
def createAccount() = Action(json) { req =>
req.body.extractOpt[CreateUser].fold(JsonParseError) { user =>
User.create(user.user())(AutoSession)
Success
}
}
def public(next: Boolean) = StackAction(AuthorityKey -> NormalUser) { implicit req =>
val result = User.updateById(loggedIn.id).withAttributes('public -> next)(AutoSession)
if(result > 0) Success else InternalServerError
}
}
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:51,代码来源:UserController.scala
示例17: ExifController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.native.Json4s
import com.ponkotuy.queries.Exif
import jp.t2v.lab.play2.auth.AuthElement
import models.{ExifSerializer, Image}
import org.json4s.{DefaultFormats, Extraction}
import org.json4s.ext.JodaTimeSerializers
import play.api.Logger
import play.api.mvc.{Action, Controller}
import scalikejdbc._
@Singleton
class ExifController @Inject()(json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import json4s._
implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
def upload() = StackAction(json, AuthorityKey -> NormalUser) { implicit req =>
req.body.extractOpt[Exif].fold(JsonParseError){ exif =>
DB localTx { implicit session =>
if(new ExifSerializer(exif).save(loggedIn.id).exists(0 < _)) {
Logger.info(s"Insert ${exif.fileName}")
Success
} else BadRequest("Duplicated?")
}
}
}
def list(userId: Long) = Action {
import models.Aliases.i
Ok(Extraction.decompose(Image.findAllBy(sqls.eq(i.userId, userId))))
}
}
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:40,代码来源:ExifController.scala
示例18: Messages
//设置package包名称以及导入依赖的类
package controllers.rememberme
import controllers.stack.Pjax
import jp.t2v.lab.play2.auth.AuthElement
import play.api.mvc.Controller
import views.html
import model.Role._
class Messages extends Controller with Pjax with AuthElement with AuthConfigImpl {
def main = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "message main"
Ok(html.message.main(title))
}
def list = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "all messages"
Ok(html.message.list(title))
}
def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "messages detail "
Ok(html.message.detail(title + id))
}
def write = StackAction(AuthorityKey -> Administrator) { implicit request =>
val title = "write message"
Ok(html.message.write(title))
}
protected val fullTemplate: User => Template = html.rememberme.fullTemplate.apply
}
开发者ID:phosphene,项目名称:play2.x-basic-auth-demo,代码行数:34,代码来源:Messages.scala
示例19: Messages
//设置package包名称以及导入依赖的类
package controllers.basic
import controllers.stack.Pjax
import jp.t2v.lab.play2.auth.AuthElement
import play.api.mvc.Controller
import views.html
import model.Role._
import play.twirl.api.Html
class Messages extends Controller with AuthElement with AuthConfigImpl {
def main = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "message main"
Ok(html.message.main(title))
}
def list = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "all messages"
Ok(html.message.list(title))
}
def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request =>
val title = "messages detail "
Ok(html.message.detail(title + id))
}
def write = StackAction(AuthorityKey -> Administrator) { implicit request =>
val title = "write message"
Ok(html.message.write(title))
}
protected implicit def template(implicit user: User): String => Html => Html = html.basic.fullTemplate(user)
}
开发者ID:phosphene,项目名称:play2.x-basic-auth-demo,代码行数:35,代码来源:Messages.scala
示例20: PreventingCsrfSample
//设置package包名称以及导入依赖的类
package controllers.csrf
import controllers.stack.TokenValidateElement
import jp.t2v.lab.play2.auth.AuthElement
import model.Role._
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.Controller
class PreventingCsrfSample extends Controller with TokenValidateElement with AuthElement with AuthConfigImpl {
def formWithToken = StackAction(AuthorityKey -> NormalUser, IgnoreTokenValidation -> true) { implicit req =>
Ok(views.html.csrf.formWithToken())
}
def formWithoutToken = StackAction(AuthorityKey -> NormalUser, IgnoreTokenValidation -> true) { implicit req =>
Ok(views.html.csrf.formWithoutToken())
}
val form = Form { single("message" -> text) }
def submitTarget = StackAction(AuthorityKey -> NormalUser) { implicit req =>
form.bindFromRequest.fold(
_ => throw new Exception,
message => Ok(message).as("text/plain")
)
}
}
开发者ID:phosphene,项目名称:play2.x-basic-auth-demo,代码行数:30,代码来源:PreventingCsrfSample.scala
注:本文中的jp.t2v.lab.play2.auth.AuthElement类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论