Tuesday, June 14, 2016

Back in Grails World and So Happy (Interceptor)

I have the opportunity to develop some in Grails again and I am just so happy. Just a breath of fresh air.

Had to build a simple token authentication for a restful web service.

Ended up with this code using the Grails 3 Interceptor.
I find it readable, concise and clear. (By the way generated this code below with hilite.me great tool)
package com.webtracker.api.prodcat

import grails.compiler.GrailsCompileStatic
import grails.converters.JSON
import org.apache.catalina.connector.Response

/**
 * This method is expensive as it can be called before every controller
 */
@GrailsCompileStatic
class TokenInterceptor {

    TokenInterceptor() {
        matchAll()
    }

    boolean before() {
        if (params?.apikey) {
            WpActivationKey key = WpActivationKey.findByActivationKey(params?.apikey)
            if (key) {
                true
            } else {
                response.status = Response.SC_FORBIDDEN
                render([errors: ['api key not valid']] as JSON)
                false
            }
        } else {
            response.status = Response.SC_FORBIDDEN
            render([errors: ['no api key specified']] as JSON)
            false
        }
    }

    boolean after() {
        true
    }

    void afterView() {
        // no-op
    }
}

Just remember to make your Domain class cacheable so you do not have to query all the time
@Cacheable("activationKeys")

No comments:

Post a Comment