views:

520

answers:

2

This code get's the currently logged in user, using the Spring Security Plugin (acegi):

def principalInfo = authenticateService.principal()
def person = null
if (principalInfo != "anonymousUser" && principalInfo.username) {
    person = Person.findByUsername(principalInfo.username)
}

I would then like to do:

session.user = person

This needs to be done after the user logs in. I can't figure out where to put my code to do this. It seem like it should be some place in the Login Controller, but I can't see where.

A: 

Why do you want to do this? The person is already attached to the principal which is in the session. Call authenticateService.userDomain() to access it.

Burt Beckwith
That almost works, but if you access any related property if fails, e.g. If I doperson = authenticateService.userDomain() company = person.companyI get a LazyInitializationException. Might that be why people have used code like I have above?Is this where I need a custom userDetailsService? Or would setting eager fetching on solve the problem?
Brad Rhoads
You could use eager fetching but it's wasteful if you only need it for this use case. To avoid LIEs you can either re-attach the instance (def person = authenticateService.userDomain(); person.attach()) or reload it by id (def person = Person.get(authenticateService.userDomain().id)). This is preferable to eager loading since you can do this only when you know it'll be needed - if you just need String, boolean, or numeric properties then there's no need to reattach or reload.
Burt Beckwith
person.attach() gave me a NonUniqueObjectException but def person = Person.get(authenticateService.userDomain().id) works.Thanks!
Brad Rhoads
A: 

Spring does not set a user object directly in the session. However they put a SPRING_SECURITY_CONTEXT object in the session. This contains the authenticated user.

The following whould work in your gsp:

${session.SPRING_SECURITY_CONTEXT?.authentication?.authenticated}

or just directly in your controller code. I use this with the Navigation plugin to show certain menu's:

static navigation = [
        group:'tabs', 
        order:10, 
        isVisible: {  session.SPRING_SECURITY_CONTEXT?.authentication?.authenticated }
    ]

and, to answer your question, you could get the user object like this:

session.SPRING_SECURITY_CONTEXT?.authentication?.principal?
Jeroen Wijdemans