spock99
spock99

Reputation: 1184

grails gorm how to do a join with a 3 table hierarchy

My web interface has an ajax call to update a photo's caption. A post sends the caption and the publicId of the photo to a service.

The service has 

Photo photo = Photo.findByPublicId(params.publicId)
photo.caption = params.caption
photo.save()

However I have read in Burt Beckwith's grails book this is not secure. As-is a hacker could post any publicId to my service and update the caption of a photo that doesn't not belong to their session. I need some GORM advice on how to write the update query to update only photos belonging to the current user's session. Due to the number of joins involved I am lost. I am familiar with getting the profile/user:

    User user = User.load(springSecurityService.principal.id)

    Profile profile = Profile.findByUser(user, [lock:true])

but not the one query that would join everything for the entire update, instead of Profile.findByUser(user, [lock:true]).photoAlbum.getPhotoWherePublicId(publicId) or something that seems it would make 4 different sql calls.

The domain schema I have with the hierarchy in question is :

//user from springsecurity for session/login management
class User {
   //no reference to profile
}

class Profile {
   PhotoAlbum photoAlbum
   User user //reference to user

   static constraints = {
       photoAlbum(nullable:true)
   }
}

class PhotoAlbum {
   static hasMany = [photos:Photo]
   static belongsTo = [profile:Profile]
}

class Photo {
   static belongsTo = PhotoAlbum
   String caption
   String publicId
}

Upvotes: 0

Views: 384

Answers (1)

Eylen
Eylen

Reputation: 2677

Maybe with a criteria or namedQuerie this could be done. Something like this may work:

First make a small change to your Photo class

class Photo {
   PhotoAlbum photoAlbum
   static belongsTo = [photoAlbum: PhotoAlbum]
   String caption
   String publicId
}

and try with this criteria

Photo.withCriteria{
  eq 'id',params.publicId
  photoAlbum {
    eq 'profile',profile
  } 
}

Upvotes: 1

Related Questions