How to check if user has access to a page in user macro

Hi,

is there a possibility to check, if a user has permission to view a page inside a user macro?
I tried the following but have not been successful.

#set($permissionHelper = $content.class.forName('com.atlassian.confluence.security.PermissionHelper'))
#set($user = $req.getRemoteUser())
#set ($spaceKey = $space.key)
#set ($pageName = $paramLink)
$permissionHelper.canViewPage($user, $spaceKey, $pageName)

Cheers,
Thomas

1 Like

Hi @thomas.egger,

  1. The permissionHelper is already loaded and accessible, so you do not have to load it yourself (see here: Confluence Objects Accessible from Velocity).
  2. The user has to be of class com.atlassian.user.User, but you are using a string from the servlet request.
  3. I do not know what $paramLink is, but I recommend that you should rather use the page id instead of the spacekey and the page title. Otherwise you might run into trouble with characters like Umlauts in page titles.

This is working for me with nothing else set up:

$permissionHelper.canViewPage($action.remoteUser,123456789)

Best regards
Alex

1 Like

Thanks Alex! That helped me a lot.
The problem was that my user has been a string instead of the named class. I didn’t know how to do that.

$paramLink comes from an input field of my user macro:

## @param Link:title=Internal Link|type=confluence-content|desc=Choose the local destination page. Choose either between a local or external link.

My code now looks something like this:

#set ($colonIndex = $paramLink.indexOf(":"))
#if ($colonIndex == -1)
  #set ($spaceKey = $space.key)
  #set ($pageName = $paramLink)
#else
  #set ($spaceKey = $paramLink.substring(0, $colonIndex))
  #set ($pageNameIndex = $colonIndex + 1 )
  #set ($pageName = $paramLink.substring($pageNameIndex))
#end
#set ($page = $pageManager.getPage($spaceKey, $pageName))

$permissionHelper.canViewPage($action.remoteUser, $spaceKey, $pageName)

$page is used later to display some stuff. This code even handles pages that don’t get a nicely readable URL from Confluence.

Your suggestion to work with the ID is a much smoother approach but unfortunately

#set ($pageId = $page.getIdAsString())
$permissionHelper.canViewPage($action.remoteUser,$pageId)

does not work because the second parameter should be of type long as stated on https://docs.atlassian.com/atlassian-confluence/6.6.0/com/atlassian/confluence/security/PermissionHelper.html#canViewPage-com.atlassian.user.User-long-

Anyway, now everything seems to be fine. Thanks again!

Cheers,
Thomas

1 Like