ReactiveMongo Scala DAO pattern - scala

I have the following DAO, Service Object and Controller pattern in my Playframework project:
CredentialsDAO.scala:
def find(authType: AuthType.Value, authAccountId: String) =
collection.find(
Json.obj(Fields.AuthType → authType,
Fields.AuthAccountId → authAccountId)).one[Credentials].recover(wrapLastError)
CredentialsService.scala:
def checkEmailPassword(email: String, password: String) = credentialsDAO.find(AuthType.EmailPassword, email).map(_.get) //Needs review
In my controller:
def auth = Action.async(parse.json) { request =>
{
val authRequest = request.body.validate[AuthRequest]
authRequest.fold(
errors => Future(BadRequest),
auth => {
//First verify username and password
val authRequestResult = for {
validCredential <- credentialsManager.checkEmailPassword(auth.email, auth.password)
validPassword <- BCrypt.checkFuture(auth.password, validCredential.passwordHash)
validAccount <- accountManager.getAccount(validCredential)
session <- sessionManager.createSession(validAccount.id, validAccount.roles)
touchedSession <- sessionManager.touchSession(session.id)
} yield AuthResponse(session.id, session.token, validAccount.id, validAccount.roles)
authRequestResult map {
case res: AuthResponse => Ok(Json.toJson(res))
case _ => NotFound
}
})
}
}
Question: Is this 'pattern' okay from a functional programming perspective? In particular, I'm bothered by this line in CredentialsService.scala:
def checkEmailPassword(email: String, password: String) = credentialsDAO.find(AuthType.EmailPassword, email).map(_.get) //Needs review
I'm new to Scala but I think there are better ways of dealing with _.get in the line above? Any suggestions/ideas would be highly appreciated.
Thanks in advance.

Related

Sending zio http response from callback function

I am trying to play around with ZIO http using their simples hello world example. I have a Java-written service which does some logic, and it expecting a handler function, so it can call it when result is ready. How do I user it together with ZIO http ?
I want something like this:
object HelloWorld extends App {
def app(service: JavaService) = Http.collect[Request] {
case Method.GET -> Root / "text" => {
service.doSomeStuffWIthCallback((s:String) => Response.text(s))
}
}
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app(new JavaService)).exitCode
}
Basically I want to send ZIO HTTP response from the callback function, I am just not sure how to go about that. Thanks.
EDIT:
I coudn't get the right types from your code, so I decided to simplify the whole thing, and arrived to this:
val content: HttpData[Blocking, Throwable] = HttpData.fromStream {
ZStream.fromEffect(doSomeStuffWrapped)
}
def doSomeStuffWrapped = {
UIO.effectAsync[String] { cb =>
cb(
IO.succeed("TEST STRING")
)
}
}
However, the issue here is that types do not match, HttpData.fromStream requires ZStream of byte
Here is the link to my gist:
https://gist.github.com/pmkyl/a37ff8b49e013c4e2e6f8ab5ad83e258
You should wrap your Java service with callback in an effect using effectAsync:
def doSomeStuffWrapped(service: JavaService): Task[String] = {
IO.effectAsync[Throwable, String] { cb =>
service.doSomeStuffWithCallback((s: String) => {
// Success case
cb(IO.succeed(s))
// Optional error case?
// cb(IO.fail(someException))
})
}
}
def app(service: JavaService) = Http.collectM[Request] {
case Method.GET -> Root / "text" => {
doSomeStuffWrapped(service)
.fold(err => {
// Handle errors in some way
Response.text("An error occured")
}, successStr => {
Response.text(successStr)
})
}
}
You might want to see this article presenting different options for wrapping impure code in ZIO: https://medium.com/#ghostdogpr/wrapping-impure-code-with-zio-9265c219e2e
In ZIO-http v1.0.0.0-RC18 HttpData.fromStream can also take ZStream[R, E, String] as input with Http charset which defaults to CharsetUtil.UTF_8 however you can pass any charset to the HttpData.fromStream as its second argument. you can find the solution below
val stream: ZStream[Any, Nothing, String] = ZStream.fromEffect(doSomeStuffWrapped)
val content: HttpData[Any, Nothing] = HttpData.fromStream(stream)
def doSomeStuffWrapped = {
UIO.effectAsync[String] { cb =>
cb(
IO.succeed("TEST STRING"),
)
}
}
// Create HTTP route
val app = Http.collect[Request] {
case Method.GET -> !! / "health" => Response.ok
case Method.GET -> !! / "file" => Response(data = content)
}
// Run it like any simple app
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app.silent).exitCode
However in previous versions you could have done something like given below to make it work
val stream: ZStream[Any, Nothing, Byte] =
ZStream.fromEffect(doSomeStuffWrapped).mapChunks(_.map(x => Chunk.fromArray(x.getBytes(HTTP_CHARSET))).flatten)
val content: HttpData[Any, Nothing] = HttpData.fromStream(stream)
def doSomeStuffWrapped = {
UIO.effectAsync[String] { cb =>
cb(
IO.succeed("TEST STRING"),
)
}
}
// Create HTTP route
val app = Http.collect[Request] {
case Method.GET -> !! / "health" => Response.ok
case Method.GET -> !! / "file" => Response(data = content)
}
// Run it like any simple app
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app.silent).exitCode
Here is also another way of achieving the same result:
case class MyService(name: String) {
def imDone[R, E](s: String => Unit): Unit = s(name)
}
val s: MyService = MyService("test")
val app: Http[Any, Nothing, Request, UResponse] = Http.collectM[Request] { case Method.GET -> Root / "text" =>
ZIO.effectAsync[Any, Nothing, UResponse] { cb =>
s.imDone { b =>
cb(IO.succeed(Response.text(b)))
}
}
}

How to refactor this scala code?

I want to refactor this code into something more readable and better in general. I know that in Scala there are normally neat ways of doing things but for me it's getting a bit messy (BTW I'm using the Play library in the code). this is a snippet of my code:
class HomeController #Inject()
(cc: ControllerComponents)
(implicit val config: Configuration)
extends AbstractController(cc) {
def removeIdElement(uid: String) =
HAction(uid, "AuthEvent", 1, "login", parse.text).async {
implicit request: Request[String] =>
val promise = Promise[Result]()
Future {
val removeId = request.body.toLong
println(s"remove id $removeId")
promise completeWith {
idElementsDAO.remove(removeId, uid.toLong) map {
_ => Ok("")
} recover {
case t: Throwable =>
val errorMessage: String = getMessageFromThrowable(t)
println("remove id element failure " + errorMessage)
BadRequest(errorMessage)
}
}
} recover {
case t: Throwable =>
val errorMessage: String = getMessageFromThrowable(t)
println("remove id element failure " + errorMessage)
promise.success(BadRequest(errorMessage))
}
promise.future
}
}
Assuming that idElementsDAO.remove return a Future, this is probably more idiomatic:
def removeIdElement(uid: String) =
HAction(uid, "AuthEvent", 1, "login", parse.text).async {implicit request =>
val removeId = request.body.toLong
println(s"remove id $removeId")
idElementsDAO.remove(removeId, uid.toLong)
.map(_ => NoContent) // probably more correct than `Ok("")`
.recover {
case t: Throwable =>
val errorMessage: String = getMessageFromThrowable(t)
println("remove id element failure " + errorMessage)
BadRequest(errorMessage)
}
}
No need for the Promise or the call to Future {...} (Future.apply).
Keep in mind, it's probably not the best idea to directly pass the underlying error of any Throwable directly to the http client (browser?).
If you add generic error handling code to the global error handler (for unexpected errors) that logs the error and sends a generic message to the front-end, you can then write it even cleaner like this:
def removeIdElement(uid: String) =
HAction(uid, "AuthEvent", 1, "login", parse.text).async {implicit request =>
val removeId = request.body.toLong
println(s"remove id $removeId")
for {
_ <- idElementsDAO.remove(removeId, uid.toLong)
} yield NoContent
}
https://www.playframework.com/documentation/2.6.x/ScalaErrorHandling
Here is a simpler version of your code:
class HomeController #Inject()(cc: ControllerComponents)(implicit val config: Configuration)
extends AbstractController(cc) {
def removeIdElement(uid: String) = HAction(uid, "AuthEvent", 1, "login", parse.text).async {
implicit request: Request[String] =>
Future {
val removeId = request.body.toLong
println(s"Removing id $removeId")
removeId
}.flatMap(id => idElementsDAO.remove(id, uid.toLong))
.map(_ => Ok(""))
.recover {
case t: Throwable =>
val errorMessage = getMessageFromThrowable(t)
println(s"Removing id element failed: ${errorMessage}")
BadRequest(errorMessage)
}
}
}
In the above code, a Promise is not needed, and the recover combinator is not repeated.

Async version of AuthenticatedBuilder in play 2

I am trying to compose a basic authentication with some other action:
def findByNameSecure(username: String) = Authenticated { _ =>
val cursor: Cursor[JsObject] = persons.
find(Json.obj("userdetails.username" -> username)).
cursor[JsObject](ReadPreference.primary)
val res = cursor.collect[List]().map { persons =>
Ok(Json.toJson(persons))
} .recover {
case _ => BadRequest(Json.parse("{'error': 'failed to read from db'}"))
}
Await.result(res, 10.seconds)
}
Route:
GET /secure/user/findbyname controllers.UserController.findByNameSecure(username: String)
This works as expected. What is disturbing is that I used Await.result which is blocking. How can I compose an async version of this kind of authentication?
I am using play 2.4.
AuthendicatedBuilder is child of ActionBuilder. So I supposed its async method should work as well.
Example of usage:
def findByNameSecure(username: String) = Authenticated.async { _ =>

ReactiveMongo query returning None

I am just new to learning Scala and the related technologies.I am coming across the problem where the loadUser should return a record but its coming empty.
I am getting the following error:
java.util.NoSuchElementException: None.get
I appreciate this is not ideal Scala, so feel free to suggest me improvements.
class MongoDataAccess extends Actor {
val message = "Hello message"
override def receive: Receive = {
case data: Payload => {
val user: Future[Option[User]] = MongoDataAccess.loadUser(data.deviceId)
val twillioApiAccess = context.actorOf(Props[TwillioApiAccess], "TwillioApiAccess")
user onComplete {
case Failure(exception) => println(exception)
case p: Try[Option[User]] => p match {
case Failure(exception) => println(exception)
case u: Try[Option[User]] => twillioApiAccess ! Action(data, u.get.get.phoneNumber, message)
}
}
}
case _ => println("received unknown message")
}
}
object MongoDataAccess extends MongoDataApi {
def connect(): Future[DefaultDB] = {
// gets an instance of the driver
val driver = new MongoDriver
val connection = driver.connection(List("192.168.99.100:32768"))
// Gets a reference to the database "sensor"
connection.database("sensor")
}
def props = Props(new MongoDataAccess)
def loadUser(deviceId: UUID): Future[Option[User]] = {
println(s"Loading user from the database with device id: $deviceId")
val query = BSONDocument("deviceId" -> deviceId.toString)
// By default, you get a Future[BSONCollection].
val collection: Future[BSONCollection] = connect().map(_.collection("profile"))
collection flatMap { x => x.find(query).one[User] }
}
}
Thanks
There is no guaranty the find-one (.one[T]) matches at least one document in your DB, so you get an Option[T].
Then it's up to you to consider (or not) that having found no document is a failure (or not); e.g.
val u: Future[User] = x.find(query).one[User].flatMap[User] {
case Some(matchingUser) => Future.successful(matchingUser)
case _ => Future.failed(new MySemanticException("No matching user found"))
}
Using .get on Option is a bad idea anyway.

Scala Type Mismatch

I am having a problem with type mismatch.
type mismatch; found : Option[models.User] required: models.User
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user))
)
}
How can I force the function to accept Option[models.User] or can I convert the models.User into an Option?
The error occurs here: User.getUserName(user). getUserName requires models.User types.
===============================================
Update with all code used:
From User.scala
def authenticate(email: String, password: String) : Option[User] = {
(findByEmail(email)).filter { (user => BCrypt.checkpw(password, user.password)) }
}
def findByEmail(email: String) : Option[User] = {
UserDAO.findOne(MongoDBObject("email" -> email))
}
From Application.scala
val signinForm = Form {
mapping(
"email" -> nonEmptyText,
"password" -> text)(User.authenticate)(_.map(user => (user.email, "")))
.verifying("Invalid email or password", result => result.isDefined)
}
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user.get))
)
}
To de-option an Option[User] into a User, you can do one of the following:
1) The unsafe way. Only do this if you are sure that optUser is not None.
val optUser: Option[User] = ...
val user: User = optUser.get
2) The safe way
val optUser: Option[User] = ...
optUser match {
case Some(user) => // do something with user
case None => // do something to handle the absent user
}
3) The monadic safe way
val optUser: Option[User] = ...
optUser.map(user => doSomething(user))
The biggest thing is that, if it's possible that optUser might actually be None, you need to figure out what you actually want to happen in the case that there is no User object.
There's a lot more information about Option in other StackOverflow questions if you'd like to read more.