/// <summary> /// Adds a new permission level to the web. /// </summary> /// <param name = "web"></param> /// <param name = "name"></param> /// <param name = "description"></param> /// <param name = "permissions"></param> public static void CreatePermissionLevel(SPWeb web, string name, string description, SPBasePermissions permissions) { if (!web.IsRootWeb && !web.HasUniqueRoleDefinitions) { throw new NotSupportedException("This web must be broken permission before adding new permission level."); } var roleDefinition = GetRoleDefinition(web, name); if (roleDefinition != null) { if (roleDefinition.BasePermissions != permissions || roleDefinition.Description != description) { roleDefinition.BasePermissions = permissions; roleDefinition.Description = description; roleDefinition.Update(); } } else { roleDefinition = new SPRoleDefinition { Name = name, Description = description, BasePermissions = permissions }; web.RoleDefinitions.Add(roleDefinition); } }
/// <summary> /// Adds a given permission to the root SPWeb of a given SPSite, if it doesn't exist. /// An optional set of base permissions are added to the permission. /// </summary> /// /// <param name="spSiteGuid">The GUID of the SPSite to add permissions to the root SPWeb of. /// </param> /// /// <param name="permissionName">The name of the permission to create.</param> /// /// <param name="permissionDescription">The description of the permission to create.</param> /// /// <param name="basePermissionsToAdd">Base permissions to add to the permission. Use 0 if /// no base permissions need to be added.</param> /// static void CreatePermission(Guid spSiteGuid, string permissionName, string permissionDescription, SPBasePermissions basePermissionsToAdd) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite spSite = new SPSite(spSiteGuid)) { using (SPWeb rootWeb = spSite.RootWeb) { SPRoleDefinitionCollection roleDefs = rootWeb.RoleDefinitions; try { SPRoleDefinition roleDef = roleDefs[permissionName]; roleDef.BasePermissions |= basePermissionsToAdd; roleDef.Update(); // permission already exists } catch (SPException) { // permission doesn't exist -- create it SPRoleDefinition roleDef = new SPRoleDefinition(); roleDef.Name = permissionName; roleDef.Description = permissionDescription; roleDef.BasePermissions |= basePermissionsToAdd; roleDefs.Add(roleDef); } } } }); }
/// <summary> /// Gets the web. /// </summary> /// <param name="webUrl">The web URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public Web GetWeb(string webUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { var url = string.Format(SpApiConstants.Webs.GET_SINGLE_PERMISSION_TRIMMED, webUrl, (int)effectiveBasePermissions); var response = JsonConvert.DeserializeObject <RestItemResponse <Web> >(GetString(url, accessToken)); return(response.d); }
private void ResetListSettings(ref DesignDataSource source) { DesignDataSource _source = source; if (source.ListInheritanceChange || source.ListRoleChange) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite site = SPContext.Current.Site; SPWeb web = site.OpenWeb(new Guid(_source.WebId)); SPList list = web.Lists[new Guid(_source.ListId)]; if (_source.ListInheritanceChange) { list.ResetRoleInheritance(); list.Update(); _source.ListInheritanceChange = false; } if (_source.ListRoleChange) { SPBasePermissions anon = list.AnonymousPermMask64; list.AnonymousPermMask64 -= SPBasePermissions.AddListItems; list.Update(); _source.ListRoleChange = false; } }); } source = _source; }
private void UpdateListSettings() { SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite site = SPContext.Current.Site; foreach (DesignDataSource source in sources) { SPWeb web = site.OpenWeb(new Guid(source.WebId)); SPList list = web.Lists[new Guid(source.ListId)]; if (!list.HasUniqueRoleAssignments) { list.BreakRoleInheritance(true); source.ListInheritanceChange = true; } SPBasePermissions anon = list.AnonymousPermMask64; list.AnonymousPermMask64 = anon | SPBasePermissions.AddListItems; list.Update(); source.ListRoleChange = true; } SourceValue = Utilities.SerializeObject(sources); }); }
private void EnableFormsLockDown(SPFeatureReceiverProperties properties) { if (properties.Feature.Parent is SPSite) { SPSite site = (SPSite)properties.Feature.Parent; foreach (SPWeb web in site.AllWebs) { try { //SPWeb rootWeb = site.RootWeb; SPRoleDefinition guestRole = web.RoleDefinitions.GetByType(SPRoleType.Guest); guestRole.BasePermissions &= ~(SPBasePermissions.EmptyMask | SPBasePermissions.ViewFormPages); guestRole.BasePermissions &= ~SPBasePermissions.UseRemoteAPIs; guestRole.BasePermissions |= SPBasePermissions.ViewVersions; guestRole.Update(); SPBasePermissions guest = guestRole.BasePermissions; web.AnonymousPermMask64 &= ~(SPBasePermissions.UseRemoteAPIs | SPBasePermissions.ViewFormPages); web.Update(); web.AnonymousPermMask64 |= SPBasePermissions.ViewVersions; web.Update(); SPBasePermissions permissions = web.AnonymousPermMask64; } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); } } } }
private bool DoesUserHavePermssionsToWeb(ref SPUser user, ref SPWeb web) { bool hasPermission = false; SPBasePermissions perms = this.GetPermissionsForUser(ref user, ref web); if (perms.ToString().Contains(SPBasePermissions.Open.ToString()) || perms.ToString().Contains(SPBasePermissions.FullMask.ToString())) { hasPermission = true; } if (!hasPermission) { // Check the users groups - this is for indirect membership; foreach (string groupLoginName in this.GetCurrentUserADGroups()) { try { SPUser groupUser = web.SiteUsers[groupLoginName]; perms = this.GetPermissionsForUser(ref groupUser, ref web); if (perms.ToString().Contains(SPBasePermissions.Open.ToString()) || perms.ToString().Contains(SPBasePermissions.FullMask.ToString())) { hasPermission = true; break; } } catch { } } } return(hasPermission); }
/// <summary> /// Imports the security. /// </summary> /// <param name="targetList">The target list.</param> /// <param name="web">The web.</param> /// <param name="includeItemSecurity">if set to <c>true</c> [include item security].</param> /// <param name="listElement">The list element.</param> internal static void ImportSecurity(SPList targetList, SPWeb web, bool includeItemSecurity, XmlElement listElement) { Logger.Write("Progress: Processing list \"{0}\".", targetList.RootFolder.ServerRelativeUrl); try { int writeSecurity = int.Parse(listElement.GetAttribute("WriteSecurity")); int readSecurity = int.Parse(listElement.GetAttribute("ReadSecurity")); if (writeSecurity != targetList.WriteSecurity) { targetList.WriteSecurity = writeSecurity; } if (readSecurity != targetList.ReadSecurity) { targetList.ReadSecurity = readSecurity; } // Set the security on the list itself. SetObjectSecurity(web, targetList, targetList.RootFolder.ServerRelativeUrl, listElement); // Set the security on any folders in the list. SetFolderSecurity(web, targetList, listElement); // Set the security on any items in the list. if (includeItemSecurity) { SetItemSecurity(web, targetList, listElement); } if (listElement.HasAttribute("AnonymousPermMask64")) { SPBasePermissions anonymousPermMask64 = (SPBasePermissions)int.Parse(listElement.GetAttribute("AnonymousPermMask64")); if (anonymousPermMask64 != targetList.AnonymousPermMask64 && targetList.HasUniqueRoleAssignments) { targetList.AnonymousPermMask64 = anonymousPermMask64; } } if (listElement.HasAttribute("AllowEveryoneViewItems")) { bool allowEveryoneViewItems = bool.Parse(listElement.GetAttribute("AllowEveryoneViewItems")); if (allowEveryoneViewItems != targetList.AllowEveryoneViewItems) { targetList.AllowEveryoneViewItems = allowEveryoneViewItems; } } targetList.Update(); } finally { Logger.Write("Progress: Finished processing list \"{0}\".", targetList.RootFolder.ServerRelativeUrl); } }
public static SPRoleDefinition AddPermissionLevel(this SPWeb web, bool isApprove, bool isAdd, bool isEdit, bool isDelete, string roleName) { SPRoleDefinitionCollection roles = web.RoleDefinitions; SPRoleDefinition role = null; foreach (SPRoleDefinition item in roles) { if (String.Compare(item.Name.Trim(), roleName) == 0) { role = item; break; } } if (role == null) { web.AllowUnsafeUpdates = true; role = new SPRoleDefinition(); SPBasePermissions approve = SPBasePermissions.ViewListItems; SPBasePermissions edit = SPBasePermissions.ViewListItems; SPBasePermissions add = SPBasePermissions.ViewListItems; SPBasePermissions delete = SPBasePermissions.ViewListItems; if (isApprove) { approve = SPBasePermissions.ApproveItems; } if (isEdit) { edit = SPBasePermissions.EditListItems; } if (isAdd) { add = SPBasePermissions.AddListItems; } if (isDelete) { delete = SPBasePermissions.DeleteListItems; } role.BasePermissions = SPBasePermissions.BrowseDirectories | SPBasePermissions.Open | SPBasePermissions.OpenItems | SPBasePermissions.ViewListItems | SPBasePermissions.ViewFormPages | edit | add | delete | approve | SPBasePermissions.ViewPages | SPBasePermissions.CancelCheckout | SPBasePermissions.ViewVersions; role.Name = roleName; web.RoleDefinitions.Add(role); web.Update(); } return(role); }
/// <summary> /// Gets the sites. /// </summary> /// <param name="tenantUrl">The tenant URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public List <Site> GetSites(string tenantUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { var url = String.Format(SpApiConstants.Webs.SEARCH_SITES, tenantUrl); var rawResponse = GetString(url, accessToken); var response = JsonConvert.DeserializeObject <RestSitesResponse>(rawResponse); if (response == null || response.d == null) { return(null); } return(response.GetSitesList()); }
private static bool DoesUserHavePermissionOnPagesLibrary(SPBasePermissions permissionsMask) { bool hasPermissions = false; var pagesLibrary = SPContext.Current.Web.GetPagesLibrary(); if (pagesLibrary != null) { hasPermissions = pagesLibrary.DoesUserHavePermissions(permissionsMask); } return(hasPermissions); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object" /> class. /// </summary> public SPSECBMenuItem(string title, string image, string urlAction, string listGuid, SPBasePermissions rights, int sequence) { _title = title; _image = image; _urlAction = urlAction; _listGuid = listGuid; _rights = rights; _sequence = sequence; }
public bool DoesUserHavePermissions(ArrayInstance permissions) { SPBasePermissions mask = SPBasePermissions.EmptyMask; for (int i = 0; i < permissions.Length; i++) { var flag = permissions[i] as string; if (flag != null) { mask = mask & (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions), flag); } } return(SecurableObject.DoesUserHavePermissions(mask)); }
public static void EnableAccessAnonymous(SPWeb web, string listTitle, SPBasePermissions basePermissions = SPBasePermissions.ViewPages | SPBasePermissions.OpenItems | SPBasePermissions.ViewVersions | SPBasePermissions.Open | SPBasePermissions.UseClientIntegration | SPBasePermissions.ViewFormPages | SPBasePermissions.ViewListItems) { runCodeInListInstance(web, listTitle, (list) => { list.BreakRoleInheritance(true, false); list.AllowEveryoneViewItems = true; list.AnonymousPermMask64 = basePermissions; list.Update(); Logger.Information("ListUtils.EnableAccessAnonymous", "Anonymous access enabled in the \"{0}\"", listTitle); }); }
public override bool DoesUserHasPermissionOnItem(SPListItem item, SPBasePermissions perms) { SPRoleDefinition roleDefinition = item.AllRolesForCurrentUser.Cast <SPRoleDefinition>().Where(x => x.Name.ToLower() == Constants.ContentManager_Perm_Name.ToLower() || x.Name.ToLower() == Constants.Admin_Perm_Name.ToLower()).FirstOrDefault(); if (roleDefinition != null) { return(true); } else { return(false); } //return item.AllRolesForCurrentUser.Cast<SPRoleDefinition>().Any<SPRoleDefinition>(rd=> rd.Name.ToLower() == Constants.ContentManager_Perm_Name.ToLower() || rd.Name.ToLower() == Constants.Admin_Perm_Name.ToLower()); //return item.DoesUserHavePermissions(this._spweb.CurrentUser, perms); }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPUtility.ValidateFormDigest(); try { ConfigurePageLibrary(properties); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } EnableFormsLockDown(properties); try { ConfigureMasterPageGallery(properties); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); } try { ConfigureStyleDocumentLibrary(properties); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); } try { AddSecuritySettings(properties); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); } SPSite site = properties.Feature.Parent as SPSite; SPWeb rootWeb = site.RootWeb; SPBasePermissions permissions = rootWeb.AnonymousPermMask64; }
/// <summary> /// Outputs the perms. /// </summary> /// <param name="perms">The perms.</param> /// <returns></returns> private static string OutputPerms(SPBasePermissions perms) { string output = string.Empty; if ((SPBasePermissions.FullMask & perms) == perms) { return(SPBasePermissions.FullMask.ToString()); } foreach (SPBasePermissions perm in Enum.GetValues(typeof(SPBasePermissions))) { if ((perms & perm) == perm) { output += perm + ", "; } } return(output.Substring(0, output.Length - 2)); }
private SPBasePermissions GetPermissionsForUser(ref SPUser user, ref SPWeb web) { SPBasePermissions perms = SPBasePermissions.EmptyMask; try { SPUserToken userToken = user.UserToken; System.Reflection.MethodInfo getPermissions = typeof(Microsoft.SharePoint.Utilities.SPUtility).GetMethod("GetPermissions", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static); perms = (SPBasePermissions)getPermissions.Invoke(null, new object[] { userToken, web }); } catch { } return(perms); }
public static bool DoesPrincipalHasPermissions(SPListItem item, SPPrincipal principal, SPBasePermissions permissions) { if (principal is SPUser) { return(item.DoesUserHavePermissions((SPUser)principal, permissions)); } SPRoleAssignment assignmentByPrincipal = null; try { assignmentByPrincipal = item.RoleAssignments.GetAssignmentByPrincipal(principal); } catch { return(false); } return(assignmentByPrincipal.RoleDefinitionBindings.Cast <SPRoleDefinition>().Any(definition => (definition.BasePermissions & permissions) == permissions)); }
private static bool DoesPrincipalHasPermissions(SPFolder folder, SPPrincipal principal, SPBasePermissions permissions) { var user = principal as SPUser; if (user != null) { return(folder.Item.DoesUserHavePermissions(user, permissions)); } SPRoleAssignment assignmentByPrincipal = null; try { assignmentByPrincipal = folder.Item.RoleAssignments.GetAssignmentByPrincipal(principal); } catch { return(false); } return(assignmentByPrincipal.RoleDefinitionBindings.Cast <SPRoleDefinition>().Any(definition => (definition.BasePermissions & permissions) == permissions)); }
/// <summary> /// Gets a file from a SharePoint document library /// </summary> /// <param name="urlString">The complete SharePoint URL</param> /// <param name="documentLibrary">The name of the document library</param> /// <param name="documentName">The name of the file to get</param> /// <param name="contextUser">The context User name</param> /// <param name="spBasePermission">The base permission</param> /// <param name="customError">Parameter for returning exception, if any</param> /// <returns>A SPFile based off the parameters</returns> internal SPFile GetFile(string urlString, string documentLibrary, string documentName, string contextUser, SPBasePermissions spBasePermission, out FaultException customError) { customError = null; SPFile spFile = null; var folder = this.GetFolder(urlString, documentLibrary, contextUser, spBasePermission, out customError); if (customError != null) { throw customError; } //If document library doesn't exists, then throw exception if (!folder.Exists) { // customError = new FaultException(String.Format(Properties.Resources.LIBRARY_MISSING, documentLibrary)); return null; } SPWeb spWeb; SPSecurity.RunWithElevatedPrivileges(delegate() { using (var site = new SPSite(urlString)) { using (spWeb = site.OpenWeb()) { var spUserTokenPermission = spWeb.AllUsers[contextUser].UserToken; using (var site1 = new SPSite(urlString, spUserTokenPermission)) { using (spWeb = site1.OpenWeb()) { // Get the file spFile = spWeb.GetFile(urlString + "/" + documentLibrary + "/" + documentName); } } } } }); return spFile; }
private static bool DoesUserHavePermissionOnCurrentFolder(SPBasePermissions permissionsMask) { bool hasPermissionsOnCurrentRootFolderUrl = false; if (!string.IsNullOrEmpty(SPContext.Current.RootFolderUrl)) { SPFolder currentRootFolder = SPContext.Current.Web.GetFolder(SPContext.Current.RootFolderUrl); if (currentRootFolder != null && currentRootFolder.Item != null && currentRootFolder.Item.DoesUserHavePermissions(permissionsMask)) { hasPermissionsOnCurrentRootFolderUrl = true; } } return(hasPermissionsOnCurrentRootFolderUrl || (SPContext.Current.ListItem != null && SPContext.Current.File != null && SPContext.Current.File.ParentFolder != null && SPContext.Current.File.ParentFolder.Item != null && SPContext.Current.File.ParentFolder.Item.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser, permissionsMask))); }
/// <summary> /// Outputs the perms. /// </summary> /// <param name="perms">The perms.</param> /// <returns></returns> private static string OutputPerms(SPBasePermissions perms) { string output = string.Empty; if ((SPBasePermissions.FullMask & perms) == perms) { return SPBasePermissions.FullMask.ToString(); } foreach (SPBasePermissions perm in Enum.GetValues(typeof(SPBasePermissions))) { if ((perms & perm) == perm) { output += perm + ", "; } } return output.Substring(0, output.Length - 2); }
private static bool DoesPrincipalHasPermissions(ISecurableObject item, SPPrincipal principal, SPBasePermissions permissions) { SPRoleAssignment roleAssignment = null; try { roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal); } catch { //if the user has no permission on the item (SPPrincipal is not in permissionlist -> item.RoleAssignments is empty), an exception is thrown. return false; } foreach (SPRoleDefinition definition in roleAssignment.RoleDefinitionBindings) { if ((definition.BasePermissions & permissions) == permissions) { return true; } } return false; }
private static SPRoleDefinition EnsureRoleDefinition(SPWeb web, string name, string description, SPBasePermissions permissions) { for (int i = 0; i < web.RoleDefinitions.Count; i++) { if (web.RoleDefinitions[i].Name == name) { web.RoleDefinitions.Delete(i); } } SPRoleDefinition roleDefinition = new SPRoleDefinition(); roleDefinition.Name = name; roleDefinition.Description = description; roleDefinition.BasePermissions = permissions; web.RoleDefinitions.Add(roleDefinition); web.Update(); roleDefinition = web.RoleDefinitions[name]; return(roleDefinition); }
public static bool LPPFEPermissionCheck(SPList list, SPBasePermissions spBasePermissions) { bool hasPFEResourceCenterPermissions = true; try { if (list != null) { switch (spBasePermissions) { case SPBasePermissions.AddListItems: { if (list.DoesUserHavePermissions(SPBasePermissions.AddListItems)) { var args = new object[] { list.ParentWeb, list.ParentWeb.CurrentUser.ID, false, hasPFEResourceCenterPermissions }; Assembly assembly = Assembly.Load("WorkEnginePPM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"); Type type = assembly.GetType("WorkEnginePPM.Core.ResourceManagement.Utilities", true, true); type.GetMethod("CheckPFEResourceCenterPermission", BindingFlags.Public | BindingFlags.Static).Invoke(null, args); hasPFEResourceCenterPermissions = Convert.ToBoolean(args[3]); return(hasPFEResourceCenterPermissions); } } break; case SPBasePermissions.EditListItems: { if (list.DoesUserHavePermissions(SPBasePermissions.EditListItems)) { var args = new object[] { list.ParentWeb, list.ParentWeb.CurrentUser.ID, false, hasPFEResourceCenterPermissions }; Assembly assembly = Assembly.Load("WorkEnginePPM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"); Type type = assembly.GetType("WorkEnginePPM.Core.ResourceManagement.Utilities", true, true); type.GetMethod("CheckPFEResourceCenterPermission", BindingFlags.Public | BindingFlags.Static).Invoke(null, args); hasPFEResourceCenterPermissions = Convert.ToBoolean(args[3]); return(hasPFEResourceCenterPermissions); } } break; case SPBasePermissions.DeleteListItems: { if (CoreFunctions.DoesCurrentUserHaveFullControl(list.ParentWeb)) { var args = new object[] { list.ParentWeb, list.ParentWeb.CurrentUser.ID, true, hasPFEResourceCenterPermissions }; Assembly assembly = Assembly.Load("WorkEnginePPM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"); Type type = assembly.GetType("WorkEnginePPM.Core.ResourceManagement.Utilities", true, true); type.GetMethod("CheckPFEResourceCenterPermission", BindingFlags.Public | BindingFlags.Static).Invoke(null, args); hasPFEResourceCenterPermissions = Convert.ToBoolean(args[3]); return(hasPFEResourceCenterPermissions); } } break; } return(false); } } catch { //No need to handle this exception because If PFE is not configured on Share Point site then also It should show Invite button. //Hence, Rather then setting hasPFEResourceCenterPermissions = false; Keeping this exception block blank. return(true); } return(list.DoesUserHavePermissions(spBasePermissions)); }
private static bool LIP(SPListItem listItem, SPBasePermissions spBasePermissions) { return(listItem.DoesUserHavePermissions(spBasePermissions)); }
/// <summary> /// Gets the SPFolder from SharePoint /// </summary> /// <param name="urlString">The SharePoint URL</param> /// <param name="documentLibrary">The Document Library Folder to retrieve</param> /// <param name="contextUser">The context User name</param> /// <param name="spBasePermission"> </param> /// <param name="customError">Parameter for returning the exception</param> /// <returns>A SPFolder based off the parameters</returns> internal SPFolder GetFolder(string urlString, string documentLibrary, string contextUser, SPBasePermissions spBasePermission, out FaultException customError) { customError = null; SPFolder spFolder = null; SPUserToken spUserTokenPermission; SPSecurity.RunWithElevatedPrivileges(delegate() { using (var site = new SPSite(urlString)) { using (var spWeb = site.OpenWeb()) { var spUser = spWeb.AllUsers[contextUser]; // Check if the user has permissions to access the Sharepoint if (!spWeb.DoesUserHavePermissions(spUser.LoginName, SPBasePermissions.Open)) { // throw new FaultException(Properties.Resources.NOT_AUTHORIZED); //customErrorReturnType = new FaultException(Properties.Resources.NOT_AUTHORIZED); //return null; } spUserTokenPermission = spUser.UserToken; } } using (var site = new SPSite(urlString, spUserTokenPermission)) { using (SPWeb spWeb = site.OpenWeb()) { // Check if the user has base permissions. if (!spWeb.DoesUserHavePermissions(spBasePermission)) { //throw new FaultException(Properties.Resources.NOT_AUTHORIZED); //customErrorReturnType = new FaultException(Properties.Resources.NOT_AUTHORIZED); //return null; } spFolder = spWeb.GetFolder(documentLibrary); //If document library doesn't exists, then throw exception if (!spFolder.Exists) { // throw new FaultException(String.Format(Properties.Resources.LIBRARY_MISSING, documentLibrary)); //customErrorReturnType = new FaultException(String.Format(Properties.Resources.LIBRARY_MISSING, documentLibrary)); //return null; } } } }); customError = null; return spFolder; }
/// <summary> /// Adds the role definitions. /// </summary> /// <param name="web">The web.</param> /// <param name="roleAssignment">The role assignment.</param> /// <param name="roleAssignmentElement">The role assignment element.</param> /// <returns></returns> private static bool AddRoleDefinitions(SPWeb web, SPRoleAssignment roleAssignment, XmlElement roleAssignmentElement) { bool modified = false; foreach (XmlElement roleDefinitionElement in roleAssignmentElement.SelectNodes("RoleDefinitionBindings/RoleDefinition")) { string name = roleDefinitionElement.GetAttribute("Name"); if (name == "Limited Access") { continue; } SPRoleDefinition existingRoleDef = null; try { existingRoleDef = web.RoleDefinitions[name]; } catch (Exception) { } if (existingRoleDef == null) { Logger.Write("Progress: Adding new Role Definition \"{0}\".", name); SPBasePermissions perms = SPBasePermissions.EmptyMask; foreach (string perm in roleDefinitionElement.GetAttribute("BasePermissions").Split(',')) { perms = perms | (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions), perm, true); } existingRoleDef = new SPRoleDefinition(); existingRoleDef.Name = name; existingRoleDef.BasePermissions = perms; existingRoleDef.Description = roleDefinitionElement.GetAttribute("Description"); existingRoleDef.Order = int.Parse(roleDefinitionElement.GetAttribute("Order")); existingRoleDef.Update(); SPWeb tempWeb = web; while (!tempWeb.HasUniqueRoleDefinitions) { tempWeb = tempWeb.ParentWeb; } tempWeb.RoleDefinitions.Add(existingRoleDef); } if (!roleAssignment.RoleDefinitionBindings.Contains(existingRoleDef)) { roleAssignment.RoleDefinitionBindings.Add(existingRoleDef); modified = true; } } List <SPRoleDefinition> roleDefsToRemove = new List <SPRoleDefinition>(); foreach (SPRoleDefinition roleDef in roleAssignment.RoleDefinitionBindings) { if (roleDef.Name == "Limited Access") { continue; } bool found = false; foreach (XmlElement roleDefinitionElement in roleAssignmentElement.SelectNodes("RoleDefinitionBindings/RoleDefinition")) { if (roleDef.Name == roleDefinitionElement.GetAttribute("Name")) { found = true; break; } } if (!found) { roleDefsToRemove.Add(roleDef); modified = true; } } foreach (SPRoleDefinition roleDef in roleDefsToRemove) { Logger.Write("Progress: Removing '{0}' from '{1}'", roleDef.Name, roleAssignment.Member.Name); roleAssignment.RoleDefinitionBindings.Remove(roleDef); } return(modified); }
/// <summary> /// Gets the web where user has permissions. /// </summary> /// <param name="tenantUrl">The tenant URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public Common.Models.Web GetWebWhereUserHasPermissions(string tenantUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { return(_sharePointService.GetWeb(tenantUrl, accessToken, effectiveBasePermissions)); }
/// <summary> /// Gets the sites where user has permissions. /// </summary> /// <param name="tenantUrl">The tenant URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public List <Site> GetSitesWhereUserHasPermissions(string tenantUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { return(_sharePointService.GetSites(tenantUrl, accessToken, effectiveBasePermissions)); }
/// <summary> /// Gets the web where user has permissions. /// </summary> /// <param name="tenantUrl">The tenant URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public Common.Models.Web GetWebWhereUserHasPermissions(string tenantUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { return _sharePointService.GetWeb(tenantUrl, accessToken, effectiveBasePermissions); }
public void BtnOK_Click(object sender, EventArgs e) { SPList taskList = null; SPList historyList = null; if (!IsValid) { return; } if (!m_bContentTypeTemplate) { // If the user requested a new task list, create it. if (m_taskListId == Guid.Empty) { string description = string.Format("Task list for the {0} workflow.", m_workflowName); m_taskListId = Web.Lists.Add(m_taskListName, description, SPListTemplateType.Tasks); } // If the user requested a new history list, create it. if (m_historyListId == Guid.Empty) { string description = string.Format("History list for the {0} workflow.", m_workflowName); m_historyListId = Web.Lists.Add(m_historyListName, description, SPListTemplateType.WorkflowHistory); } taskList = Web.Lists[m_taskListId]; historyList = Web.Lists[m_historyListId]; } // perform association (if it doesn't already exist) bool isNewAssociation; if (m_assocTemplate == null) { isNewAssociation = true; if (!m_bContentTypeTemplate) { m_assocTemplate = SPWorkflowAssociation.CreateListAssociation(m_baseTemplate, m_workflowName, taskList, historyList); } else { m_assocTemplate = SPWorkflowAssociation.CreateSiteContentTypeAssociation(m_baseTemplate, m_workflowName, taskList.Title, historyList.Title); } } else // modify existing template { isNewAssociation = false; m_assocTemplate.Name = m_workflowName; m_assocTemplate.SetTaskList(taskList); m_assocTemplate.SetHistoryList(historyList); } // set up starup parameters in the template m_assocTemplate.Name = m_workflowName; m_assocTemplate.LockItem = m_bLockItem; m_assocTemplate.AutoStartCreate = m_autoStartCreate; m_assocTemplate.AutoStartChange = m_autoStartChange; m_assocTemplate.AllowManual = m_allowManual; if (m_assocTemplate.AllowManual) { SPBasePermissions newPerms = SPBasePermissions.EmptyMask; if (Request.Params["ManualPermEditItemRequired"] == "ON") { newPerms |= SPBasePermissions.EditListItems; } if (Request.Params["ManualPermManageListRequired"] == "ON") { newPerms |= SPBasePermissions.ManageLists; } m_assocTemplate.PermissionsManual = newPerms; } // place data from form into the association template m_assocTemplate.AssociationData = SerializeFormToString(FormType.Association);// SerializeFormToString(m_assocTemplate.AssociationData, FormType.Association); // if its a content type association, add the template to the content type if (m_ct != null) { if (isNewAssociation) { m_ct.AddWorkflowAssociation(m_assocTemplate); } else { m_ct.UpdateWorkflowAssociation(m_assocTemplate); } if (m_updateLists) { m_ct.UpdateWorkflowAssociationsOnChildren(false); } } else// Else, if this is a list association, { if (isNewAssociation) //if new association { List.AddWorkflowAssociation(m_assocTemplate); } else { List.UpdateWorkflowAssociation(m_assocTemplate); } if (m_assocTemplate.AllowManual && List.EnableMinorVersions) { //In case you selected this WF to be the content approval WF (m_setDefault = true see association page) if (List.DefaultContentApprovalWorkflowId != m_assocTemplate.Id && m_setDefault) { if (!List.EnableModeration) { List.EnableModeration = true; } List.DefaultContentApprovalWorkflowId = m_assocTemplate.Id; List.Update(); } else if (List.DefaultContentApprovalWorkflowId == m_assocTemplate.Id && !m_setDefault) { // Reset the DefaultContentApprovalWorkflowId List.DefaultContentApprovalWorkflowId = Guid.Empty; List.Update(); } } } string strUrl = StrGetRelativeUrl(this, "WrkSetng.aspx", null) + m_strQueryParams; Response.Redirect(strUrl); }
private bool DoesUserHavePermissionOnCurrentFolder(SPBasePermissions permissionsMask) { bool hasPermissionsOnCurrentRootFolderUrl = false; if (!string.IsNullOrEmpty(SPContext.Current.RootFolderUrl)) { SPFolder currentRootFolder = SPContext.Current.Web.GetFolder(SPContext.Current.RootFolderUrl); if (currentRootFolder != null && currentRootFolder.Item != null && currentRootFolder.Item.DoesUserHavePermissions(permissionsMask)) { hasPermissionsOnCurrentRootFolderUrl = true; } } return hasPermissionsOnCurrentRootFolderUrl || (SPContext.Current.ListItem != null && SPContext.Current.File != null && SPContext.Current.File.ParentFolder != null && SPContext.Current.File.ParentFolder.Item != null && SPContext.Current.File.ParentFolder.Item.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser, permissionsMask)); }
private static bool LP(SPList list, SPBasePermissions spBasePermissions) { return(list.DoesUserHavePermissions(spBasePermissions)); }
private bool DoesUserHavePermissionOnCurrentListItem(SPBasePermissions permissionsMask) { return SPContext.Current.ListItem != null && SPContext.Current.ListItem.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser, permissionsMask); }
/// <summary> /// Gets the sites where user has permissions. /// </summary> /// <param name="tenantUrl">The tenant URL.</param> /// <param name="accessToken">The access token.</param> /// <param name="effectiveBasePermissions">The effective base permissions.</param> public List<Site> GetSitesWhereUserHasPermissions(string tenantUrl, string accessToken, SPBasePermissions effectiveBasePermissions) { return _sharePointService.GetSites(tenantUrl, accessToken, effectiveBasePermissions); }
private bool DoesUserHavePermissionOnPagesLibrary(SPBasePermissions permissionsMask) { bool hasPermissions = false; var pagesLibrary = SPContext.Current.Web.GetPagesLibrary(); if (pagesLibrary != null) { hasPermissions = pagesLibrary.DoesUserHavePermissions(permissionsMask); } return hasPermissions; }
public override bool DoesUserHasPermissionOnItem(SPListItem item, SPBasePermissions perms) { SPRoleDefinition roleDefinition = item.AllRolesForCurrentUser.Cast<SPRoleDefinition>().Where(x => x.Name.ToLower() == Constants.ContentManager_Perm_Name.ToLower() || x.Name.ToLower() == Constants.Admin_Perm_Name.ToLower()).FirstOrDefault(); if (roleDefinition != null) { return true; } else { return false; } //return item.AllRolesForCurrentUser.Cast<SPRoleDefinition>().Any<SPRoleDefinition>(rd=> rd.Name.ToLower() == Constants.ContentManager_Perm_Name.ToLower() || rd.Name.ToLower() == Constants.Admin_Perm_Name.ToLower()); //return item.DoesUserHavePermissions(this._spweb.CurrentUser, perms); }
public static void AddECBMenu(this SPList list, string title, string location, string url, SPBasePermissions basePermission) { SPUserCustomActionCollection spUserCustomActionCollection = list.UserCustomActions; var spUserCustomAction = spUserCustomActionCollection.FirstOrDefault(p => p.Title == title); if (spUserCustomAction == null) { spUserCustomAction = spUserCustomActionCollection.Add(); spUserCustomAction.Location = location; spUserCustomAction.Sequence = 100; spUserCustomAction.Title = title; if (basePermission != null) { spUserCustomAction.Rights = basePermission; } spUserCustomAction.Url = url; spUserCustomAction.Update(); } }