Skip to content

Instantly share code, notes, and snippets.

@amirkarimi
Last active October 3, 2016 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amirkarimi/481f6c2005d70679ee09 to your computer and use it in GitHub Desktop.
Save amirkarimi/481f6c2005d70679ee09 to your computer and use it in GitHub Desktop.
CookieAuthenticator implemented on top of ReactiveMongo and Silhouette
package services
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
import com.mohiva.play.silhouette.api.StorableAuthenticator
import com.mohiva.play.silhouette.impl.daos.AuthenticatorDAO
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import com.mohiva.play.silhouette.api.LoginInfo
import reactivemongo.bson._
import reactivemongo.api.collections.default.BSONCollection
import org.joda.time.DateTime
import xcala.play.extensions.BSONHandlers._
import xcala.play.services.WithExternalCollectionAccess
class CookieAuthenticatorService(implicit val ec: ExecutionContext) extends WithExternalCollectionAccess {
val collection: BSONCollection = collection("authenticators")
}
class CookieAuthenticatorDAO(service: CookieAuthenticatorService, implicit val ec: ExecutionContext) extends AuthenticatorDAO[CookieAuthenticator] {
implicit val logInfoHandler = BSONCookieAuthenticator.logInfoHandler
implicit val documentHandler = BSONCookieAuthenticator.CookieAuthenticatorHandler
def save(authenticator: CookieAuthenticator): Future[CookieAuthenticator] = {
service.collection.save(authenticator).map(_ => authenticator)
}
def find(id: String): Future[Option[CookieAuthenticator]] = {
service.collection.find(BSONDocument("_id" -> id)).one[CookieAuthenticator]
}
def remove(id: String): Future[Unit] = {
service.collection.remove(BSONDocument("_id" -> id)).map(_ => ())
}
}
object BSONCookieAuthenticator {
implicit val logInfoHandler = Macros.handler[LoginInfo]
implicit object CookieAuthenticatorHandler extends BSONHandler[BSONDocument, CookieAuthenticator] with BSONDocumentReader[CookieAuthenticator] with BSONDocumentWriter[CookieAuthenticator] {
def write(authenticator: CookieAuthenticator): BSONDocument = BSONDocument(
"_id" -> authenticator.id,
"loginInfo" -> authenticator.loginInfo,
"lastUsedDate" -> authenticator.lastUsedDate,
"expirationDate" -> authenticator.expirationDate,
"idleTimeout" -> authenticator.idleTimeout,
"fingerprint" -> authenticator.fingerprint
)
def read(doc: BSONDocument): CookieAuthenticator = CookieAuthenticator(
id = doc.getAs[String]("_id").get,
loginInfo = doc.getAs[LoginInfo]("loginInfo").get,
lastUsedDate = doc.getAs[DateTime]("lastUsedDate").get,
expirationDate = doc.getAs[DateTime]("expirationDate").get,
idleTimeout = doc.getAs[Int]("idleTimeout"),
fingerprint = doc.getAs[String]("fingerprint")
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment