I have a Grails 2.1.1 application which runs fine, at least until I try to define a filter for all Controller to redirect to the index.gsp if user is not set in the session variable…
what ever I try, I’m not able to redirect to “/index”, nor render “/index” when starting the server – if I remove the filter and redirect to “/index” from my AuthenticationController on false parameters, all works like charm…
so, here’s what I have so far:
class AuthenticationFilters {
all(controller:'*', action'*') {
before = {
def user = (User) session.getValue("user")
if(user == null || !user.loginState) {
redirect(controller: 'authentication', action: 'index')
return false
}
}
}
}
class AuthenticationController {
def authenticationService
def index = {
render(view: '/index')
}
def login(LoginCommand cmd) {
if(cmd.hasErrors()) {
redirect(action: index)
return
}
}
....
}
now, if I comment out the all Filters definition, everything works well. I got the page (index.gsp) shown on start up and if the LoginCommand has errors, I’m redirected to the index.gsp page without any problems.
if I now comment in the all Filters definition, I get a 404.
I tried:
Grails: Redirect to index.gsp that is not in any controller
Upgrade to Grails 2.0: /index.gsp not found
Grails: what are the main issues (and his solutions) when deploying in weblogic?
but I didn’t had any luck…
I’m developing on Intellij IDEA 11.1.4 Premium (evaluation)
EDIT: I tried to get the User object from the session property in my AuthenticationFilters class, surrounded by a try/catch block and now facing the problem that obviously the session property is not available? why?
try {
def user = (User) session.getValue("user")
if((user == null || !user.loginState)) {
...
}
} catch(Exception e) {
println("... couldn't get user from session! ${e.getMessage()}")
}
console output:
... couldn't get user from session! No such property: session for class: grailstest001.AuthenticationFilters
any suggestions on this?
So, just to add my experience here to close this question as solved and for further usage for other users:
to check if the user is entering the page for the first time, you could easily do this by checking for the
controllerNamefield. It should benullor""(empty String) if the user was not referred to the site by any controller.Also, I’m not using any Database within my application for authentication because all of this issuses are backended by an API. So I created a
UserService.groovyclass which is acting as aSessionScopedBeanand I store all my user related infos within this class.So, your filter definition could look like:
Otherwise, if you don’t want to redirect the user which ‘freshly’ entered your page from within your
Filters.groovyclass, you could use theUrlMappings.groovyclass to do so. Just map your/(root) index to the page you want: