views:

247

answers:

4

I'm writing a small webapp in Grails and I have the following question regarding best practices for controller design and using GORM:

I'm storing the user object in session.user. Currently all my action methods start with the following code to make sure a valid user is logged in and that the user object is fresh:

class FooController {
  def actionMethodThatRequiresAValidUser = {
    if (!session?.user) {
      redirect(controller: "authentication", action: "login")
    }
    session.user.refresh()
    ...
    /* do stuff */
    ...
  }
}

Is that best practice? Can it be done in a better and/or more concise way?

+6  A: 

Use a filter, that way you can put that same repeated code in the filter and keep your controllers focussed on the real action.

Bart Schuller
+1  A: 

You might try defining this as a filter rather than duplicating code.

Joe Soul-bringer
+1  A: 

I agree with the filter suggestions others have made. If that doesn't work for you, you could define a beforeInterceptor on your controller to minimize some duplication as well.

Rob Hruska
+3  A: 

I think using beforeInterceptor is appropriate.And give some look at this JSecurity plugin.For user authentication jsecurity plugin is very useful.

BlackPanther