views:

225

answers:

1

Given a list of Workspaces:

http://server/managed_path/sitecoll/basic
http://server/managed_path/sitecoll/blank
http://server/managed_path/sitecoll/decision
http://server/managed_path/sitecoll/multipage
http://server/managed_path/sitecoll/social

How can I call DoesUserHavePermissions() - or something similar - to find out if the currently logged in user can access the web site?

I am writing a user control to output a list of workspaces they have access to, but when I try to check, I get a variety of errors I can't seem to work around with this code:

foreach (String s in workspaces)
{
    using (SPSite site = new SPSite(s))
    {
        using (SPWeb web = site.OpenWeb(s))
        {
    // web.DoesUserHavePermissions(...)
        }
    }
}
+1  A: 

1) The list of URLs in your example are all in the same site collection, just different webs involved, this means you don't have to re-open the SPSite every time, just SPWebs

2) When opening the spsite, use "SystemAccount.Token" as in this example: http://blackninjasoftware.com/2009/04/09/how-to-programmatically-impersonate-users-in-sharepoint/

SPSite tempSite = new SPSite(siteStr); 
SPUserToken systoken = tempSite.SystemAccount.UserToken;
using (SPSite site = new SPSite(siteStr, systoken)) {
   //here goes the foreach loop and you iterate through the workspaces
}

This way you will be able to call "DoesuserHavePermissions" method.

3) This bear in mind that opening and closing SPWebs at runtime will hit performance. Try to cache the results of your code, if possible.

naivists
Good answer, except I don't think you will be able to open a web if the user does not have access to it. At best, it will throw a FileNotFound exception and at worst it will open the SPSite's web without an exception. Be careful with OpenWeb and make sure it gets you the web you are looking for.
Kit Menke
@Kit Menke, when you open a SPSite object using SystemAccount's user token, you *are* the system account. Hence, you can do whatever the system account can do.
naivists
Sorry, I apparently didn't read it very closely. :) As the system account, you would have access to everything. I don't understand how being the system account would allow you to determine if the current user can open the URL or not...
Kit Menke
@Kit, 'SPWeb' has a method "DoesUserHavePermissions" where you can pass a login to that method (http://msdn.microsoft.com/en-us/library/ms441848.aspx) You take the login from SPContext.Current.Web.CurrentUser, but do the tests using System account.
naivists
Ah now it all makes sense! Thanks for the explanation.
Kit Menke