1
votes

We can develop a webpart and deploy in sharepoint site with some user context. This is specific to user. Suppose if we login with read only user then we will get an error message stating like error occurred. Is there any way to avoid that? Means, if we login with read only user then the webpart should not visible to that user. If login user has full rights then it should visible to that user.

SPSecurity.RunWithElevatedPrivileges 

method Executes the specified method with Full Control rights even if the user does not otherwise have Full Control. Like this is there any method to satisfy my criteria with out showing any error in the webpage. Please give me solution. Thanks.

1

1 Answers

3
votes

What you could do is handle if the user has not enough permissions to access a certain resource and stop rendering the web part.

Firstly, access denied handling: Assuming you are accessing the resources in CreateChildControls of the web part:

private bool accessDenied;

protected override void CreateChildControls()
{ 
  try
  {
    // prevent SharePoint from catching an access denied exception and 
    // redirecting to the error page.
    using (new SPSecurity.SuppressAccessDeniedRedirectInScope())
    {
      SPContext.Current.Web.Lists["Restriced"] // some thing...
    }
  }
  catch (UnauthorizedAccessException)
  {
    // set variable in case the user has not enough permissions
    accessDenied = true;
  } 
}

Now, we know whether the user has not enough rights to access a resource. Next step is to disable rendering and hide the web part and its contents. Hiding the web part is straightforward. All we need to do is override the render method and do nothing:

protected override void RenderWebPart(HtmlTextWriter writer)
{
  if (accessDenied) return;

  base.RenderWebPart(writer);
}

You could alternatively display an error message. However this would defeat the purpose, I guess.

Last step is to disable the web part's chrome. This can be done by setting the ChromeType in the OnPreRender method:

protected override void OnPreRender(EventArgs e)
{
  // Important to call base method in order to ensure child controls...
  base.OnPreRender(e);

  if (accessDenied)
  {
    ChromeType = PartChromeType.None;
  }
}

Of course, if you are overriding other methods in the web part you need to check if accessDenied is set.