Skip to content

Commit

Permalink
Completed the forms auth demo.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dave Hrycyszyn committed Dec 7, 2013
1 parent 0a53a82 commit e55d13d
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 32 deletions.
2 changes: 1 addition & 1 deletion 2.2/http/forms-auth-demo/project/build.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ object FormsAuthDemoBuild extends Build {
val Name = "Forms Auth Demo"
val Version = "0.1.0-SNAPSHOT"
val ScalaVersion = "2.10.0"
val ScalatraVersion = "2.2.0"
val ScalatraVersion = "2.2.2"

lazy val project = Project (
"forms-auth-demo",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ import javax.servlet.ServletContext
class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
context.mount(new ProtectedController, "/*")
context.mount(new SessionsController, "/sessions/*")

}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package org.scalatra.example

import org.scalatra._
import scalate.ScalateSupport
import org.slf4j.LoggerFactory

class ProtectedController extends FormsAuthDemoStack with AuthenticationSupport {

val logger = LoggerFactory.getLogger(getClass)

class ProtectedController extends FormsAuthDemoStack {

get("/") {
logger.info("Hitting controller")
requireLogin
<html>
<body>
<h1>Hello, world!</h1>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.scalatra.example

import org.slf4j.LoggerFactory

class SessionsController extends FormsAuthDemoStack with AuthenticationSupport {

val logger = LoggerFactory.getLogger(getClass)


get("/new") {
if (isAuthenticated) redirect("/")

contentType="text/html"
ssp("/sessions/new", "authenticated" -> isAuthenticated)
}

post("/") {
logger.info(("Starting authentication"))
scentry.authenticate()

if (isAuthenticated) {
redirect("/")
}else{
redirect("/sessions/new")
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,28 @@ package org.scalatra.example
import org.scalatra.auth.strategy.{BasicAuthStrategy, BasicAuthSupport}
import org.scalatra.auth.{ScentrySupport, ScentryConfig}
import org.scalatra.{ScalatraBase}
import org.slf4j.LoggerFactory

trait AuthenticationSupport extends ScentrySupport[User] with BasicAuthSupport[User] {
trait AuthenticationSupport extends ScalatraBase with ScentrySupport[User] {
self: ScalatraBase =>

val realm = "Scalatra Basic Auth Example"
val mylogger = LoggerFactory.getLogger(getClass)

protected def fromSession = { case id: String => User("1", "timmy", "password") } // TODO: WTF?
protected def toSession = { case usr: User => usr.id }

protected val scentryConfig = (new ScentryConfig {}).asInstanceOf[ScentryConfiguration]

protected def requireLogin() = {
mylogger.info("requireLogin auth check")
if(!isAuthenticated) {
redirect("/sessions/new")
}
}

override protected def configureScentry = {
scentry.unauthenticated {
// scentry.strategies("Basic").unauthenticated()
scentry.strategies("UserPassword").unauthenticated()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,56 @@ package org.scalatra.example
import org.scalatra.auth.ScentryStrategy

import org.scalatra.{ScalatraBase}
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import org.slf4j.LoggerFactory


/**
* Authentication strategy to authenticate a user from a username (or email) and password combination.
*/
class UserPasswordStrategy(protected val app: ScalatraBase)
class UserPasswordStrategy(protected val app: ScalatraBase)(implicit request: HttpServletRequest, response: HttpServletResponse)
extends ScentryStrategy[User] {

private def login = app.params.get("userName")
private def password = app.params.get("password")

private def remoteAddress = {
val proxied = app.request.getHeader("X-FORWARDED-FOR")
val res = if (proxied != "" ) proxied else app.request.getRemoteAddr
override def name: String = "UserPassword"
val logger = LoggerFactory.getLogger(getClass)

res
}

override def isValid = {
login.isDefined && password.isDefined
private def login = app.params.getOrElse("login", "")
private def password = app.params.getOrElse("password", "")

/***
* Determine whether the strategy should be run for the current request.
*/
override def isValid(implicit request: HttpServletRequest) = {
logger.info("valid???: " + (login != "" && password != "").toString())

login != "" && password != ""
}

/**
* Authenticates a user by validating the username (or email) and password request params.
*/
def authenticate: Option[User] = {
User.login(login.get, password.get) match {
def authenticate()(implicit request: HttpServletRequest, response: HttpServletResponse): Option[User] = {
logger.info("Attempting authentication with UserPasswordStrategy")
User.login(login, password) match {
case None => {
logger.info("None on login")
None
}
case Some(usr) => {
logger.info("Found user on login")

Some(usr)
}
}
}

/**
* What should happen if the user is currently not authenticated?
*/
override def unauthenticated()(implicit request: HttpServletRequest, response: HttpServletResponse) {
app.redirect("/sessions/new")
}

protected def getUserId(user: User): String = user.userIdAsString
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ object User {
User.findByLogin(username) match {
case Some(user) => {
if(username == user.login && password == user.password){
// updateRememberMe(user)
Some(user)
}else{
None
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<%@ val body: String %>
<html>
<body>
<%= unescape(body) %>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<p>Please login</p>

<form action="/sessions" method="post">
<p>
<label>Login:</label>
<input type="text" name="login"/><br>
<label>Password:</label>
<input type="password" name="password"/><br/>
</p>
<p>
<input type="submit">
</p>
</form>

0 comments on commit e55d13d

Please sign in to comment.