Created
November 16, 2013 15:44
-
-
Save ostronom/7501644 to your computer and use it in GitHub Desktop.
Наколеночные action-ы для авторизации
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package controllers | |
| import scala.concurrent._ | |
| import play.api.mvc._ | |
| import play.api.libs.json._ | |
| import play.api.libs.concurrent.Execution.Implicits._ | |
| import play.modules.reactivemongo.json.collection.JSONCollection | |
| import play.modules.reactivemongo.MongoController | |
| import reactivemongo.api.DB | |
| import models._ | |
| case class AuthenticatedRequest[A](val user: Option[JsObject], request: Request[A]) | |
| extends WrappedRequest[A](request) | |
| trait Authentication { | |
| self: Controller with MongoController => | |
| val users: JSONCollection = db.collection[JSONCollection]("users") | |
| val sessions: JSONCollection = db.collection[JSONCollection]("sessions") | |
| def asId(id: String) = { Json.obj("_id" -> id) } | |
| def getUser(userId: String): Future[Option[JsObject]] = { | |
| sessions.find(asId(userId)).one[MTTSession] flatMap { | |
| case Some(session) => users.find(asId(session.userId)).one[JsObject] | |
| case None => Future { None } | |
| } | |
| } | |
| object Authenticated extends ActionBuilder[AuthenticatedRequest] { | |
| def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A] => Future[SimpleResult])) = { | |
| request.cookies.get("session").map { v => | |
| getUser(v.value) flatMap { user => block(AuthenticatedRequest(user, request)) } | |
| } getOrElse { block(AuthenticatedRequest(None, request)) } | |
| } | |
| } | |
| object StrictlyAuthenticated extends ActionBuilder[AuthenticatedRequest] { | |
| def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A] => Future[SimpleResult])) = { | |
| request.cookies.get("session").map { v => | |
| getUser(v.value) flatMap { user => block(AuthenticatedRequest(user, request)) } | |
| } getOrElse { Future.successful(Forbidden) } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| object Auth extends Controller with MongoController with Authentication { | |
| def check = Authenticated { request => | |
| request.user match { | |
| case Some(user) => Ok(User.exposeUser(user) getOrElse JsNull) | |
| case None => NotFound | |
| } | |
| } | |
| def login = Authenticated(parse.json) { request => ... | |
| } | |
| def logout = StrictlyAuthenticated { request => ... | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment