Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the user is logged in (in the GSP)

I have index.gsp that presents a page. In that page there is a button to register, and a button to log in. Once you have logged in, if the login is ok, the app drives you again to index.gsp. I need that, if the user is logged in, these buttons disappear, and instead say "Hello, [username]". I've tried with this code, but it doesn't work (it is never logged in):

In the Controller:

def dologin(){

    def user=Usuario.findByUsernameAndPassword(params.username,springSecurityService.encodePassword(params.password) )

    if(user){
        redirect (controller:'usuario', action:'index')
    }else{

        flash.message=message(code:'default.user.not.found', args:[message(code: 'params.username', default:'Usuario'), params.id])
    def userlogged = springSecurityService.getCurrentUser()
                render view: 'index', model: [user: user]
}

}

In index.gsp (is not full, only the piece that matters):

<sec:ifNotLoggedIn>

<div id="buttons">
    <div id="login"><a href="loginurl">Login</a>
    </div>
    <div id="register"><a href="registerurl">Registrarse</a>
    </div>
</div>
</sec:ifNotLoggedIn>
<sec:ifLoggedIn>

<div id="greet">Hello!</div> 

</sec:ifLoggedIn>

Any help would be appreciated.

Thank you.

like image 309
Fustigador Avatar asked Jul 19 '12 14:07

Fustigador


2 Answers

It looks like you're doing your own authentication, rather than going through the spring security authentication process. The <sec:ifLoggedIn> tag relies on spring security handling the authentication.

The usual way this is handled in a spring security app is by posting the login request to /j_spring_security_check, which, behind the scenes, gets filtered by a UsernamePasswordAuthenticationFilter.

Grails and the spring security plugin make this relatively painless by providing a LoginController and auth.gsp that you can use as a starting point. Run the s2-quickstart script (which also creates User and Role domain objects), or just copy them from the spring-security-core templates directory.

like image 165
ataylor Avatar answered Nov 07 '22 21:11

ataylor


I tried it simply

<sec:ifNotLoggedIn> // DO SOMTHING</sec:ifNotLoggedIn>
<sec:ifLoggedIn> // DO SOMTHING</sec:ifNotLoggedIn>
like image 1
asroboy Avatar answered Nov 07 '22 19:11

asroboy