control not entering in fold() method - scala

i am trying to insert data from form to database but on form submission control does not enter in fold(error, success) method and runs the statement after it and redirects it to other page
this is my controller method
def submitinfo = Action { implicit request =>
signupForm.bindFromRequest().fold(
errors => BadRequest(views.html.signup(errors)),
data => {
println("************enter sucess case *********************")
signupcc.insertData(data.name, data.username, data.email, data.password)
})
println("************Redirecting to sucess page *********************")
Redirect(routes.Application.success)
}
here is my routes file
# Home page
GET / controllers.Application.index
GET /signup controllers.Application.signup
POST /submit controllers.Application.submitinfo
GET /success controllers.Application.success
GET /signin controllers.Application.signin
please tell me what i am doing wrong

Redirect action should be part of sucess case inside fold method:
def submitinfo = Action { implicit request =>
signupForm.bindFromRequest().fold(errors => BadRequest(views.html.signup(errors)),
data => {
println("************enter sucess case *********************")
signupcc.insertData(data.name, data.username, data.email, data.password)
println("************Redirecting to sucess page *********************")
Redirect(routes.Application.success)
})
}

Related

scala akka does not redirect

I have the following backend. If going to the "localhost:8080", the login page is loaded by redirecting from "/" to "login". Login page is loaded. At submitting the login form, the "perform-login" is called. However, for some reason, there is no redirect to "storage" page. Why?
P.S. If requesting the page "storage" manually, it is loaded. The problem is with the redirect from "login" page to "storage" page. Probably, it has something to do with setting the cookies, as this command also has the return type Route.
Scala version: 2.13.6,
Akka HTTP version: 10.2.6
object Backend {
def main(args: Array[String]) = {
implicit val system = ActorSystem(Behaviors.empty, "lowlevel")
// needed for the future map/flatmap in the end
implicit val executionContext: ExecutionContext = system.executionContext
val topLevelRoute: Route =
concat(
pathSingleSlash {
redirect("login", StatusCodes.PermanentRedirect)
},
path("login") {
complete("my login page")
},
path("storage") {
cookie("token") { tokenCookie =>
println("you managed to login, token:" + tokenCookie.value + "ENDLINE")
complete("my storage page")
}
},
path("perform-login") {
formFields("Username", "Password") { (username, password) =>
var isAbleToLogin = database.isUserLoggedIn(username, password)
if (isAbleToLogin == true) {
setCookie(HttpCookie("token", value="ThisIsMyStrongAccessToken")) {
//TODO: debug why does not redirect to main page
redirect("storage", StatusCodes.PermanentRedirect)
}
}
else {
reject(ValidationRejection("bad credentials"))
}
}
},
path(Remaining) { pathRest =>
reject(ValidationRejection("topLevelRoute, unknown path:" + pathRest + "ENDLINE"))
}
)
val binding = Http().newServerAt("localhost", 8080).bind(topLevelRoute)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
binding
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
Solution:
When I was navigating to the "/" page, the redirect to the "/login" page happens due to the "document / redirect" request type (if analysing the network).
But, in case of redirecting from "/login" page to "/storage" page, the request is of type "xhr /redirect" that cannot be done on the server side, i.e. I had to add $(location).attr('href', 'storage') to my jQuery script to make it work.

How to unit test OAuth2BearerToken in route header in akka http

i have a route which needs an access token in its header to grant access to it for that i have this working code
def accessProtectedResource: server.Route =
path("access-protected-resource") {
get {
bearerToken { token =>
token match {
case Some(tokenValue) =>
complete(OK, routeResponseMessage.getResponse(OK.intValue,ServerMessages.AUTH_PASS,JsObject.empty))
case None => reject(AuthorizationFailedRejection)
}
}
}
}
private def bearerToken: Directive1[Option[String]] =
for {
authBearerHeader <- optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken)
xAuthCookie <- optionalCookie("X-Authorization-Token").map(_.map(_.value))
} yield authBearerHeader.orElse(xAuthCookie)
private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
authHeader.collect {
case Authorization(OAuth2BearerToken(token)) => token
}
when i hit the route through postman in the Authorization tab i selected the type to Bearer Token and add the token and send the request and everything works fine now i want to unit test this route
for this i am looking at this
but i am confused how can i add the header in a proper way in my unit test here is my code
"pass route /access-protected-resource" in {
routeResponseMessage.getResponse(OK.intValue, ServerMessages.AUTH_PASS, JsObject.empty)
val originHeader = Authorization(OAuth2BearerToken("accessTokenString"))
Get("http://0.0.0.0:8083/get-user-token") ~> originHeader ~> authenticationController.route ~> check {
}
}
but my route is getting rejected
- pass route /access-protected-resource *** FAILED ***
[info] Request was rejected with rejection MethodRejection(HttpMethod(POST)) (CheckValidUserTokenExistsTest.scala:76)
how to do this correctly ?
How about using addCredential and testing only bearerToken method wrapped with Route.seal like this(https://github.com/ItoYo16u/scala-usage-playground/blob/master/src/test/scala/web/akka/JWTDirectivesSpec.scala)?

Silhouette and mobile application

I've used as example play-silhouette-angular-seed.
Authorization via Satellizer works fine.
When I try to authorize via iOs app I got next error:
com.mohiva.play.silhouette.impl.exceptions.UnexpectedResponseException:
[Silhouette][facebook] Cannot build OAuth2Info because of invalid response format:
List((/access_token,List(ValidationError(List(error.path.missing),WrappedArray()))))
I got an error 400 in this function from OAuth2Provider.scala :
protected def getAccessToken(code: String)(implicit request: RequestHeader): Future[OAuth2Info] = {
httpLayer.url(settings.accessTokenURL).withHeaders(headers: _*).post(Map(
ClientID -> Seq(settings.clientID),
ClientSecret -> Seq(settings.clientSecret),
GrantType -> Seq(AuthorizationCode),
Code -> Seq(code),
RedirectURI -> Seq(resolveCallbackURL(settings.redirectURL))) ++ settings.accessTokenParams.mapValues(Seq(_))).flatMap { response =>
logger.debug("[Silhouette][%s] Access token response: [%s]".format(id, response.body))
Future.from(buildInfo(response))
}
}
This error has been risen because Satellizer for authentication via Facebook send to server an 'authentication code' and Silhouette server use this code to get Facebook 'access token' and create user.
Facebook iOs SDK, instead, obtained 'Access token' and I've tried to send it to server in Json in field 'code' like 'Satellizer.
To resolve this issue I send an 'access token' in Json field named 'access_token' and use next code to authenticate mobile application:
class MobileSocialAuthController #Inject() (
val messagesApi: MessagesApi,
userService: UserService,
authInfoRepository: AuthInfoRepository,
socialProviderRegistry: SocialProviderRegistry,
val env: Environment[User, JWTAuthenticator])
extends Silhouette[User, JWTAuthenticator]
{
def authenticate(provider: String) = UserAwareAction.async(parse.json) {
implicit request =>
provider match {
case "facebook" =>
request.body.asOpt[OAuth2Info] match {
case Some(authInfo) =>
(socialProviderRegistry.get[FacebookProvider](provider) match {
case Some(p: FacebookProvider) =>
for {
profile <-p.retrieveProfile(authInfo)
user <- userService.save(profile)
authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
authenticator <- env.authenticatorService.create(profile.loginInfo)
token <- env.authenticatorService.init(authenticator)
} yield {
env.eventBus.publish(LoginEvent(user, request, request2Messages))
Ok(Json.obj("token" -> token))
}
case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
case e: ProviderException =>
logger.error("Unexpected provider error", e)
Unauthorized(Json.obj("message" -> Messages("could.not.authenticate")))
}
case _ =>
Future(BadRequest(Json.obj(
"message" -> "Bad OAuth2 json.")))
}
case _ =>
Future(BadRequest(Json.obj(
"message" -> "You can use only Facebook account for authentication.")))
}
}
}
As a result, I have a token which I use in ios application to obtain resources.
This happens when the OAuth2Provider gets a response it can't parse, which is, any non-success response. So there can be many reasons for this error, for instance the authorization code is invalid or expired, or you haven't configured the redirect_uri properly (check your Facebook app configuration on the Facebook dev site to set the redirect_uri).
Silhouette does log the response it gets from Facebook which should help you debug what the actual issue is, the log line to look for is in the snippet you provided:
logger.debug("[Silhouette][%s] Access token response:...
So check your logs, there you should see the response from Facebook, likely with an error indicating why they couldn't give you an access_token.

Unable to run a POST action in play framework 2.2

I have a similar problem to this person and I am unsure why.
my post action is called from a form submission and the controller code
def processFreeDoc = UserAwareAction {
implicit request => {
userEmailForm.bindFromRequest.fold(
formWithErrors => {
Logger.error("Error processing the form %s "format formWithErrors.errors)
Redirect(routes.Application.index)
},
data => {
val sessionProduct = getSessionUnProcessedProduct(data.sessionId, data.documentName)
if(sessionProduct != null){
Logger.info("Found")
sessionProduct.updateProcessing(data.emailAddress, data.sessionId)
Redirect(routes.Application.index)
}
else
Logger.info("Nothing found")
Redirect(routes.Application.checkoutFree(data.sessionId))
}
)
}
}
is skipped entirely. There are no errors in the IDE(IDEA) console and the breakpoint at the entry of the method is not reached so none of the log messages are seen.
EDIT :
The relevant route in the routes file - POST /processFreeDoc controllers.Application.processFreeDoc

Scala Play Templates: Reverse routing with HTTP POST

when reverse routing to a GET route, i simply do
Hello
this means theres a GET route to the sayHello function. What if it was POST and needed an attached payload? is the POST implicit? how is the payload data attached?
The HTTP method for the reverse router is derived from your route configuration file.
Here is an example from a route configuration where I have two different requests with the same URL but different HTTP methods pointing to different methods:
GET /login controllers.Application.login
POST /login controllers.Application.authenticate
The login() method in the Application controller simply streams out the HTML form:
def login = Action { implicit request =>
Ok(html.loginForm(loginForm))
}
the authenticate() method however binds the request to a form allowing further processing:
def authenticate = Action { implicit request =>
loginForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.loginForm(formWithErrors)),
user => {
// OTHER CODE HERE
Redirect(routes.Blog.createPost).withSession("user" -> user)
}
)
}
This second method requires a form definition in the controller:
val loginForm = Form(
tuple(
"username" -> text,
"password" -> text
) verifying ("Invalid username or password", result => result match {
case (username, password) => Account.authenticate(username, password).isDefined
})
)
So depending which method you put to the reverse router in your view, that is the HTTP method which will be used for the request.