本文整理汇总了Scala中utils.auth.DefaultEnv类的典型用法代码示例。如果您正苦于以下问题:Scala DefaultEnv类的具体用法?Scala DefaultEnv怎么用?Scala DefaultEnv使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultEnv类的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: ChangePasswordController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api._
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 models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.{ DefaultEnv, WithProvider }
import scala.concurrent.Future
class ChangePasswordController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv],
userService: UserService,
credentialsProvider: CredentialsProvider,
authInfoRepository: AuthInfoRepository,
passwordHasherRegistry: PasswordHasherRegistry
)
extends Controller with I18nSupport {
def view = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)) { implicit request =>
Ok(views.html.changePassword(new myform.MyChangePasswordForm(), request.identity))
}
def submit = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
new myform.MyChangePasswordForm().bindFromRequest match {
case form: myform.MyChangePasswordForm => Future.successful(BadRequest(views.html.changePassword(form, request.identity)))
case data: myform.MyChangePasswordFormData => {
val (currentPassword, newPassword) = (data.currentPassword, data.newPassword)
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 { _ =>
Redirect(routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
}
}.recover {
case e: ProviderException =>
Redirect(routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
}
}
}
}
}
示例3: ResetPasswordController
//设置package包名称以及导入依赖的类
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 models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv
import scala.concurrent.Future
class ResetPasswordController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv],
userService: UserService,
authInfoRepository: AuthInfoRepository,
passwordHasherRegistry: PasswordHasherRegistry,
authTokenService: AuthTokenService
)
extends Controller with I18nSupport {
def view(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
authTokenService.validate(token).map {
case Some(authToken) => Ok(views.html.resetPassword(new myform.MyResetPasswordForm(), token))
case None => Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link"))
}
}
def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
authTokenService.validate(token).flatMap {
case Some(authToken) =>
new myform.MyResetPasswordForm().bindFromRequest match {
case form: myform.MyResetPasswordForm => Future.successful(BadRequest(views.html.resetPassword(form, token)))
case data: myform.MyResetPasswordFormData => userService.retrieve(authToken.userID).flatMap {
case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
val passwordInfo = passwordHasherRegistry.current.hash(data.password)
authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
Redirect(routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
}
case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
}
}
case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
}
}
}
示例4: ForgotPasswordController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import models.daos._
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv
import scala.concurrent.Future
class ForgotPasswordController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv],
userService: UserService,
authTokenService: AuthTokenService,
mailerClient: MailerClient,
envDAO: EnvDAO
)
extends Controller with I18nSupport {
def view = silhouette.UnsecuredAction.async { implicit request =>
Future.successful(Ok(views.html.forgotPassword(new myform.MyForgotPasswordForm())))
}
def submit = silhouette.UnsecuredAction.async { implicit request =>
new myform.MyForgotPasswordForm().bindFromRequest match {
case form: myform.MyForgotPasswordForm => Future.successful(BadRequest(views.html.forgotPassword(form)))
case data: myform.MyForgotPasswordFormData => {
val email = data.email
val loginInfo = LoginInfo(CredentialsProvider.ID, email)
val result = Redirect(routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
userService.retrieve(loginInfo).flatMap {
case Some(user) if user.email.isDefined =>
authTokenService.create(user.userID).map { authToken =>
val url = routes.ResetPasswordController.view(authToken.id).absoluteURL()
println("url " + url)
if (envDAO.getDosendmail) mailerClient.send(Email(
subject = Messages("email.reset.password.subject"),
from = Messages("email.from"),
to = Seq(email),
bodyText = Some(views.txt.emails.resetPassword(user, url).body),
bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
))
result
}
case None => Future.successful(result)
}
}
}
}
}
示例5: LogIn
//设置package包名称以及导入依赖的类
package controllers
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.{LoginEvent, Silhouette}
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.forms.UserLogInForm
import models.services.UserService
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc._
import utils.auth.DefaultEnv
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class LogIn @Inject()(
silhouette: Silhouette[DefaultEnv],
userService: UserService,
credentialsProvider: CredentialsProvider,
val messagesApi: MessagesApi)
extends Controller with I18nSupport {
def view = silhouette.UnsecuredAction{ implicit request =>
Ok(views.html.login(UserLogInForm.form))
}
def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
UserLogInForm.form.bindFromRequest.fold(
form => Future.successful(BadRequest(views.html.login(form))),
data => {
val credentials = Credentials(data.username, data.password)
credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
val result = Redirect(routes.Application.index())
userService.retrieve(loginInfo).flatMap {
case Some(user) if !user.activated =>
Future.successful(Ok(views.html.activateAccount(user.email)))
// Future.successful(Redirect(routes.LogIn.view()).flashing("error" -> "Account not activated."))
case Some(user) =>
silhouette.env.authenticatorService.create(loginInfo).flatMap {
authenticator =>
silhouette.env.eventBus.publish(LoginEvent(user, request))
silhouette.env.authenticatorService.init(authenticator).flatMap { v =>
silhouette.env.authenticatorService.embed(v, result)
}
}
case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
}
}
.recover {
case e: ProviderException =>
Redirect(routes.LogIn.view()).flashing("error" -> Messages("invalid.credentials"))
}
}
)
}
}
示例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: RegistrationController
//设置package包名称以及导入依赖的类
package controllers
import com.mohiva.play.silhouette.api.util.{PasswordHasher, PasswordHasherRegistry}
import com.mohiva.play.silhouette.api.{LoginEvent, LoginInfo, SignUpEvent, Silhouette}
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import com.omis.UserReg
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.Action
import services.{PasswordInfoService, UserService}
import utils.auth.DefaultEnv
import scala.concurrent.{ExecutionContext, Future}
class RegistrationController(userService: UserService, passwordInfoService: PasswordInfoService,
val messagesApi: MessagesApi,
passwordHasher: PasswordHasher,
silhouette: Silhouette[DefaultEnv])(implicit val ec: ExecutionContext) extends BaseController(silhouette) with I18nSupport {
def register = Action.async(parse.json) { implicit request =>
request.body.validate[UserReg].map { data =>
val loginInfo = LoginInfo(CredentialsProvider.ID, data.regCode)
userService.retrieve(loginInfo).flatMap {
case Some(user) =>
val passwordInfo = passwordHasher.hash(data.password)
for {
_ <- passwordInfoService.add(loginInfo, passwordInfo)
authenticator <- silhouette.env.authenticatorService.create(loginInfo)
token <- silhouette.env.authenticatorService.init(authenticator)
} yield {
silhouette.env.eventBus.publish(SignUpEvent(user, request))
silhouette.env.eventBus.publish(LoginEvent(user, request))
Ok(token)
}
case None =>
Future.successful(BadRequest(Json.obj("message" -> Messages("User not found."))))
}
}.recoverTotal {
case error =>
Future.successful(Unauthorized(Json.obj("message" -> Messages("Invalid data"))))
}
}
}
示例8: 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"))
}
}
}
}
示例9: 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)
}
}
示例10: DeadboltHandlerImpl
//设置package包名称以及导入依赖的类
package utils.auth.deadbolt
import javax.inject.{ Inject, Singleton }
import be.objectify.deadbolt.scala.models.Subject
import be.objectify.deadbolt.scala.{ AuthenticatedRequest, DeadboltHandler, DynamicResourceHandler }
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.util.ExtractableRequest
import models.services.UserService
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{ Request, Result, Results }
import utils.auth.DefaultEnv
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class DeadboltHandlerImpl @Inject() (val messagesApi: MessagesApi, silhouette: Silhouette[DefaultEnv], userService: UserService)
extends DeadboltHandler with I18nSupport {
override def beforeAuthCheck[A](request: Request[A]): Future[Option[Result]] = Future.successful(None)
override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] = {
implicit val extractableRequest = new ExtractableRequest(request)
silhouette.env.authenticatorService.retrieve.flatMap {
case Some(authenticator) =>
userService.retrieve(authenticator.loginInfo)
case None => Future.successful(None)
}
}
override def onAuthFailure[A](request: AuthenticatedRequest[A]): Future[Result] = {
println("Deadbolt: onAuthFailure triggered!")
Future.successful(Results.Unauthorized) // todo or does this need to accept?
}
override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] =
Future.successful(None)
}
示例11: 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)
}
}
示例12: WebSocketController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import actors.SocketActor
import akka.actor.ActorSystem
import akka.stream.Materializer
import com.mohiva.play.silhouette.api.{ HandlerResult, Silhouette }
import play.api.libs.streams._
import play.api.mvc._
import utils.auth.DefaultEnv
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class WebSocketController @Inject() (
implicit
system: ActorSystem,
materializer: Materializer,
silhouette: Silhouette[DefaultEnv]) extends Controller {
def secureSocket = WebSocket.acceptOrResult[String, String] { request =>
implicit val req = Request(request, AnyContentAsEmpty)
silhouette.SecuredRequestHandler { securedRequest =>
Future.successful(HandlerResult(Ok, Some(securedRequest.identity)))
}.map {
case HandlerResult(r, Some(user)) => Right(ActorFlow.actorRef(out => SocketActor.props(out)))
case HandlerResult(r, None) => Left(Unauthorized)
}
}
def socket = WebSocket.accept[String, String] { request =>
ActorFlow.actorRef(out => SocketActor.props(out))
}
}
示例13: 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))
}
}
示例14: _TuiGameController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import de.htwg.se.nmm.Game
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.Controller
import utils.auth.DefaultEnv
import scala.concurrent.Future
class _TuiGameController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv])
extends Controller with I18nSupport {
var tui = Game.getInstance().getTui
def set(command: String) = silhouette.SecuredAction { implicit request =>
process("set", command)
Ok(views.html.tuiGame(tui.printHTML(), request.identity))
}
def pick(command: String) = silhouette.SecuredAction { implicit request =>
process("pick", command)
Ok(views.html.tuiGame(tui.printHTML(), request.identity))
}
def move(command1: String, command2: String) = silhouette.SecuredAction { implicit request =>
process("move", String.format("%s,%s", command1, command2))
Ok(views.html.tuiGame(tui.printHTML(), request.identity))
}
def reset() = silhouette.SecuredAction { implicit request =>
tui.processInputLine(String.format("reset"))
Ok(views.html.tuiGame(tui.printHTML(), request.identity))
}
def get() = silhouette.SecuredAction { implicit request =>
Ok(views.html.tuiGame(tui.printHTML(), request.identity))
}
private def process(command: String, query: String) = {
tui.processInputLine(String.format("%s(%s)", command, query).toLowerCase())
}
}
示例15: GameController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import de.htwg.se.nmm.Game
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.Controller
import utils.auth.DefaultEnv
class GameController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv])
extends Controller with I18nSupport {
val gameController = Game.getInstance.getController
def index = silhouette.SecuredAction { implicit request =>
val player = gameController.getPlayerWithoutUserID(request.identity.userID)
if (player != null) {
player.setName(request.identity.fullName.getOrElse(player.getMan.toString()))
player.setUserID(request.identity.userID)
gameController.update()
}
Ok(views.html.game(request.identity))
}
def reset = silhouette.SecuredAction { implicit request =>
gameController.initNewGame()
gameController.update()
Redirect(routes.ApplicationController.index())
}
}