aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/Authentication.scala
blob: b7ee72494c87a251883972880a06a777e5f4208b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package controllers

import play.api._
import play.api.data._
import play.api.data.Forms._
import play.api.mvc._

import play.api.db.slick._
import play.api.db.slick.Config.driver.simple._
import play.api.Play.current

import scala.concurrent.Future

import models._


case class AuthRequest[A](account: Option[Views.Account] = None, request: Request[A]) extends WrappedRequest(request)

object Auth extends ActionBuilder[AuthRequest] {

  def invokeBlock[A](request: Request[A], block: (AuthRequest[A]) => Future[Result]) = DB.withSession { implicit session =>
    val uuid = request.session.get(Security.username)
    var account: Option[Views.Account] = None

    if (uuid.nonEmpty) {
      val resultSet = Views.Accounts.filter(_.userUuid === uuid).run
      if (resultSet.nonEmpty) {
        account = Some(resultSet.head)
      }
    }

    block(AuthRequest(account, request))
  }

}


case class LoginData(username: String, password: String)

object Authentication extends Controller {

  val loginForm = Form(
    mapping(
      "username" -> nonEmptyText,
      "password" -> nonEmptyText
    )(LoginData.apply)(LoginData.unapply)
      verifying("Log in failed.", fields => fields match {
      case loginData => checkLoginData(loginData.username, loginData.password)
    })
  )

  def checkLoginData(username: String, password: String) = DB.withSession { implicit session =>
    Tables.Users.filter(u => u.username === username && u.userPassword === password).length.run > 0
  }


  def login = Auth { implicit request =>
    if (request.account.isEmpty) {
      Ok(views.html.pages.auth.loginForm(loginForm))
    } else {
      Redirect(routes.Application.index())
    }
  }

  def loginSubmit = Auth { implicit request =>
    DB.withSession { implicit session =>
      loginForm.bindFromRequest.fold(
        formWithErrors => {
          BadRequest(views.html.pages.auth.loginForm(formWithErrors))
        },
        validForm => {
          val userUuid: String = Tables.Users.filter(_.username === validForm.username).map(_.uuid).first.run

          Redirect(routes.Application.index())
            .withSession(Security.username -> userUuid)
            .flashing(("success", "Welcome, valuable user!"))
        }
      )
    }
  }

  def logout = Auth { implicit request =>
    if (request.account.nonEmpty) {
      Redirect(routes.Application.index())
        .withNewSession
        .flashing("success" -> "You are now logged out. Do not go to our competitor's website. Thanks.")
    } else {
      Redirect(routes.Application.index())
    }
  }

}