If you are implementing Forgot password functionality in your web application using Liftweb and you have such a scenario where you have to send redirect URL with unique token in Email , Liftweb with Scala provides a wonderful functionality to handle this .
1) Write a function to send URL with unique token in Email .
def sendLoginToken(user: User): Unit = {
import net.liftweb.util.Mailer._
val token = LoginToken.createForUserId(user.id.is)
val msgTxt =
"""
|Someone requested a link to change your password on the %s website.
|
|If you did not request this, you can safely ignore it. It will expire 48 hours from the time this message was sent.
|
|Follow the link below or copy and paste it into your internet browser.
|
|%s
|
|Thanks,
|%s
""".format(siteName, token.url, sysUsername).stripMargin
sendMail(
From(MongoAuth.systemFancyEmail),
Subject("%s Password Help".format(siteName)),
To(user.fancyEmail),
PlainMailBodyType(msgTxt)
)
}
This function will generate a Unique token url and save unique token in collection.
2) Override handleLoginToken function according to your requirement .
override def handleLoginToken: Box[LiftResponse] = {
var respUrl = indexUrl.toString
S.param("token").flatMap(LoginToken.findByStringId) match {
case Full(at) if (at.expires.isExpired) ⇒ {
S.error("Login token has expired")
at.delete_!
}
case Full(at) ⇒ logUserInFromToken(at.userId.is) match {
case Full(_) ⇒ respUrl = loginTokenAfterUrl.toString
case _ ⇒ S.error("User not found")
}
case _ ⇒ S.error("Login token has expired")
}
Full(RedirectResponse(respUrl))
}
When user would click on URL , he would be redirected to password page . After redirecting , user session would be true and you can get current user . Now ask user for his new password and replace with old password .
Once URL is clicked by user , it would be expired and deleted from login token collection . It can not be used again .






Reblogged this on Agile Mobile Developer.