33 lines
1.2 KiB
Scala
33 lines
1.2 KiB
Scala
package controllers.devel
|
|
|
|
import dao.UsersDAO
|
|
import play.api.libs.functional.syntax.toFunctionalBuilderOps
|
|
import play.api.libs.json.{JsError, JsPath, Json, Reads}
|
|
import play.api.mvc.*
|
|
|
|
import javax.inject.Inject
|
|
import scala.concurrent.{ExecutionContext, Future}
|
|
|
|
class DevActionsController @Inject()(val controllerComponents: ControllerComponents,
|
|
val usersDAO: UsersDAO)
|
|
(implicit val ec: ExecutionContext)
|
|
extends BaseController {
|
|
|
|
private case class UserData(username: String, password: String)
|
|
private implicit val userDataReads: Reads[UserData] = (
|
|
(JsPath \ "username").read[String] and (JsPath \ "password").read[String]
|
|
)(UserData.apply)
|
|
|
|
def createUser = Action.async(parse.json) { implicit request =>
|
|
request.body.validate[UserData].fold(
|
|
errors => Future.successful(BadRequest(JsError.toJson(errors))),
|
|
userData => usersDAO.create(userData.username, userData.password)
|
|
.map {
|
|
case Left(UsersDAO.UsernameTaken) => BadRequest(Json.obj("error" -> "Username exists"))
|
|
case Left(_ex) => BadRequest(Json.obj("error" -> "User creation error"))
|
|
case Right(user) => Ok(Json.toJson(user))
|
|
}
|
|
)
|
|
}
|
|
}
|