本文整理汇总了Scala中com.mohiva.play.silhouette.api.Silhouette类的典型用法代码示例。如果您正苦于以下问题:Scala Silhouette类的具体用法?Scala Silhouette怎么用?Scala Silhouette使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Silhouette类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SignupController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.Silhouette
import forms.SignupForm
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.{Action, Controller, Flash}
import utils.auth.DefaultEnv
@Singleton
class SignupController @Inject()
(
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv]
) extends Controller with I18nSupport {
def createUser = Action { implicit request =>
println("trying to create!")
SignupForm.form.bindFromRequest.fold(
hasErrors = { form =>
Redirect(routes.SignupController.registerPage())
.flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
},
success = { signupData =>
println(s"creating a new user $signupData")
Redirect(routes.BookmarkController.list())
}
)
}
def registerPage = silhouette.UnsecuredAction { implicit request =>
Ok(views.html.users.register(SignupForm.form))
}
}
示例2: CoinController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api.{Environment, Silhouette}
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import forms.CoinAddForm
import models.User
import models.coin.{Person, WorkEntry}
import models.common.Pagination
import play.api.i18n.MessagesApi
import play.api.mvc.{Action, AnyContent}
import scala.concurrent.Future
class CoinController @Inject()(
val messagesApi: MessagesApi,
val env: Environment[User, CookieAuthenticator]
) extends Silhouette[User, CookieAuthenticator] {
val itemsPerPage = 9
def remove(id: Long): Action[AnyContent] = SecuredAction.async { implicit request =>
WorkEntry.remove(id)
Future.successful(Redirect(routes.CoinController.landing()))
}
}
示例3: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import scala.concurrent.Future
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.impl.providers.SocialProviderRegistry
import play.api.mvc._
import play.api.i18n.{I18nSupport, MessagesApi}
import utils.auth.CookieEnv
class Application @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[CookieEnv],
socialProviderRegistry: SocialProviderRegistry,
implicit val webJarAssets: WebJarAssets) extends Controller with I18nSupport {
import silhouette._
def index = UserAwareAction.async { implicit request =>
Future.successful(Ok(views.html.index(request.identity, request.authenticator.map(_.loginInfo))))
}
def profile = SecuredAction { implicit request =>
Ok(views.html.profile(request.identity, request.authenticator.loginInfo, socialProviderRegistry))
}
}
示例4: RestApi
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import scala.concurrent.Future
import com.mohiva.play.silhouette.api.Silhouette
import play.api.libs.json._
import play.api.mvc._
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import models.User
import User._
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import utils.auth.CookieEnv
class RestApi @Inject() (
val messagesApi: MessagesApi,
val silhouette: Silhouette[CookieEnv]) extends Controller with I18nSupport {
import silhouette._
def profile = SecuredAction.async { implicit request =>
val json = Json.toJson(request.identity.profileFor(request.authenticator.loginInfo).get)
val prunedJson = json.transform(
(__ \ 'loginInfo).json.prune andThen
(__ \ 'passordInfo).json.prune andThen
(__ \ 'oauth1Info).json.prune)
prunedJson.fold(
_ => Future.successful(InternalServerError(Json.obj("error" -> Messages("error.profileError")))),
js => Future.successful(Ok(js))
)
}
val errorHandler = new SecuredErrorHandler {
override def onNotAuthenticated(implicit request: RequestHeader) = {
Future.successful(Unauthorized(Json.obj("error" -> Messages("error.profileUnauth"))))
}
override def onNotAuthorized(implicit request: RequestHeader) = {
Future.successful(Forbidden("local.not.authorized"))
}
}
}
示例5: OAuth2Controller
//设置package包名称以及导入依赖的类
package controllers
import java.security.SecureRandom
import javax.inject.{Inject, Singleton}
import auth.{DefaultEnv, OAuthDataHandlerImpl}
import com.mohiva.play.silhouette.api.Silhouette
import models.daos.AccessTokenDAO
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc.{Controller, Request, Result}
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.ExecutionContext.Implicits._
import scalaoauth2.provider.{AuthorizationHandler, OAuth2Provider, OAuthGrantType, TokenEndpoint}
@Singleton
class OAuth2Controller @Inject() (
override val tokenEndpoint: TokenEndpoint,
config: Configuration,
secureRandom: SecureRandom,
accessTokenDAO: AccessTokenDAO,
silhouette: Silhouette[DefaultEnv]) extends Controller with OAuth2Provider {
def accessToken = silhouette.UserAwareAction.async { implicit request =>
request.identity match {
case Some(user) =>
issueAccessToken(new OAuthDataHandlerImpl(config, secureRandom, accessTokenDAO, Some(user)))
case _ => Future.successful(Redirect(routes.AuthController.getSignIn()))
}
}
override def issueAccessToken[A, U](handler: AuthorizationHandler[U])(implicit request: Request[A], ctx: ExecutionContext): Future[Result] = {
tokenEndpoint.handleRequest(request, handler).map {
case Left(e) => new Status(e.statusCode)(responseOAuthErrorJson(e)).withHeaders(responseOAuthErrorHeader(e))
case Right(r) =>
r.authInfo.redirectUri match {
case Some(uri) if request.grantType == OAuthGrantType.IMPLICIT =>
Redirect(s"$uri#token=${r.accessToken}")
case _ =>
Ok(Json.toJson(responseAccessToken(r))).withHeaders("Cache-Control" -> "no-store", "Pragma" -> "no-cache")
}
}
}
}
示例6: EmployeeController
//设置package包名称以及导入依赖的类
package controllers
import com.mohiva.play.silhouette.api.Silhouette
import com.omis.{EmpDetails, UserReg}
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.libs.json.Json
import repositories.Employee
import services.EmployeeService
import utils.auth.DefaultEnv
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random
class EmployeeController(
silhouette: Silhouette[DefaultEnv],
val messagesApi: MessagesApi, employeeService: EmployeeService
)(implicit val ec: ExecutionContext)
extends BaseController(silhouette) with I18nSupport {
def createEmp = silhouette.SecuredAction.async(parse.json) { req =>
if (req.identity.role == "admin") {
req.body.validate[EmpDetails].map { data =>
val codeList = Seq("AE", "BG", "NQ", "ZB", "TA", "OM", "IE", "PL", "LE", "AR", "AV", "DA", "FO")
val rand = new Random(System.currentTimeMillis())
val random_index = rand.nextInt(codeList.length)
val result = codeList(random_index)
employeeService.createEmpWithRole(Employee(
java.util.UUID.randomUUID(),
result, java.util.UUID.randomUUID(), java.util.UUID.randomUUID(), java.time.LocalDateTime.now(), java.time.LocalDateTime.now()
), "teacher", data).flatMap(
e => Future(Ok(e))
)
}.recoverTotal {
case error =>
Future.successful(Unauthorized(Json.obj("message" -> Messages("Invalid data"))))
}
} else {
Future(Forbidden)
}
}
def getAllEmp = withAdminSession("allEmp") {
_ =>
employeeService.getALl().map {
e => Ok(Json.toJson(e))
}
}
def getEmp = withSession("getProfile") {
req =>
{
println(req.identity.id)
employeeService.findEmpDetailsById(req.identity.id).map {
case Some(e) => Ok(Json.toJson(e))
case None => NotFound
}
}
}
}
示例7: BaseController
//设置package包名称以及导入依赖的类
package controllers
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.actions.{SecuredRequest, UserAwareRequest}
import play.api.libs.json.{JsValue, Reads}
import play.api.mvc._
import utils.AppLogger
import utils.auth.DefaultEnv
import scala.concurrent.{Future}
abstract class BaseController(silhouette: Silhouette[DefaultEnv]) extends Controller with AppLogger {
protected def unmarshalJsValue[R](request: Request[JsValue])(block: R => Future[Result])(implicit rds: Reads[R]): Future[Result] =
request.body.validate[R](rds).fold(
valid = block,
invalid = e => {
val error = e.mkString
log.error(error)
Future.successful(BadRequest(error))
}
)
def withoutSession(action: String)(block: UserAwareRequest[DefaultEnv, AnyContent] => Future[Result]) = {
silhouette.UserAwareAction.async { implicit request =>
block(request)
}
}
def withSession(action: String)(block: (SecuredRequest[DefaultEnv, AnyContent]) => Future[Result]) = {
silhouette.UserAwareAction.async { implicit request =>
request.identity match {
case Some(u) =>
val auth = request.authenticator.getOrElse(throw new IllegalStateException("You're not logged in."))
block(SecuredRequest(u, auth, request))
case None =>
Future.successful(Unauthorized("You are not authorized to access this resource"))
}
}
}
def withAdminSession(action: String)(block: (SecuredRequest[DefaultEnv, AnyContent]) => Future[Result]) = {
silhouette.UserAwareAction.async { implicit request =>
request.identity match {
case Some(u) =>
if (u.role == "admin") {
val auth = request.authenticator.getOrElse(throw new IllegalStateException("You're not logged in."))
block(SecuredRequest(u, auth, request))
} else {
Future.successful(Unauthorized("You are not authorized to access this resource"))
}
case None =>
Future.successful(Unauthorized("You are not authorized to access this resource"))
}
}
}
}
示例8: ViewController
//设置package包名称以及导入依赖的类
package controllers
import com.mohiva.play.silhouette.api.Silhouette
import play.api.Configuration
import play.api.i18n.{I18nSupport, MessagesApi}
import utils.auth.DefaultEnv
import scala.concurrent.{ExecutionContext, Future}
class ViewController(
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv],
implicit val webJarAssets: WebJarAssets,
implicit val config: Configuration,
implicit val ec: ExecutionContext
)
extends BaseController(silhouette) with I18nSupport {
def index = withoutSession("index") { implicit request =>
Future(Ok(html.app( )))
}
def bundleUrl(projectName: String): Option[String] = {
val name = projectName.toLowerCase
Seq(s"$name-opt-bundle.js", s"$name-fastopt-bundle.js")
.find(name => getClass.getResource(s"/public/$name") != null)
.map(controllers.routes.Assets.versioned(_).url)
}
}
示例9: BasicActorCtrl
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import akka.actor.ActorSystem
import akka.stream.Materializer
import com.mohiva.play.silhouette.api.{HandlerResult, Silhouette}
import models.daos.actors.ChatActorFactory
import play.api.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc._
import utils.DefaultEnv
import scala.concurrent.Future
class BasicActorCtrl @Inject()(
val messagesApi: MessagesApi,
implicit val mat: Materializer,
implicit val actorSystem: ActorSystem,
val chatActorFactory: ChatActorFactory,
silhouette: Silhouette[DefaultEnv]
) extends Controller with I18nSupport {
val log = Logger("IDP." + this.getClass.getSimpleName);
def send(eventName: String, username: String, token: String) = WebSocket.acceptOrResult[JsValue, JsValue] {
request =>
{
//log.debug(s"new query string: ${request.getQueryString("X-Auth-Token")}")
val tmpRequest = request.copy(headers = new Headers(Seq("X-Auth-Token" -> token)))
implicit val req = Request(tmpRequest, AnyContentAsEmpty)
silhouette.SecuredRequestHandler { securedRequest =>
Future.successful(HandlerResult(Ok, Some(securedRequest.identity)))
}.map {
case HandlerResult(r, Some(user)) => {
Right(ActorFlow.actorRef(chatActorFactory.props(username, eventName, _)))
}
case HandlerResult(r, None) => {
Left(r)
}
}
}
}
}
示例10: Auth
//设置package包名称以及导入依赖的类
package utils.auth.deadbolt
import javax.inject.{Inject, Singleton}
import be.objectify.deadbolt.scala.DeadboltActions
import com.mohiva.play.silhouette.api.Silhouette
import models.Roles
import play.api.mvc.{BodyParser, BodyParsers, Result, Results}
import utils.auth.DefaultEnv
import scala.concurrent.Future
@Singleton
class Auth @Inject()(deadboltActions: DeadboltActions, silhouette: Silhouette[DefaultEnv])
extends Results with BodyParsers {
def SubjectPresent[B](parser: BodyParser[B] = parse.anyContent)(block: SecureRequest[B] => Future[Result]) =
silhouette.SecuredAction.async(parser) { implicit req =>
deadboltActions.SubjectPresent()(parser)(block.compose(_ => new SecureRequest(req)))(req)
}
def Restrict[B](parser: BodyParser[B] = parse.anyContent)(role: Roles.Role)(block: SecureRequest[B] => Future[Result]) =
silhouette.SecuredAction.async(parser) { implicit request =>
deadboltActions.Restrict(role.group)(parser)(block.compose(_ => new SecureRequest(request)))(request)
}
}
示例11: AboutController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Action, Controller }
import utils.auth.DefaultEnv
class AboutController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv])
extends Controller with I18nSupport {
def index = silhouette.UserAwareAction { implicit request =>
Ok(views.html.about(request.identity))
}
def help = silhouette.UserAwareAction { implicit request =>
Redirect(routes.AboutController.index())
}
def technologies = silhouette.UserAwareAction { implicit request =>
Ok(views.html.technologies(request.identity))
}
}
示例12: LocalizationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import play.api.i18n.{ I18nSupport, MessagesApi, Lang }
import play.api.mvc.Controller
import utils.auth.DefaultEnv
class LocalizationController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv])
extends Controller with I18nSupport {
def langDE = silhouette.UserAwareAction { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
Redirect(referrer).withLang(Lang("de"))
}
def langEN = silhouette.UserAwareAction { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
Redirect(referrer).withLang(Lang("en"))
}
}
示例13: ProductController
//设置package包名称以及导入依赖的类
package controllers
import scala.concurrent.Future
import javax.inject._
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.Clock
import com.mohiva.play.silhouette.impl.providers.{CredentialsProvider, SocialProviderRegistry}
import forms.ProductForm
import models.Product
import models.daos.ProductDAO
import models.services.UserService
import play.api.Configuration
import play.api.i18n.I18nSupport
import play.api.i18n.MessagesApi
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv
@Singleton
class ProductController @Inject()(val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv],
userService: UserService,
authInfoRepository: AuthInfoRepository,
credentialsProvider: CredentialsProvider,
socialProviderRegistry: SocialProviderRegistry,
configuration: Configuration,
clock: Clock,
productDAO: ProductDAO,
implicit val webJarAssets: WebJarAssets)
extends Controller with I18nSupport {
private val logger = org.slf4j.LoggerFactory.getLogger(this.getClass)
def list = silhouette.SecuredAction.async { implicit request =>
productDAO.all().map { products =>
logger.info(s"Calling index: products = ${products}")
Ok(views.html.products.list(request.identity, ProductForm.form, products))
}
}
def add = silhouette.SecuredAction.async { implicit request =>
ProductForm.form.bindFromRequest.fold(
form => Future.successful(BadRequest(views.html.products.details(request.identity,ProductForm.form))),
data => {
val product = Product(
ean = data.ean,
name = data.name,
description = data.description
)
productDAO.insert(product).map(_ => Redirect(routes.ProductController.list))
}
)
}
}
示例14: UserResourceController
//设置package包名称以及导入依赖的类
package com.clemble.loveit.thank.controller
import javax.inject.{Inject, Singleton}
import com.clemble.loveit.common.util.AuthEnv
import com.clemble.loveit.thank.service.repository.UserResourceRepository
import com.mohiva.play.silhouette.api.Silhouette
import play.api.mvc.Controller
import scala.concurrent.ExecutionContext
@Singleton
case class UserResourceController @Inject()(
repo: UserResourceRepository,
silhouette: Silhouette[AuthEnv],
implicit val ec: ExecutionContext
) extends Controller {
def getMy() = silhouette.SecuredAction.async(implicit req => {
val fUserResource = repo.find(req.identity.id)
fUserResource.map(_ match {
case Some(res) => Ok(res)
case None => NotFound
})
})
}
示例15: UserSupportedProjectController
//设置package包名称以及导入依赖的类
package com.clemble.loveit.thank.controller
import javax.inject.Inject
import com.clemble.loveit.common.model.UserID
import com.clemble.loveit.common.util.AuthEnv
import com.clemble.loveit.thank.service.UserSupportedProjectsService
import com.mohiva.play.silhouette.api.Silhouette
import play.api.libs.json.Json
import play.api.mvc.Controller
import scala.concurrent.ExecutionContext
class UserSupportedProjectController @Inject()(
supportedProjectsService: UserSupportedProjectsService,
silhouette: Silhouette[AuthEnv],
implicit val ec: ExecutionContext
) extends Controller {
def getSupported(supporter: UserID) = silhouette.SecuredAction.async(implicit req => {
supportedProjectsService.
getSupported(supporter).
map(projects => Ok(Json.toJson(projects)))
})
}