Search code examples
scalalift

Lift Authentication


I want to create an authentication route for my Lift Application.

  1. Create a route, for instance www.myapp.com/user/login
  2. I am not using Lift forms/templating. The forms are rendered in JS.
  3. Send a post request with email and password.
  4. Call Lift authentication when that POST request is received.
  5. Use the Users.login(email, password) method to validate the credentials.

Q: How do I tell Lift to authenticate the credentials incoming via /user/login?


Solution

  • This is overly simplistic, but something like this will allow you to create a url that you can post to. The JSON extraction is not very safe, but should give you an idea of how this might work.

    In Boot.scala

    LiftRules.dispatch.append(new RestHelper{
      serve {
        case JsonPost("user" :: "login" :: Nil, (json, _)) =>
          //extract JSON from json object to get username and password
          val userEmail:String = (json \ "username").extract[String]
          val password = (json \ "password").extract[String]
          User.login(userEmail, password) match {
            case Full(r) =>
              User.current(true)
              InMemoryResponse(Array(), Nil, Nil, 200)
            case _ => ForbiddenResponse
          }
      }
    })
    

    In User.scala

    object User {
      object loggedIn extends SessionVar[Boolean](false)
    }
    

    Then you can use if(User.loggedIn.get){ ... } to test if the user is logged in anywhere. This will work for anything added to the stateful dispatch, if you use LiftRules.statelessDispatch the session will not exist.