Archive for the 'Tech' Category


Discovering your grails application version 0

In many projects around, one of the requisites is that our customer should know what version of the application was running in the environment. The first approach that people reaches is to insert a comment in the HTML source code or some static page that contains this info.

Using grails, we manage our application versions using the set-version grails command as you should know. After creating your grails application, the default version your application assumes is the 0.1. After some development you’re highly recommended on changing this. There is infinite approaches on managing app versions, I really like this one:

grails set-version 20090403-1

That says this is the first (1) version of today (2009 april’s third). After that, whe you create your war, the version will be appended in the war file’s name.

Ok, now that you have your application “versioned”, you can retrieve it with this simple line:

def version = grailsApplication.metadata['app.version']

Simple and useful!!! This will get the grailsApplication reference, that can get this information for you.

Are you following me and reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

[3/25] Building a RSS Reader with Quartz Plugin – Grails Tutorial 4

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

 

Groovy Version: 1.6
Grails Version: 1.1
Plugin Version: 0.4.1-SNAPSHOT
Plugin Docs: http://grails.org/plugin/quartz
Download Resources: source code screencast 1 screencast 2

Hello,

In this tutorial, we’ll talk about the Quartz plugin used to schedule jobs executions in your application. The plugin is build on top of the Quartz Job Scheduler Library from OpenSymphony. OpenSympony is the company that built the WebWork framework, that is now called Struts2 after Apache “aquisition”.

“Scheduling jobs” is very useful in your application to cover background needs. Some tasks you’ll need to execute undercover your application some times (invalidating old users that have not logged for more than 1 month) or even async processes that you’ll have to do if you do not have a JMS infrastructure, for example, sending e-mails to a lot of people.

In our example, we’ll build a simple RSS Reader that will use the quartz plugin to schedule fetchs it will be done in the feeds and insert in the database. Our application will mainly have one domain class called Post (seen in the last tutorial), a Feed domain class to store our feeds and a similar RSS Parser from technorati.  (Yes, I love the RSS format).

Initially, we’ll create the app, install the quartz plugin, create the domain classes and the Feed scaffold structure

grails create-app feedreader
cd feedreader
grails install-plugin quartz
grails create-domain-class Post

We’ll insert the Post domain class code

class Post {
    String title
    String link
    String body
}

We have to create the Feed domain class and its scaffold structure.

grails create-domain-class Feed
class Feed {
    String word
    String url
}

Scaffolding…

grails generate-all Feed

screencast-1
screencast

After this, we’ll create our Technorati Feed Parser from this code above.

class TechnoratiService {
    boolean transactional = false
    def parseAndSave(rss) {
        def rssObj = new XmlSlurper().parse(rss)
        rssObj.channel.item.each {
            def post = new Post(title: it.title.toString(),
                    link: it.link.toString(),
                    body: it.description.toString())
            post.save()
            println "Post [${post}] saved."
        }
    }
}

We’ll run our application using the grails run-app command and insert some feeds. Note that we’ve configured our datasource to use hsqldb storing in the filesystem instead of regular memory setup. 

Note that we have one JobController that Quartz install for us, forget about it, ok? We’ll create our own job after the second screencast.

screencast-2
screencast

Now, we have to understant some quartz properties and commands. 

When we install the quatz plugin, it installs another command for us the grails create-job MyJob, with it we’ll create our FeedParserJob. Note that we use convention over configuration with all jobs having *Job names. 

grails create-job FeedParser

Job classes have to implement the execute() method. This method is the one that Quartz will trigger when it’s time to execute the job. To define when the job it will be executed and what’s the interval between executions, I suggest you read the plugin documentation witch shows N ways to do this. In our example we’ll use a cron expression similar to *N*X OS systems setting our job to execute once in five minutes.

Our cron expression will be like this:  “0 0/5 * * * ?”

Depending on your jobs requisites, it may run concurrently with another instance of it or not. In our case, we’ll not start other job execution if the last on is still running. To prevent this behavior, we can set the concurrent property to false

def concurrent = false

Our job will essentially look for the feeds we’ve inserted on the database, and for each one it will call the Technorati service asking for new Posts. The final source for our job is the one below:

class FeedParserJob {
    def concurrent = false
    def cronExpression = "0 0/5 * * * ?"
    
    def technoratiService

    def execute() {
        def feedList = Feed.findAll()
        for (Feed feed : feedList) {
            println "Reading feed ${feed.word} @ ${feed.url}"
            technoratiService.parseAndSave(feed.url)
        }
    }
}

As you can see in the example above, you can inject any spring bean in your job, just declare it as I did with my TechnoratiService! :) (this is really great!)

That’s it, if you run you application you’ll see that every 5 minutes (minutes 0,5,10,15…) the job will be called and every posts technorati returns will be inserted on your database. Note that in this simple example we did not check if the post had been already inserted in the database before inserting it, this will just grow our database with a lot of instances representing the same post. This can be avoided checking if the post already exists before inserting it  (just check if you have any Post with the same link), but I’ll left this for you!

Before finish this, let’s just improve a little bit our post list view.

 

Tela de posts

 

 

Now, try to enrich its interface, adding some ajax to get only the new posts since the last fech! Maybe you can start from this your new Google Reader killer! :P

Now, let me know, are you using this plugin in your production environment? What for? What kind of jobs you do with it? 

Thanks!

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

 

Next tutorial: [4of25] Jasper Plugin

Past tutorials:
        [2of25] Searchable Plugin
        [1of25] AcegiSecurity Plugin

[2/25] Searchable: Full text indexed search in grails 13

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up to my feed and following me on twitter!

Introduction

Groovy Version: 1.6
Grails Version: 1.1
Plugin Version: 0.5.3
Plugin Docs: http://www.grails.org/plugin/searchable
Download resources: source code screencast

-

Overview

The Searchable Plugin provides integration between Grails and, IMO, one of the most powerful open source libraries that we have. The Apache Lucene Project. I must admit that I’m a Lucene Lover, since my last project where I was leading a technical team for the largest brazilian e-commerce company and fourth worldwide. The project was totally lucene-driven to store everything you see there (yes, no database, believe me!); products, prices, categories, everything. Of course, the integration processes running backstage took all responsibility for update product prices and other stuff. For this project, we also used other important frameworks such as Apache Solr. I recommend you all look into Apache Lucene. It’s the base of the Compass Project, that is the framework that the Searchable Plugin integrates into our app.

All of this will provide us an excellent indexing tool to index our domain classes that will be searchable across our application. Searching in the Lucene index is infinitely lighter and faster than doing a “LIKE” select in any kind of relational database, and that’s why it is so awesome. So, let’s do it!

-

Download and Install

To do this example, we’ll create an application that searches in our posts archive! I’ll not save a lot of fake news articles in our bootstrap (as everybody is used to). I’ll use this tutorial to also show how to read a remote feed/rss! So, I will ask technorati what people are writing about groovy, and we’ll search on this database, I believ that this is a more realistic example :)

We’ll have a simple Post class that has only the post title, link and text, and make it searchable.

Creating the application

grails create-app postsearch
cd postsearch
grails install-plugin searchable
grails create-domain-class Post

This is the Post class

class Post {
    String title
    String link
    String body

    static searchable = true
    static constraints = {
        //constraints...
    }
}

Note that doing this:

static searchable = true

we are telling the searchable plugin that all instances of this domain class have to be indexed so we can search it later.

Take a look, now in action:

screencast

-

Technorati Integration

To get the technorati feed we’ll use to search, I build a simple class that will get the search results feed and iterate over the results and save one post for each entry. On technorati, I’ll search the following words: groovy, grails, java, griffon, springsource, g2one, acegi, groovyws, and codehaus. This will give us approximately 200 posts. I’ll create a simple controller that will just do this.

grails create-controller technorati

and this is its content

class TechnoratiController {
    def index = {
        def totalPosts = 0
        def wordList = ['groovy', 'grails', 'java', 'griffon', 'springsource',
                'g2one', 'acegi', 'groovyws', 'codehaus'].each() { word ->
            def rss = "http://feeds.technorati.com/search/${word}"
            def rssObj = new XmlSlurper().parse(rss)
            rssObj.channel.item.each { item ->
                def post = new Post(title: item.title.toString(),
                        link: item.link.toString(),
                        body: item.description.toString())
                if (post.save())
                    totalPosts++
            }
        }
        render "${totalPosts} posts indexed"
    }
}

Maybe we can turn this into a plugin later! :) That’s it, no view for it, we just need to request it to feed our database.

-

Searching with SearchController

After this you can go to the SearchableController that is installed in our application:

http://localhost:8080/postsearch/searchable

Try searching for “grails” or any other word that may have been in our technorati posts.

Note that this view uses the toString() method, so lets beautify it.

String toString() {
    return "${title}: ${body}"
}

SearchController screen

-

Changing the way fields are indexed

Our Post class is indexed using the default configuration for the Searchable plugin and that’s not the best way since the post URL is indexed as well and currently has the same relevance as its title (this is wrong, believe me). IMO, the link should not be indexed, just the title and the text of the post, and the title is much more important that its description.

To do this, we’ll use some plugin options. This plugin has A LOT of options, (it deserves a book of it, really), and all the options are described here. I strongly recommend you to read this if you use this plugin in your production environment.

Here we’ll just stick to the basics, we’ll exclude some properties being indexed and boost one field (title) that is more important. This means that when you search for “grails”, posts with “grails” in the title will come with a higher score than posts with “grails” only in the body of it.

Excluding link from being indexed

This is easy! We’ll change the static searchable = true for this one with the ‘except’ property.

static searchable = {
    except = ['link']
}

That’s it, no link will be indexed anymore. It’s recommended to index ONLY properties you really ‘ll need, otherwise your lucene index can grow to be quite large.

Boosting the title

This is easier (I don’t remember anything difficult using grails) than the last one, we’ll add the property boost to our title, and this is the final mapping closure:

static searchable = {
    except = ['link']
    title boost: 2.0
}

This will give our searches what we really want.

-

Searching – Domain classes

After installed, the plugins offer us (for domain classes marked as searchable) some methods that will search on the index. Here I’ll explain some of the most important ones.

search

The main method of this plugin. Will search across all instances of this domain class for the requested string (and options)

def postsListSeachResult = Post.search("grails")
def postsListOrderedSearchResult = Post.search("grails", [sort: 'title'])

Remember that ordering searches is not a good idea since you will lose all effective relevance-based scoring that lucene gives to each hit entry.

countHits

This method returns just the number of hits that your query retrieved in the index, useful to know how many entries will be returned if the search method was used instead. You can use as search method.

[groovy]def postsListSeachResultCount = Post.countHits("grails")
def postsListOrderedSearchResultCount = Post.countHits("grails", [sort: 'title'])

moreLikeThis and suggestQuery

“moreLikeThis” and “suggestQuery” (aka spell checking) can be done easily with Seachable Plugin, all you have to do is set these properties to the mapping closure.

Take a look here and here for more information.

-

Conclusion

This plugin is one of my favorites. If you’re planning a grails website in a production environment, this one will be your friend.

Ohh remember that this plugin is much more powerful than shown here, most configuration options available for Compass and Lucene have not been demonstrated here. This is just a small part of it!

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up my feed and following me on twitter!

Last Tutorial:  [1/25] Acegi: Secure your grails application with no pain

Next Tutorial: [3/25] Quartz: Easy job scheduling plugin.

My TinyUrl plugin released! 2

Hi,

This is the first plugin I release on my own. This is very very simple, and the main reason to do this, is actually to learn how to deal with your own grails plugins.

It’s called TinyUrl plugin and provides a to your application a service to integrate with TinyUrl URL shrinker website, It’s simple to user, and I recommend to everyone that sends URLs through twitter or other services. Imagine after you insert a post into your blog, you’ll twitter it:

Inject the service

def tinyurlService

and in your action:

def post = new Post(params)
//save your post

def newUrl = tinyurlService.tiny(post.link)

//set your twitter status
twitter.post("I've just posted about ${post.title} right here: ${newUrl}")

That’s it!, visit its page: http://www.grails.org/plugin/TinyUrl

Are you reading my blog’s feed? Be the first to know when I publish some interesting article signing up my feed and following me on twitter!

Thanks!

IP restriction in specific actions with AcegiSecurity 2

Hi,

Need to make one specific controller/action visible just to one IP? That’s easy using another Acegi configuration option in your SecurityConfig. You can use this to restrict the acess for some intranet part of your application, this is really easy and useful! Try adding this in your <app>/grails-app/conf/SecurityConfig.groovy

ipRestrictions = ['/admin/**': '127.0.0.1',
'/myController/myAction': '10.**']

This will make the first all actions in admin controller (or any other thing mapped with this pattern) accessable only from the machine that is running the application, and “myAction” of “myController” accessable from any ip starting with 10.

Remeber… As the documentation says, ALL ACTIONS can be accesses from localhost (the example I said above), no matter what you do in your mappings.

:)

[1/25] Acegi: Secure your grails application with no pain 36

Groovy Version: 1.6
Grails Version: 1.1
Plugin Version: 0.5.1
Plugin Docs: http://grails.org/plugin/acegi
Tutorial resources: Download here

Tutorial topics

  1. Overview
  2. Download and install
  3. Domain classes
  4. Permissions Management
  5. Storing permissions outside the database
  6. User self registration
  7. Taglib and service
  8. Acegi events
  9. Conclusion

I have to thank a lot Rob James that helped me a lot in correcting some english issues and clarifying some things in my head. Specially in the Roles/Authentication part, witch was rewrited by him.

Overview

The Acegi Security plugin provides an easy way to work with Spring Sercurity. I really like this plugin ’cause after it is installed, it is ready to be used. Offering user authentication, registration and management out-of-the box. I’m using this plugin in some of my projects and for what I need, it’s awesome. Here are some of the features I really like in it:

  • User management
  • Online permissions (roles x uri) management when storing in a database (you can also store this in the config file)
  • A simple registration screen, protected with a simple captcha and support for mailing user’s their credentials
  • Login/logout with no pain
  • Quick OpenID and LDAP integration
  • User-chosen domain class names
  • Simple taglib and service class for integration your application

.

Download and install

To install the Acegi Security plugin, we’ll create a simple app called “tutorials” in witch I’ll start the plugin tutorials.

grails create-app tutorials

As any other plugin, we can choose from a remote install where the files will be fetched from the official grails plugins repository (http://plugins.grails.org) or from a local install, where you can install from a local zip file. I’ll demonstrate both.

Remote install

grails install-plugin acegi

The main advantage on getting it from the remote repository is that you’ll always get the latest plugin version.

Local install

grails install-plugin /Users/lucastex/grails/plugins/acegi/grails-acegi-0.5.1.zip

I like installing the plugins from my local repository because I’m not online all the time, sometimes I’m behind a nasty proxy and this way I can have previous versions of the plugin in case I need to get to them. Since plugin zip files are really tiny, I recommend you storing it in some old usb flash memory or in any webdav drive over the cloud… :)

After installing it, you’ll get all dependencies you need for using the plugin features (except for the mail.jar and activation.jar that will be downloaded only when needed).

The process is shown here:

thumb

Domain Classes

Authentication and Authorization firstly involves understanding some important concepts.

Who can do what?

A “User” in Acegi is a login, which represents an individual person. This User will log into your application, and will consequently have certain functions that they can perform. With Acegi, you are firstly permitting users access to your application (Authentication) and secondly determining if they can perform a certain function (Authorization).

If we were to try and map this to the physical world, you could draw an analogy with how people work in an organisation. In your company, people are “Authenticated” to get into the building with an Identification card. It confirms that the person is who they claim to be. With Acegi, we generally do this with a Username and Password (although this the main way to authenticate in Acegi, there are actual many different ways of doing this).

Once in the building, they may be “Authorized” to do certain things. These authorizations prevent the Mailroom Clerk from signing off on a $1 billion project that the CEO must do. And therefore the Mailroom Clerk may be “authorized” to do or access less things than the CEO is.

In Acegi, we do this by assigning users to certain “Roles”. Roles can be confusing at times, because they are actually quite flexible. In its simplest form, you can create Roles that represent real world Roles, such as Admin, Developer, Clerk, Manager. Then in your application, you can test if the Authorized user has that role before allowing them to perform a certain function.

A more powerful model is to break down the “functions” they can perform as roles. This will allow for more flexibility in the long term. For example, all your users may have basic access to information, but only Admins, Managers and Developers have access to Documents, and Managers and Admins can modify this information, and finally Admins will be the only role that can create users. So you can create Roles in Acegi like, “PROJECT_ACCESS”, “USER_ACCESS”, “USER_WRITE” etc.

The power in doing this, is that you can have users (individuals) sharing responsibilities without changing a line of code. So you can decide that Developers can now modify documents, and just assign them that Role.

The process of “Assigning” Roles (the Authorities) to Users (the Authentication) is done through the RequestMap entity (default by the AcegiSerurity).

With these fresh concepts, we can now create these entities inside our application using one command the plugin installed for us, the “create-auth-class” command. The command itself creates all the 3 classes we need, but we’ll pass the names of the Domain objects we want each class to have as arguments. The regular usage for it is:

grails create-auth-domains &lt;person class name&gt; &lt;authority class name&gt; &lt;request map class name&gt;

And our command consists of:

grails create-auth-domains User Role RequestMap

After this, we get some new files in the project:

Login user domain class: User
Authority domain class: Role
Requestmap domain class: RequestMap
file generated at /home/lucastex/Desktop/grails/tutorials/grails-app/domain/User.groovy
file generated at /home/lucastex/Desktop/grails/tutorials/grails-app/domain/Role.groovy
file generated at /home/lucastex/Desktop/grails/tutorials/grails-app/domain/RequestMap.groovy
file generated at /home/lucastex/Desktop/grails/tutorials/grails-app/conf/SecurityConfig.groovy
copying login.gsp and Login/Logout Controller example.
[mkdir] Created dir: /home/lucastex/Desktop/grails/tutorials/grails-app/views/login
[copy] Copying 1 file to /home/lucastex/Desktop/grails/tutorials/grails-app/views/login
[copy] Copying 1 file to /home/lucastex/Desktop/grails/tutorials/grails-app/views/login
[copy] Copying 1 file to /home/lucastex/Desktop/grails/tutorials/grails-app/views/login
[copy] Copying 1 file to /home/lucastex/Desktop/grails/tutorials/grails-app/controllers
[copy] Copying 1 file to /home/lucastex/Desktop/grails/tutorials/grails-app/controllers

If we run the application, we’ll notice that we have one logincontroller and one logoutcontroller, they are ready to be used and all we have to do is setup one user in the database. Due to the laziness that is consuming me right now, to create and manage the users, we’ll run the second command the plugin gives us.

grails generate-manager

After running it, we’ll have more controllers (that manage the users, roles and requestmaps) and all the necessary views.
Using the new controllers, we’ll add two new roles, one admin user (god) and one other user with simple user privileges (slave).

That’s it, you can now use the login and logout controller to test the process!

thumb

Permissions Management

Keep in mind that securing URLs is not easy. You have to think what actions are linked with what “flows” in your web app and draw from the permission graphs, linking profiles (roles) with actions. Be calm, after the first one, you’ll be the master of roles.
You’ll use the RequestMapController to do this. Access this screen by clicking on the RequestMapController link and take a look at your options. In the field labeled as “URL”, you’ll enter the URL you want to secure, and below it, you’ll enter the roles you want to grant access to it, for example, in our app, we’ll restrict the user creation process, so only admin users logged should create users.

URL: /user/create
Roles: ROLE_ADMIN

Doing this, only admins will have access to create new users in the app.

And we’ll let any logged in user list users, but non-logged users won’t do this:

URL: /user/list
Roles: ROLE_ADMIN, ROLE_USER

Take a look in this quick presentation, showing the users trying to log and execute the actions. Note that the “safari” user will be the admin user, and the “firefox” user will be the regular user. And note that the rest of actions/controllers (RoleController, RequestMapController) are not affected.

thumb

That’s it! As this tutorial is using the in-memory database grails offer us, let’s edit our BootStrap.groovy file so we can load some sample data (so that we don’t have to manually keep doing this). Note that I’ll secure other actions here as well.

Adding Roles:

//Adding Roles
def roleAdmin = new Role(authority:'ROLE_ADMIN', description:'App admin').save()
def roleUser  = new Role(authority:'ROLE_USER', description:'App user').save()

Adding Users:

http://snipplr.com/view/13209/adding-users-to-bootstrapgroovy/

Adding Permissions:

//Adding Users
def userGod = new User( username:'god',
userRealName:'god almighty',
enabled: true,
emailShow: true,
email: 'god@grailsapp.com',
passwd: authenticateService.encodePassword('god')).save()

def userSlave = new User(username:'slave',
userRealName:'poor slave',
enabled: true,
emailShow: true,
email: 'slave@grailsapp.com',
passwd: authenticateService.encodePassword('slave')).save()

Final Bootstrap.groovy:

class BootStrap {

def authenticateService

def init = { servletContext -&gt;

//Adding Roles
def roleAdmin = new Role(authority:'ROLE_ADMIN', description:'App admin').save()
def roleUser  = new Role(authority:'ROLE_USER', description:'App user').save()

//Adding Users
def userGod = new User(username:'god',
userRealName:'god almighty',
enabled: true,
emailShow: true,
email: 'god@grailsapp.com',
passwd: authenticateService.encodePassword('god')).save()

def userSlave = new User(    username:'slave',
userRealName:'poor slave',
enabled: true,
emailShow: true,
email: 'slave@grailsapp.com',
passwd: authenticateService.encodePassword('slave')).save()

def secureUserEdit = new RequestMap(url: '/user/edit', configAttribute:'ROLE_ADMIN').save()
def secureUserSave = new RequestMap(url: '/user/save', configAttribute:'ROLE_ADMIN').save()
def secureUserCreate = new RequestMap(url: '/user/create', configAttribute:'ROLE_ADMIN').save()

def secureUserList = new RequestMap(url: '/user/list', configAttribute:'ROLE_ADMIN, ROLE_USER').save()

//Note that here we associate users with their respective roles
roleAdmin.addToPeople(userGod)
roleUser.addToPeople(userGod)
roleUser.addToPeople(userSlave)

}
def destroy = {
}
}

Storing permissions outside the database

Depending on your application needs, it may be better to store all permissions (requestmaps) outside the database. It’s up to you.

database

* Pros: You can change permissions on the fly! new permissions to old roles can be assigned in the RequestMap Domain we’ve created and after its added, it s working without a restart of the application.
* Cons: All requests will have to search for the requestmap permissions inside its objects. Upgrading these objects to memory will cost in database round trips, but won’t be terrible.

securityconfig

* Pros: It’s faster! If your site relies on performance and you don’t expect dynamically having to secure new URLs at runtime, this is for you :P
* Cons: You will have to restart your applications when the permissions changes.

If permissions don’t change often, I strongly recommend you store all permissions outside the database, but remember.. It’s up to you and what your application needs! :)

Let’s take our tutorials app and change the permissions mapping to the static method. First of all, I’ll comment the lines on our BootStrap to not insert the permissions we did, and then, open the tutorials/grails-app/conf/SecurityConfig.groovy file. We’ll see:

security {

// see DefaultSecurityConfig.groovy for all settable/overridable properties

active = true

loginUserDomainClass = "User"
authorityDomainClass = "Role"
requestMapClass = "RequestMap"
}

Three important points:

* Note that our domain class names are written there, so please DO NOT change this. This will mess up with your application :P
* The DefaultSecurityConfig.groovy defines everything in Acegi’s behavior, so take a look in this file, it’s important to understand what can be done! :P
* Read this doc where all is explained about what you’ll find inside the DefaultSecurityConfig.groovy

Now, we’ll add the same permissions we’ve added before using the BootStrap, but this time in the DefaultSecurityConfig.groovy file. In a string called requestMapString, set the variable useRequestMapDomainClass to false, so the application will not use the domain class we’ve created. Pay attention to the simple syntax, using URL=ROLE1,ROLE2,….

All these changes result in this SecurityConfig.groovy

security {

// see DefaultSecurityConfig.groovy for all settable/overridable properties

active = true

loginUserDomainClass = "User"
authorityDomainClass = "Role"
requestMapClass = "RequestMap"

useRequestMapDomainClass = false

requestMapString = """
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/user/create=ROLE_ADMIN
/user/edit=ROLE_ADMIN
/user/save=ROLE_ADMIN
/user/list=ROLE_ADMIN, ROLE_USER
"""
}

User self registration

The acegi plugin also gives us another command-line tool, that auto-generate a simple registration screen that you can use for visitors to register themselves in your app. It’s a simple form, with password confirmation and even a simple captcha! I’m using it in my own project and it works great. To generate this, all you have to do is run this command line inside your grails application:

grails generate-registration

Now run your application using the run-app command and you’ll see all the existing controllers as well as a brand new one, called RegisterController. This handle’s the user registration.

You can also send confirmation e-mails to users. But I won’t cover this on this tutorial. I’ll leave this to the Mail Plugin.

Important trick: It’s not correct to any user in your application to not have any roles, so you have to define one “DEFAULT ROLE” for self registrations. You can do this in the SecurityConfig.groovy, like this:

security.defaultRole = "USER_ROLE"

Taglib and service

Ok, I have a secured application, user can register and the roles are defined, but how will I integrate my existing application with all this new stuff? The Acegi Security plugin also installs two interesting resources in your application:

AuthenticateService

This service can be injected inside your application, such as your controllers and services. It provides access to the logged in user information that may be needed when, for example, your application need to log which user is logged in and posting articles!

You can inject the service like any other service you’ve created, and you may retrieve information about the user (IMO, the most important is explained here).
Logged in User’s principal: calling the method “principal()” on the service, will return you the Principal object that can give you the username and the authorities of the user.
I’ll show a simple snippet of an action using it:

def authenticateService

def debugPrincipal = {
def userPrincipal = authenticateService.principal()
println userPrincipal.getUsername() //shows the current logged user username
println userPrincipal.getAuthorities() //shows the current logged user authorities
redirect action: list, params: params
}

Just REMEMBER; If no one is logged in, the method will return the String “anonymousUser”. Be careful when trying to get the username from this String, you will get an exception.

AuthorizeTaglib

This is the taglib that you’ll use on your GSPs to interact with the plugin.

* isLoggedIn – restrict access to content within this tag to logged in users only
* isNotLoggedIn – restrict access to content within this tag to non-logged in users only
* loggedInUserInfo -this will give you information about the logged in user domain class, you pass the property name and it returns it’s value.
* ifAllGranted – restrict access to content within this tag only if the logged user have ALL THE ROLES passed to the taglib
* ifAnyGranted – restrict access to content within this tag only the logged in user has ANY of the ROLES that was passed to the taglib.
* ifNonGranted – (I think you got it!) Only will show the content if the user DOES NOT have any of these roles

&lt;g:isLoggedIn&gt;
Only logged users (no matter witch roles) will see this text. This is useful to build the "Welcome ..." text and the logout link!
&lt;/g:isLoggedIn&gt;

&lt;g:isNotLoggedIn&gt;
Only anonymous users will see this. This is nice to build your "login" or "registration" link!
&lt;/g:isNotLoggedIn&gt;

&lt;!-- Let's pretend we are logged as our 'god' user --&gt;
&lt;g:loggedInUserInfo field="username"/&gt; &lt;!-- will show 'god' --&gt;
&lt;g:loggedInUserInfo field="email"/&gt; &lt;!-- will show 'god@grailsapp.com' --&gt;
&lt;g:loggedInUserInfo field="userRealName"/&gt; &lt;!-- will show 'god almighty' --&gt;

&lt;g:ifAllGranted role="ROLE_ADMIN,ROLE_USER"&gt;
This information will be available for admins whom have the ROLE_USER associated either.
&lt;/g:ifAllGranted&gt;

&lt;g:ifAnyGranted role="ROLE_ADMIN,ROLE_USER"&gt;
This information will be available for any logged admin or user.
&lt;/g:ifAnyGranted&gt;

&lt;g:ifNotGranted role="ROLE_ADMIN"&gt;
All sessions that have the ROLE_ADMIN associated will not see this message!
&lt;/g:ifNotGranted&gt;

Acegi events

Let’s imagine you need to log every successful or unsuccessful user login in your system, or any other event that Acegi listens to. This can be done by building your own listener class that implements the ApplicationListener class. Implementing this interface will force you to define the onApplicationEvent method that will receive an ApplicationEvent instance.

Remember swing onClicks button events? This works in a similar way, you’ll have to check the class of the event using the “instanceof” and choose what events you’ll log, and what you won’t.

Here’s an example, logging any user login on our application, we’ll define this simple class:

import org.springframework.context.*
import org.springframework.security.event.authentication.*
import org.springframework.security.event.authorization.AbstractAuthorizationEvent

class AcegiEventListener implements ApplicationListener {

void onApplicationEvent(final ApplicationEvent e) {

if (e instanceof AbstractAuthenticationEvent) {

if (e instanceof AuthenticationSuccessEvent) {

println "** Attention: User ${e.source.principal.username} is logged!"
}
}
}
}

After this, we still have to register our class in the spring beans groovy file, so the application can find it (IMO, this should happen automatically with files ending in “ApplicationListener” as it happens with filters :P what do you think?).

beans = {

acegiEventListener(AcegiEventListener) {}

}

Conclusion

That’s it folks, a simple tutorial that shows how bad our world would be if we had to implement all this by ourselves. I love grails plugins and think without it all, grails development would be horible.

Acegi is one of the most complete plugins we have, and I really like it. This tutorial is much longer than I planned (and the others that will come), but I removed too much stuff I didn’t have time to write. Maybe I’ll do it other posts.

Thank you for reading this, and please spread it out!

Next tutorial will be about the Searchable Plugin

Want to be informed on blog news? Sign up for our feed and follow me on twitter!

Poll results. Check it out! 2

Hi,

Just closed the poll, got a lot of work to do :P   Here are the results.

* Acegi Security Plugin (66,0%, 221 Votes)
* Searchable Plugin (45,0%, 150 Votes)
* Quartz Plugin (37,0%, 125 Votes)
* Jasper Plugin (35,0%, 118 Votes)
* Mail Plug-in (32,0%, 106 Votes)
* Axis2 Plugin (26,0%, 88 Votes)
* Shopping Cart Plugin (23,0%, 77 Votes)
* Google Chart Plugin (22,0%, 75 Votes)
* OpenId Plugin (22,0%, 74 Votes)
* Calendar Plugin (22,0%, 74 Votes)
* RichUI-Autocomplete (20,0%, 67 Votes)
* Taggable Plugin (18,0%, 61 Votes)
* Feeds Plugin (18,0%, 60 Votes)
* Tooltip Plugin (16,0%, 54 Votes)
* RichUI-RichTextEditor (16,0%, 54 Votes)
* Captcha Plugin (16,0%, 54 Votes)
* RichUI-DateChooser (14,0%, 48 Votes)
* SyntaxHighlighter (13,0%, 45 Votes)
* Commentable Plugin (13,0%, 43 Votes)
* FilterPane Plugin (12,0%, 40 Votes)
* Twitter Plugin (12,0%, 39 Votes)
* RichUI-Tag Cloud (10,0%, 32 Votes)
* RichUI-Star Rating (8,0%, 27 Votes)
* ModalBox Plugin (8,0%, 27 Votes)
* Avatar Plugin (5,0%, 18 Votes)

So, the first one will be the AcegiSecurity plugin, I’ll start it today, willing to publish this thursday. hope so.

One thing is important to know, these tutorials are not the best one over the web, and just represent MY OWN EXPERIENCE using it!  Suggestions are always accepted!

Thank you everybody that is supporting this mini-project over twitter, comments and e-mail. Thank you :)

Why don’t you sign for the blog’s feed or follow me on twitter? :) Stay tuned!

About the plugins poll. 0

I’ll let the poll open till monday or tuesday since I’ll travel on this weekend. 

But I’ll start working in Acegi’s one…

 

Hope next thursday it can go live! :)

 

You may like to sign for the blog’s RSS feed here, and follow me on twitter here.

25 Grails Plugins tutorials. Vote for your favorites! 28

Hey,

I’m shocked. I’ve posted the other entry about 10 grails plugins that I recommend and posted one link at the Grails.org site (link here) and by blog jumped over 6000% on visitors. That is awesome and motivated me to write about plugins. Not only the 10 I wrote, but some others that people commented and others I found at the Grails Wiki Plugins Page.

So, I created a poll in the blog (in the right column) and I’ll write for every plugins listed there. Please, vote on the 10 (or less) plugins you want me to write and I’ll write first on the most voted. I think will take some time to write for all plugins, but I’ll do this nicely, I promisse!

For each plugin I write, I’ll talk a little about how it works, make some examples (I’ll try some screencasts) and upload to the blog files the example applications.

Thanks for coming, I’ll write mainly in english from now on, but as I said before, comments in any language are welcome.

You may like to sign for the blog’s RSS feed here, and follow me on twitter here.

Another groovier way to access some itens in my list. 0

Hello,

Yesterday I’ve posted this post: Uma maneira bem ‘a-lá groovy’ de se acessar o último elemento de uma lista! (English version here) that explains how we can use negative indexes to access the elements on one list using groovy. And a friend of mine, Paulo Suzart, that works with me commented that using Scala he can have some extra calls one one list.

lista.head //first element
lista.last //last element
lista.tail //all elements except the first one

I myself do not know scala well, ( except for the times he keeps talking about it! LOL). But this comments submitted me to my textmate to explore the list methods, and I got surprised when I saw all that methods exactly reproduced in groovy. My mistake that I did not posted this way in yesterday’s post, but here it is:

def lista = []
lista << “first element”
lista << “second element”
lista << “third element”

println lista.head() //”first element”
println lista.last() //”third element”
println lista.tail() //gives me another list, formed by “second element” and “third element”

That’s it! Hope it helps.

You can follow me on twitter: twitter.com/lucastex

« Previous PageNext Page »

Web Analytics