Pages

Wednesday, April 1, 2015

Grails mail plugin: implementing email validation (part 2)

Continuing the 1st part of email validation.

In my urlmappings the default controller is user:

//"/"(view:"/index")
"/"(controller:"user", action:"index")

Inside the UserController :
def index() {
if(params.id){
Map model = [queueId: params.id]
redirect(controller:'queue', action:'view', params:model)
}
if(params.confirmationCode){
print "email confirmation code: '${params.confirmationCode}'"
Map params = [confirmationCode: params.confirmationCode]
redirect(controller:'user', action:'confirmEmail', params: params)
}

}

When user opens the link from email like www.yourapp.com/?confirmationCode=32irm4oifjij then the flow passes to the confirmEmail action

confirmEmail action:

def confirmEmail(){
def confirmationCode = params.confirmationCode
def decoded = new String(params.confirmationCode.decodeBase64())
def separatorIndex = decoded.indexOf("QQQ")
def userId = decoded.substring(0, separatorIndex).toInteger()
def user = User.findById(userId)
def proceed = true
if(!user){
proceed = false
flash.message = "User not found with such id."
}
if(confirmationCode != user.temp){
proceed = false
flash.message = "Wrong confirmation code!"
}
if(proceed){
user.temp = null
user.emailVerified = true
user.save(flush:true)
flash.message = "Email was successfully verified for user '${user.userName}'."
}
redirect(controller:'user', action:'index')

}
This is a string decoded in base64 format. For my application queit the format was next: [user id]QQQ[confirmation code]

So the decoded string would look like "1QQQ#@FR$G#ESD", while the encoded string looks something like "ferGW$GFHWgweroih6"

The id is used to fetch user from DB. The user table has a "temp" field where i stored the confirmation code when registering and then sending email.

I believe the rest is self explanatory.

No comments:

Post a Comment