4

I am using MongoDB and Spring Security Core and UI on my application. Nearly everything works perfectly, except this bit:

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

which is part of the User domain class. I have read that dirty checking was not supported by the MongoDB plugin yet. So I tried to implement my own like this:

if ( User.collection.findOne(id:id).password != password ) {
            encodePassword()
        } 

But it is not working. I get the classical Cannot get property 'password' on null object.

Does anyone know how to reference an instance from the domain class definition ? I am also open to any better idea to implement the dirty checking.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alexandre Bourlier
  • 3,972
  • 4
  • 44
  • 76
  • See last comment at this JIRA issue: http://jira.grails.org/browse/GPMONGODB-114?focusedCommentId=69898&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-69898 "You'll need to delete the beforeInsert, beforeUpdate, and encodePassword methods and encrypt the password like in earlier versions of the plugin, using springSecurityService.encodePassword() in controllers, services, etc." – Klemens Zleptnig May 25 '13 at 13:09

4 Answers4

2

Maybe findOne is returning null? Did you try:

def existing = User.collection.findOne(id:id)?.password 
if ( !existing || existing != password ) 
Graeme Rocher
  • 7,985
  • 2
  • 26
  • 37
  • This works. I did User.collection?.findOne(id)?.password, in case we are running a unit test and collection is not defined. – Keeth Sep 09 '13 at 18:36
0

I just hit the same problem, until the dynamic methods work, this will have to do:

def mongo
def beforeUpdate() {
    def persisted = mongo.getDB("test").user.findOne(id).password
    def encodedNew = springSecurityService.encodePassword(password)
    if(persisted != encodedNew) password = encodedNew
    //if (isDirty('password')) {
    //  encodePassword()
    //}
}
Andre
  • 11
0
User.collection.findOne(_id:id).password
amit
  • 1,991
  • 1
  • 18
  • 29
0

I struggled with this issue as well - here is my solution:

def beforeUpdate() {
    User.withNewSession {
        def user = User.findByUsername(this.username)
        if ( !user?.password || user?.password != password) {
            encodePassword()
        }
    }
}

Please let me know if there is a more efficient way.