I am newbie in Grails. I am using Spring Security Grails plugin for Authentication purpose. I want to get current user in my view gsp file.
I am trying like this ...
<g:if test="${post.author == Person.get(springSecurityService.principal.id).id }">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
Here I want to show Edit this post link to only those posts who created by signed_in user. But It showing ERROR -
Error 500: Internal Server Error
URI
/groovypublish/post/list
Class
java.lang.NullPointerException
Message
Cannot get property 'principal' on null object
Here is my Post.groovy --
class Post {
static hasMany = [comments:Comment]
String title
String teaser
String content
Date lastUpdated
Boolean published = false
SortedSet comments
Person author
....... more code ....
Here is my Person.groovy Domain Class File --
class Person {
transient springSecurityService
String realName
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
byte[] avatar
String avatarType
static hasMany = [followed:Person, posts:Post]
static searchable = [only: 'realName']
........ more code ......
Please help.
You can use the Spring Security Taglibs. For what you want to do, check if logged in user is owner of post, you can do the following:
<sec:isLoggedIn>
<g:if test="${post.author.id == sec.loggedInUserInfo(field: 'id')}">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
</sec:isLoggedIn>
If you find you need to do this check a lot, I would suggest putting it into a custom taglib
class AuthTagLib {
def springSecurityService
def isOwner = { attrs, body ->
def loggedInUser = springSecurityService.currentUser
def owner = attrs?.owner
if(loggedInUser?.id == owner?.id) {
out << body()
}
}
}
Then use it like so
<g:isOwner owner="${post?.author}">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:isOwner>