16 September 2011

Whether the current user belongs to a SharePoint group policy

This time I will present the work Code which provides the current user has identification.

    #region Permission
    /// <summary>
    /// return true is the CurrentUser has Permission in CurrentWeb
    /// groupNames is the groups that split by ';'.
    /// </summary>
    /// <param name="groupNames"></param>
    /// <returns></returns>
    public static bool IsUserHasPermission(string groupNames)
    {
      SPUser user = SPContext.Current.Web.CurrentUser;
      SPWeb web = SPContext.Current.Web;
      return IsUserHasPermission(groupNames,web,user);
    }
    /// <summary>
    /// return true is the User has Permission in Web
    /// groupNames is the groups that split by ';'.
    /// </summary>
    /// <param name="groupNames"></param>
    /// <returns></returns>
    public static bool IsUserHasPermission(string groupNames, SPWeb web,SPUser user)
    {
      try
      {
        string[] arrGroups = groupNames.Split(';');
        bool isUserHasPermission = false;
        if (!String.IsNullOrEmpty(groupNames))
        {
          if (user.Groups.OfType<SPGroup>().Where<SPGroup>(x => arrGroups.Contains(x.Name)).Count() > 0)
          {
            isUserHasPermission = true;
          }
          List<SPGroup> grps = new List<SPGroup>();
          // checking if current user exist in group
          foreach (SPGroup grp in web.Groups)
          {
            if (arrGroups.Contains(grp.Name))
              grps.Add(grp);
          }
          if (grps.Where<SPGroup>(x => x.ContainsCurrentUser).Count() > 0)
          {
            isUserHasPermission = true;
          }

        }
        return isUserHasPermission;
      }
      catch (Exception ex)
      {
        SetErrorMessage(ex);
        throw ex;
      }
    }
    #endregion

All you need to send method - This group names. You can also submit the web and user.

Example for groupNames :
string groupNames = "Group1;Group2;Group3";

yours,
Roi

1 comment:

Anonymous said...

thank you very very much :-)

Post a Comment