/
UserAuthServlet.scala
62 lines (48 loc) · 1.47 KB
/
UserAuthServlet.scala
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
package scalatrashiro
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc._
import org.scalatra.{FlashMapSupport, ScalatraServlet}
/**
* Created by sam on 22/05/15.
*/
class UserAuthServlet(val afterAction: String, val loginUrl: String) extends ScalatraServlet with FlashMapSupport {
post("/login") {
val username = params.getOrElse("username", "")
val password = params.getOrElse("password", "")
val currentUser = SecurityUtils.getSubject()
try {
val token = new UsernamePasswordToken(username, password)
token.setRememberMe(false)
currentUser.login(token)
this.flash("success") = "Logged in successfuly."
redirect(afterAction)
} catch {
case uae: UnknownAccountException => {
this.flash("error") = "Account not found."
redirect(loginUrl)
}
case ice: IncorrectCredentialsException => {
this.flash("error") = "Invalid username password combination."
redirect(loginUrl)
}
case lae: LockedAccountException => {
this.flash("error") = "Account is locked."
redirect(loginUrl)
}
case ae: AuthenticationException => {
throw ae
}
}
}
get("/logout") {
val subject = SecurityUtils.getSubject
if (!subject.isAuthenticated) redirect("/login")
try {
subject.logout()
flash("success") = "Logged out successfuly."
redirect(afterAction)
} catch {
case e: Exception => throw e
}
}
}