Thursday, October 1, 2009

Exposing google UserService as a bean in Grails

Here's a how to expose the google's com.google.appengine.api.users.UserService as a bean in your application.

In resources.groovy

beans = {
 userService(com.google.appengine.api.users.UserServiceFactory){
  it.factoryMethod = "getUserService"
 }
}

I use the service in a taglib to expose some useful methods as tags.


class GoogleUserTagLib {
    def userService;
   
    def isUserAdmin = {attrs, body ->
        try{
            if( userService.isUserAdmin() ){
                out << body();
            }
            else{
                out << "NOT ADMIN"
            }
        }
        catch(e){
            out << "";
        }
    }

    def isUserLoggedIn = {attrs, body ->
        try{
            if( userService.isUserLoggedIn() ){
                out << body();
            }
            else{
                out << "";
            }
        }
        catch(e){
            out << "";
        }
    }

    def isUserNotLoggedIn = {attrs, body ->
        try{
            if( !userService.isUserLoggedIn() ){
                out << body();
            }
            else{
                out << "";
            }
        }
        catch(e){
            out << "";
        }
    }

    def loginURL = {attrs, body ->
        def destinationURL = attrs.url;
        def authDomain = attrs.domain ?: null;
        def url = "";

        if(authDomain){
            url = userService.createLoginURL(destinationURL,authDomain);
        }
        else{
            url = userService.createLoginURL(destinationURL);
        }
        out << url;
    }

    def logoutURL = {attrs, body ->
        def destinationURL = attrs.url;
        def authDomain = attrs.authDomain;
        def url = "";

        if(authDomain){
            url = userService.createLogoutURL(destinationURL,authDomain);
        }
        else{
            url = userService.createLogoutURL(destinationURL);
        }
        out << url;
    }
}

so now you can do ‹g:isUserLoggedIn›YOU ARE LOGGED IN‹/g:isUserLoggedIn›

3 comments:

  1. Amazing ! Exactly what I was looking for !
    I'm going to test this right now ! Thanks :-)

    ReplyDelete
  2. Hey! Thanks for putting this out there! I found it, and it was useful.

    ReplyDelete