/// <summary> /// Updates the specified authorization type. /// </summary> /// <param name="owner">The owner Sid.</param> /// <param name="sid">The member Sid.</param> /// <param name="sidWhereDefined">The object owner where defined.</param> /// <param name="authorizationType">Type of the authorization.</param> /// <param name="validFrom">The valid from.</param> /// <param name="validTo">The valid to.</param> public void Update(IAzManSid owner, IAzManSid sid, WhereDefined sidWhereDefined, AuthorizationType authorizationType, DateTime?validFrom, DateTime?validTo) { if (this.owner.StringValue != owner.StringValue || this.sid.StringValue != sid.StringValue || this.sidWhereDefined != sidWhereDefined || this.authorizationType != authorizationType || this.validFrom != validFrom || this.validTo != validTo) { //DateTime range check if (validFrom.HasValue && validTo.HasValue) { if (validFrom.Value > validTo.Value) { throw new InvalidOperationException("ValidFrom cannot be greater then ValidTo if supplied."); } } SqlAzManSID oldOwner = new SqlAzManSID(this.owner.StringValue, this.ownerSidWhereDefined == WhereDefined.Database); SqlAzManSID oldSid = new SqlAzManSID(this.sid.StringValue, this.sidWhereDefined == WhereDefined.Database); WhereDefined oldOwnerSidWhereDefined = this.ownerSidWhereDefined; WhereDefined oldSidWhereDefined = this.SidWhereDefined; AuthorizationType oldAuthorizationType = this.AuthorizationType; DateTime? oldValidFrom = this.validFrom; DateTime? oldValidTo = this.validTo; string memberName; bool isLocal; DirectoryServicesUtils.GetMemberInfo(owner.StringValue, out memberName, out isLocal); WhereDefined ownerSidWhereDefined = isLocal ? WhereDefined.Local : WhereDefined.LDAP; this.db.AuthorizationUpdate(this.item.ItemId, owner.BinaryValue, (byte)ownerSidWhereDefined, sid.BinaryValue, (byte)sidWhereDefined, (byte)authorizationType, (validFrom.HasValue ? validFrom.Value : new DateTime?()), (validTo.HasValue ? validTo.Value : new DateTime?()), this.authorizationId, this.item.Application.ApplicationId); this.owner = new SqlAzManSID(owner.BinaryValue); this.ownerSidWhereDefined = ownerSidWhereDefined; this.sid = sid; this.sidWhereDefined = sidWhereDefined; this.authorizationType = authorizationType; this.validFrom = validFrom; this.validTo = validTo; this.raiseAuthorizationUpdated(this, oldOwner, oldOwnerSidWhereDefined, oldSid, oldSidWhereDefined, oldAuthorizationType, oldValidFrom, oldValidTo); } }
/// <summary> /// Equalses the specified sqlazman sid. /// </summary> /// <param name="sqlazmanSid">The sqlazman sid.</param> /// <returns></returns> public bool Equals(SqlAzManSID sqlazmanSid) { if (Object.ReferenceEquals(sqlazmanSid, null)) { return(false); } if (this.securityIdentifier != null) { return(this.securityIdentifier.Equals(sqlazmanSid.securityIdentifier)); } else if (this.guid != Guid.Empty) { return(this.guid.Equals(sqlazmanSid.guid)); } else { if (this.customSid.Length != sqlazmanSid.customSid.Length) { return(false); } for (int i = 0; i < this.customSid.Length; i++) { if (this.customSid[i] != sqlazmanSid.customSid[i]) { return(false); } } return(true); } }
/// <summary> /// Updates the specified object owner. /// </summary> /// <param name="description">The description.</param> /// <param name="groupType">Type of the group.</param> public void Update(string description, GroupType groupType) { if (this.description != description || this.groupType != groupType) { this.db.ApplicationGroupUpdate(sid.BinaryValue, this.name, description, this.lDapQuery, (byte)(groupType), this.applicationGroupId, this.application.ApplicationId); IAzManSid oldSid = new SqlAzManSID(this.sid.StringValue); string oldDescription = this.description; GroupType oldGroupType = this.groupType; this.description = description; this.groupType = groupType; this.raiseApplicationGroupUpdated(this, oldSid, oldDescription, oldGroupType); } }
/// <summary> /// Updates the specified object owner. /// </summary> /// <param name="description">The description.</param> /// <param name="groupType">Type of the group.</param> public void Update(string description, GroupType groupType) { if (this.description != description || this.groupType != groupType) { IAzManSid oldSid = new SqlAzManSID(this.sid.StringValue); string oldDescription = this.description; GroupType oldGroupType = this.groupType; this.db.StoreGroupUpdate(this.Store.StoreId, sid.BinaryValue, this.name, description, this.LDAPQuery, (byte)(groupType), this.storeGroupId); this.description = description; this.groupType = groupType; this.raiseStoreGroupUpdated(this, oldSid, oldDescription, oldGroupType); } }
/// <summary> /// Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false. /// </returns> public override bool Equals(object obj) { if (Object.ReferenceEquals(obj, null)) { return(false); } SqlAzManSID sqlazmansid = obj as SqlAzManSID; if (!object.ReferenceEquals(sqlazmansid, null)) { return(this.Equals(sqlazmansid)); } else { return(base.Equals(obj)); } }
/// <summary> /// Equalses the specified sid. /// </summary> /// <param name="sid">The sid.</param> /// <returns></returns> public bool Equals(IAzManSid sid) { if (Object.ReferenceEquals(sid, null)) { return(false); } SqlAzManSID sqlazmansid = sid as SqlAzManSID; if (!object.ReferenceEquals(sqlazmansid, null)) { return(this.Equals(sqlazmansid)); } else { return(this.GetHashCode() == sid.GetHashCode()); } }
/// <summary> /// Gets the store group. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public IAzManStoreGroup GetStoreGroup(string name) { StoreGroupsResult sgr; if ((sgr = (from tf in this.db.StoreGroups() where tf.Name == name && tf.StoreId == this.storeId select tf).FirstOrDefault()) != null) { int storeGroupid = sgr.StoreGroupId.Value; IAzManSid objectSid = new SqlAzManSID(sgr.ObjectSid.ToArray()); string description = sgr.Description; string lDapQuery = sgr.LDapQuery; GroupType groupType = (GroupType)sgr.GroupType.Value; IAzManStoreGroup result = new SqlAzManStoreGroup(this.db, this, storeGroupid, objectSid, name, description, lDapQuery, groupType, this.ens); if (this.ens != null) { this.ens.AddPublisher(result); } return(result); } else { throw SqlAzManException.StoreGroupNotFoundException(name, this, null); } }
/// <summary> /// News the SQL az man owner. /// </summary> /// <returns></returns> public static IAzManSid NewSqlAzManSid() { Guid guid; bool isGood = false; SqlAzManSID result = null; while (!isGood) { try { do { guid = Guid.NewGuid(); } while (guid.ToByteArray()[0] == 1); result = new SqlAzManSID(Guid.NewGuid().ToByteArray()); isGood = true; } catch { isGood = false; } } return(result); }
/// <summary> /// Equalses the specified sqlazman sid. /// </summary> /// <param name="sqlazmanSid">The sqlazman sid.</param> /// <returns></returns> public bool Equals(SqlAzManSID sqlazmanSid) { if (Object.ReferenceEquals(sqlazmanSid, null)) return false; if (this.securityIdentifier != null) return this.securityIdentifier.Equals(sqlazmanSid.securityIdentifier); else if (this.guid != Guid.Empty) return this.guid.Equals(sqlazmanSid.guid); else { if (this.customSid.Length != sqlazmanSid.customSid.Length) return false; for (int i = 0; i < this.customSid.Length; i++) { if (this.customSid[i] != sqlazmanSid.customSid[i]) return false; } return true; } }
/// <summary> /// Gets the application group. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public IAzManApplicationGroup GetApplicationGroup(string name) { ApplicationGroupsResult agr; if ((agr = (from t in this.db.ApplicationGroups() where t.Name == name && t.ApplicationId == this.applicationId select t).FirstOrDefault()) != null) { int applicationGroupid = agr.ApplicationGroupId.Value; IAzManSid objectSid = new SqlAzManSID(agr.ObjectSid.ToArray()); string description = agr.Description; string lDapQuery = agr.LDapQuery; GroupType groupType = (GroupType)agr.GroupType.Value; IAzManApplicationGroup result = new SqlAzManApplicationGroup(this.db, this, applicationGroupid, objectSid, name, description, lDapQuery, groupType, this.ens); if (this.ens != null) this.ens.AddPublisher(result); return result; } else { throw SqlAzManException.ApplicationGroupNotFoundException(name, this, null); } }
private void ImportFromAzMan(string azManStorePath, string netSqlAzManStoreName) { Microsoft.Interop.Security.AzRoles.AzAuthorizationStore azstore = null; string tempFileName = Path.Combine(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.Machine), String.Format("AzMan{0}.xml", Guid.NewGuid())); try { this.storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); string storeDescription = String.Format("Store imported from AzMan Store:" + " ({0}) - {1}", azManStorePath, DateTime.Now.ToString()); IAzManStore store = this.storage.CreateStore(netSqlAzManStoreName, storeDescription); azstore = new AzAuthorizationStoreClass(); if (this.rbtStoreFile.Checked) { this.FileUpload1.SaveAs(tempFileName); azManStorePath = String.Format("msxml://{0}", tempFileName); } azstore.Initialize(2, azManStorePath, null); #region Store Groups //Store Groups foreach (IAzApplicationGroup azStoreGroup in azstore.ApplicationGroups) { //Store Groups Definition if (azStoreGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_BASIC) { //Basic store.CreateStoreGroup(SqlAzManSID.NewSqlAzManSid(), azStoreGroup.Name, azStoreGroup.Description, String.Empty, GroupType.Basic); } else if (azStoreGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_LDAP_QUERY) { //LDap store.CreateStoreGroup(SqlAzManSID.NewSqlAzManSid(), azStoreGroup.Name, azStoreGroup.Description, azStoreGroup.LdapQuery, GroupType.LDapQuery); } } //Store Groups Members foreach (IAzApplicationGroup azStoreGroup in azstore.ApplicationGroups) { if (azStoreGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_BASIC) { //Basic IAzManStoreGroup storeGroup = store.GetStoreGroup(azStoreGroup.Name); //Store Group Members - Members Store Group object[] azStoreGroupMembers = azStoreGroup.AppMembers as object[]; if (azStoreGroupMembers != null) { foreach (string azStoreGroupMember in azStoreGroupMembers) { IAzManStoreGroup member = store.GetStoreGroup(azStoreGroupMember); storeGroup.CreateStoreGroupMember(member.SID, WhereDefined.Store, true); } } //Store Group Non-Members - Non-Members Store Group object[] azStoreGroupNonMembers = azStoreGroup.AppNonMembers as object[]; if (azStoreGroupNonMembers != null) { foreach (string azStoreGroupNonMember in azStoreGroupNonMembers) { IAzManStoreGroup nonMember = store.GetStoreGroup(azStoreGroupNonMember); storeGroup.CreateStoreGroupMember(nonMember.SID, WhereDefined.Store, false); } } //Store Group Members - Windows NT Account object[] azStoreGroupWindowsMembers = azStoreGroup.Members as object[]; if (azStoreGroupWindowsMembers != null) { foreach (string azStoreWindowsMember in azStoreGroupWindowsMembers) { IAzManSid sid = new SqlAzManSID(azStoreWindowsMember); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); storeGroup.CreateStoreGroupMember(sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, true); } } //Store Group NonMembers - Windows NT Account object[] azStoreGroupWindowsNonMembers = azStoreGroup.NonMembers as object[]; if (azStoreGroupWindowsNonMembers != null) { foreach (string azStoreWindowsNonMember in azStoreGroupWindowsNonMembers) { IAzManSid sid = new SqlAzManSID(azStoreWindowsNonMember); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); storeGroup.CreateStoreGroupMember(sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, false); } } } } #endregion Store Groups #region Applications //Applications foreach (IAzApplication azApplication in azstore.Applications) { IAzManApplication application = store.CreateApplication(azApplication.Name, azApplication.Description); #region Application Groups //Store Groups foreach (IAzApplicationGroup azApplicationGroup in azApplication.ApplicationGroups) { //Application Groups Definition if (azApplicationGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_BASIC) { //Basic application.CreateApplicationGroup(SqlAzManSID.NewSqlAzManSid(), azApplicationGroup.Name, azApplicationGroup.Description, String.Empty, GroupType.Basic); } else if (azApplicationGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_LDAP_QUERY) { //LDap application.CreateApplicationGroup(SqlAzManSID.NewSqlAzManSid(), azApplicationGroup.Name, azApplicationGroup.Description, azApplicationGroup.LdapQuery, GroupType.LDapQuery); } } //Application Groups Members foreach (IAzApplicationGroup azApplicationGroup in azApplication.ApplicationGroups) { if (azApplicationGroup.Type == (int)tagAZ_PROP_CONSTANTS.AZ_GROUPTYPE_BASIC) { //Basic IAzManApplicationGroup applicationGroup = application.GetApplicationGroup(azApplicationGroup.Name); //Application Group Members - Members Group object[] azStoreGroupMembers = azApplicationGroup.AppMembers as object[]; if (azStoreGroupMembers != null) { foreach (string azGroupMember in azStoreGroupMembers) { IAzManStoreGroup storemember; try { storemember = store.GetStoreGroup(azGroupMember); } catch (SqlAzManException) { storemember = null; } IAzManApplicationGroup appmember; try { appmember = application.GetApplicationGroup(azGroupMember); } catch (SqlAzManException) { appmember = null; } if (storemember != null) applicationGroup.CreateApplicationGroupMember(storemember.SID, WhereDefined.Store, true); else applicationGroup.CreateApplicationGroupMember(appmember.SID, WhereDefined.Application, true); } } //Application Group Non-Members - Non-Members Group object[] azStoreGroupNonMembers = azApplicationGroup.AppNonMembers as object[]; if (azStoreGroupNonMembers != null) { foreach (string azGroupNonMember in azStoreGroupNonMembers) { IAzManStoreGroup storenonMember; try { storenonMember = store.GetStoreGroup(azGroupNonMember); } catch (SqlAzManException) { storenonMember = null; } IAzManApplicationGroup appnonMember; try { appnonMember = application.GetApplicationGroup(azGroupNonMember); } catch (SqlAzManException) { appnonMember = null; } if (storenonMember != null) applicationGroup.CreateApplicationGroupMember(storenonMember.SID, WhereDefined.Store, false); else applicationGroup.CreateApplicationGroupMember(appnonMember.SID, WhereDefined.Application, false); } } //Application Group Members - Windows NT Account object[] azApplicationGroupWindowsMembers = azApplicationGroup.Members as object[]; if (azApplicationGroupWindowsMembers != null) { foreach (string azApplicationWindowsMember in azApplicationGroupWindowsMembers) { IAzManSid sid = new SqlAzManSID(azApplicationWindowsMember); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); applicationGroup.CreateApplicationGroupMember(sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, true); } } //Application Group NonMembers - Windows NT Account object[] azApplicationGroupWindowsNonMembers = azApplicationGroup.NonMembers as object[]; if (azApplicationGroupWindowsNonMembers != null) { foreach (string azApplicationWindowsNonMember in azApplicationGroupWindowsNonMembers) { IAzManSid sid = new SqlAzManSID(azApplicationWindowsNonMember); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); applicationGroup.CreateApplicationGroupMember(sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, false); } } } } #endregion Application Groups //Without Scopes IAzTasks tasks = azApplication.Tasks as IAzTasks; if (tasks != null) { foreach (IAzTask azTask in tasks) { if (azTask.IsRoleDefinition == 1) { IAzManItem item = application.CreateItem(azTask.Name, azTask.Description, ItemType.Role); } else { IAzManItem item = application.CreateItem(azTask.Name, azTask.Description, ItemType.Task); } } } IAzOperations operations = azApplication.Operations as IAzOperations; if (operations != null) { foreach (IAzOperation azOperation in operations) { application.CreateItem(azOperation.Name, azOperation.Description, ItemType.Operation); } } //Build Item Hierarchy if (tasks != null) { foreach (IAzTask azTask in tasks) { this.SetHirearchy(null, azApplication, azTask.Name, application); } } //Scopes foreach (IAzScope azScope in azApplication.Scopes) { azApplication.OpenScope(azScope.Name, null); IAzTasks tasksOfScope = azScope.Tasks as IAzTasks; if (tasksOfScope != null) { foreach (IAzTask azTask in tasksOfScope) { if (azTask.IsRoleDefinition == 1) { IAzManItem item = application.CreateItem(azTask.Name, azTask.Description, ItemType.Role); } else { IAzManItem item = application.CreateItem(azTask.Name, azTask.Description, ItemType.Task); } } } //Build Item Hierarchy if (tasksOfScope != null) { foreach (IAzTask azTask in tasksOfScope) { this.SetHirearchy(azScope, azApplication, azTask.Name, application); } } } //Authorizations on Roles without Scopes AuthorizationType defaultAuthorization = AuthorizationType.AllowWithDelegation; IAzRoles azRoles = azApplication.Roles; foreach (IAzRole azRole in azRoles) { IAzManItem item; try { item = application.GetItem(azRole.Name); } catch (SqlAzManException) { item = null; } if (item == null) item = application.CreateItem(azRole.Name, azRole.Description, ItemType.Role); //Store & Application Groups Authorizations foreach (string member in (object[])azRole.AppMembers) { IAzManStoreGroup storeGroup; try { storeGroup = application.Store.GetStoreGroup(member); } catch (SqlAzManException) { storeGroup = null; } IAzManApplicationGroup applicationGroup; try { applicationGroup = application.GetApplicationGroup(member); } catch (SqlAzManException) { applicationGroup = null; } if (storeGroup != null) item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, storeGroup.SID, WhereDefined.Store, defaultAuthorization, null, null); else if (applicationGroup != null) item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, applicationGroup.SID, WhereDefined.Application, defaultAuthorization, null, null); } //Windows Users & Groups Authorizations foreach (string sSid in (object[])azRole.Members) { IAzManSid sid = new SqlAzManSID(sSid); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, defaultAuthorization, null, null); } } //Authorizations on Roles with Scopes foreach (IAzScope azScope in azApplication.Scopes) { IAzRoles azRolesWithScopes = azScope.Roles; foreach (IAzRole azRole in azRolesWithScopes) { IAzManItem item; try { item = application.GetItem(azRole.Name); } catch (SqlAzManException) { item = null; } if (item == null) item = application.CreateItem(azRole.Name, azRole.Description, ItemType.Role); //Store & Application Groups Authorizations foreach (string member in (object[])azRole.AppMembers) { IAzManStoreGroup storeGroup; try { storeGroup = application.Store.GetStoreGroup(member); } catch (SqlAzManException) { storeGroup = null; } IAzManApplicationGroup applicationGroup; try { applicationGroup = application.GetApplicationGroup(member); } catch (SqlAzManException) { applicationGroup = null; } if (storeGroup != null) item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, storeGroup.SID, WhereDefined.Store, defaultAuthorization, null, null); else if (applicationGroup != null) item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, applicationGroup.SID, WhereDefined.Application, defaultAuthorization, null, null); } //Windows Users & Groups Authorizations foreach (string sSid in (object[])azRole.Members) { IAzManSid sid = new SqlAzManSID(sSid); string memberName; bool isLocal; DirectoryServicesWebUtils.GetMemberInfo(sid.StringValue, out memberName, out isLocal); item.CreateAuthorization(this.currentOwnerSid, this.currentOwnerSidWhereDefined, sid, isLocal ? WhereDefined.Local : WhereDefined.LDAP, defaultAuthorization, null, null); } } } //try //{ // azstore.CloseApplication(azApplication.Name, 0); //} //catch //{ // //PorkAround: COM Is a mistery //} } #endregion Applications if (storage.TransactionInProgress) storage.CommitTransaction(); } catch { if (storage.TransactionInProgress) { storage.RollBackTransaction(); } throw; } finally { if (azstore != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(azstore); File.Delete(tempFileName); azstore = null; } } }
/// <summary> /// News the SQL az man owner. /// </summary> /// <returns></returns> public static IAzManSid NewSqlAzManSid() { Guid guid; bool isGood = false; SqlAzManSID result = null; while (!isGood) { try { do { guid = Guid.NewGuid(); } while (guid.ToByteArray()[0] == 1); result = new SqlAzManSID(Guid.NewGuid().ToByteArray()); isGood = true; } catch { isGood = false; } } return result; }
private void RefreshActiveDirectoryObjectsList() { DataTable dtADList = new DataTable("Active Directory Objects List"); dtADList.Columns.Add("sAMAccountName", typeof(string)); dtADList.Columns.Add("Name", typeof(string)); dtADList.Columns.Add("objectClass", typeof(string)); dtADList.Columns.Add("objectSid", typeof(string)); if (this.searchResultCollection != null) { foreach (SearchResult sr in this.searchResultCollection) { DirectoryEntry de = sr.GetDirectoryEntry(); DataRow dr = dtADList.NewRow(); dr["sAMAccountName"] = de.Properties["sAMAccountName"]!=null && de.Properties["sAMAccountName"].Count>0 ? (string)de.Properties["sAMAccountName"][0] : String.Empty; dr["Name"] = (string)de.InvokeGet("displayname"); dr["objectClass"] = de.SchemaClassName; dr["objectSid"] = new SqlAzManSID((byte[])de.Properties["objectSid"].Value).StringValue; dtADList.Rows.Add(dr); } } this.gvLDAPQueryResults.DataSource = dtADList; this.gvLDAPQueryResults.DataBind(); this.EmptyGridFix(this.gvLDAPQueryResults); }
protected void Application_Start(object sender, EventArgs e) { List<string> sqlDataSources = new List<string>(); if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["RootDSEPath"])) SqlAzManStorage.RootDSEPath = ConfigurationManager.AppSettings["RootDSEPath"]; NetSqlAzMan.DirectoryServices.DirectoryServicesUtils.SetActiveDirectoryLookUpCredential( ConfigurationManager.AppSettings["Active Directory LookUp Username"], ConfigurationManager.AppSettings["Active Directory LookUp Password"]); //Populate SQL Data Sources System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( delegate(object o) { try { sqlDataSources.AddRange(this.GetSqlDataSources()); this.Application.Lock(); this.Application["SqlDataSources"] = sqlDataSources; this.Application.UnLock(); } catch { this.Application.Lock(); this.Application["SqlDataSources"] = null; this.Application.UnLock(); } } )); //Populate Active Directory Users & Groups System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( delegate(object o) { try { DirectoryEntry root = Utility.NewDirectoryEntry("LDAP://" + SqlAzManStorage.RootDSEPath); DirectorySearcher deSearch = new DirectorySearcher(root); deSearch.Filter = "(|(&(objectClass=user)(objectCategory=person))(objectClass=group))"; SearchResultCollection searchResultCollection = deSearch.FindAll(); DataTable dtADList = null; dtADList = new DataTable("Active Directory Objects List"); dtADList.Columns.Add("sAMAccountName", typeof(string)); dtADList.Columns.Add("Name", typeof(string)); dtADList.Columns.Add("objectClass", typeof(string)); dtADList.Columns.Add("objectSid", typeof(string)); dtADList.Columns.Add("ADSPath", typeof(string)); if (searchResultCollection != null) { foreach (SearchResult sr in searchResultCollection) { DirectoryEntry de = sr.GetDirectoryEntry(); DataRow dr = dtADList.NewRow(); dr["sAMAccountName"] = (string)de.Properties["sAMAccountName"][0]; dr["Name"] = (string)de.InvokeGet("displayname"); dr["objectClass"] = de.SchemaClassName; dr["objectSid"] = new SqlAzManSID((byte[])de.Properties["objectSid"].Value).StringValue; dr["ADSPath"] = de.Path; dtADList.Rows.Add(dr); } } DataView dv = dtADList.DefaultView; dv.Sort = "sAMAccountName"; this.Application.Lock(); this.Application["Active Directory List"] = dv; this.Application.UnLock(); } catch { this.Application.Lock(); this.Application["Active Directory List"] = null; this.Application.UnLock(); } })); }
/// <summary> /// Updates the specified authorization type. /// </summary> /// <param name="owner">The owner Sid.</param> /// <param name="sid">The member Sid.</param> /// <param name="sidWhereDefined">The object owner where defined.</param> /// <param name="authorizationType">Type of the authorization.</param> /// <param name="validFrom">The valid from.</param> /// <param name="validTo">The valid to.</param> public void Update(IAzManSid owner, IAzManSid sid, WhereDefined sidWhereDefined, AuthorizationType authorizationType, DateTime? validFrom, DateTime? validTo) { if (this.owner.StringValue != owner.StringValue || this.sid.StringValue != sid.StringValue || this.sidWhereDefined != sidWhereDefined || this.authorizationType != authorizationType || this.validFrom != validFrom || this.validTo != validTo) { //DateTime range check if (validFrom.HasValue && validTo.HasValue) { if (validFrom.Value > validTo.Value) throw new InvalidOperationException("ValidFrom cannot be greater then ValidTo if supplied."); } SqlAzManSID oldOwner = new SqlAzManSID(this.owner.StringValue, this.ownerSidWhereDefined == WhereDefined.Database); SqlAzManSID oldSid = new SqlAzManSID(this.sid.StringValue, this.sidWhereDefined == WhereDefined.Database); WhereDefined oldOwnerSidWhereDefined = this.ownerSidWhereDefined; WhereDefined oldSidWhereDefined = this.SidWhereDefined; AuthorizationType oldAuthorizationType = this.AuthorizationType; DateTime? oldValidFrom = this.validFrom; DateTime? oldValidTo = this.validTo; string memberName; bool isLocal; DirectoryServicesUtils.GetMemberInfo(owner.StringValue, out memberName, out isLocal); WhereDefined ownerSidWhereDefined = isLocal ? WhereDefined.Local : WhereDefined.LDAP; this.db.AuthorizationUpdate(this.item.ItemId, owner.BinaryValue, (byte)ownerSidWhereDefined, sid.BinaryValue, (byte)sidWhereDefined, (byte)authorizationType, (validFrom.HasValue ? validFrom.Value : new DateTime?()), (validTo.HasValue ? validTo.Value : new DateTime?()), this.authorizationId, this.item.Application.ApplicationId); this.owner = new SqlAzManSID(owner.BinaryValue); this.ownerSidWhereDefined = ownerSidWhereDefined; this.sid = sid; this.sidWhereDefined = sidWhereDefined; this.authorizationType = authorizationType; this.validFrom = validFrom; this.validTo = validTo; this.raiseAuthorizationUpdated(this, oldOwner, oldOwnerSidWhereDefined, oldSid, oldSidWhereDefined, oldAuthorizationType, oldValidFrom, oldValidTo); } }
/// <summary> /// Imports the specified XML reader. /// </summary> /// <param name="xmlNode">The XML node.</param> /// <param name="includeWindowsUsersAndGroups">if set to <c>true</c> [include windows users and groups].</param> /// <param name="includeDBUsers">if set to <c>true</c> [include DB users].</param> /// <param name="includeAuthorizations">if set to <c>true</c> [include authorizations].</param> /// <param name="mergeOptions">The merge options.</param> public void ImportChildren(XmlNode xmlNode, bool includeWindowsUsersAndGroups, bool includeDBUsers, bool includeAuthorizations, SqlAzManMergeOptions mergeOptions) { //Create Store Groups foreach (XmlNode node in xmlNode.ChildNodes) { if (node.Name == "Attributes") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Attribute") { if (!this.Attributes.ContainsKey(childNode.Attributes["Key"].Value)) { IAzManAttribute <IAzManStore> newStoreAttribute = this.CreateAttribute(childNode.Attributes["Key"].Value, childNode.Attributes["Value"].Value); } else { this.Attributes[childNode.Attributes["Key"].Value].Update(childNode.Attributes["Key"].Value, childNode.Attributes["Value"].Value); } } } } else if (node.Name == "Attribute") { if (!this.Attributes.ContainsKey(node.Attributes["Key"].Value)) { IAzManAttribute <IAzManStore> newStoreAttribute = this.CreateAttribute(node.Attributes["Key"].Value, node.Attributes["Value"].Value); } else { this.Attributes[node.Attributes["Key"].Value].Update(node.Attributes["Key"].Value, node.Attributes["Value"].Value); } } if (node.Name == "Permissions") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Managers") { foreach (XmlNode childChildNode in childNode.ChildNodes) { if (childChildNode.Name == "Manager") { this.GrantAccessAsManager(childChildNode.Attributes["SqlUserOrRole"].Value); } } } else if (childNode.Name == "Users") { foreach (XmlNode childChildNode in childNode.ChildNodes) { if (childChildNode.Name == "User") { this.GrantAccessAsUser(childChildNode.Attributes["SqlUserOrRole"].Value); } } } else if (childNode.Name == "Readers") { foreach (XmlNode childChildNode in childNode.ChildNodes) { if (childChildNode.Name == "Reader") { this.GrantAccessAsReader(childChildNode.Attributes["SqlUserOrRole"].Value); } } } } } if (node.Name == "StoreGroups") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "StoreGroup") { GroupType groupType = GroupType.Basic; if (childNode.Attributes["GroupType"].Value == GroupType.LDapQuery.ToString()) { groupType = GroupType.LDapQuery; } IAzManStoreGroup storeGroup = null; string sid = null; if (this.StoreGroups.ContainsKey(childNode.Attributes["Name"].Value)) { storeGroup = this.StoreGroups[childNode.Attributes["Name"].Value]; sid = storeGroup.SID.StringValue; //Change Store Group SID MergeUtilities.changeSid(childNode.OwnerDocument.DocumentElement, childNode.Attributes["Sid"].Value, sid); } else { sid = SqlAzManSID.NewSqlAzManSid().StringValue; storeGroup = this.CreateStoreGroup(new SqlAzManSID(sid), childNode.Attributes["Name"].Value, childNode.Attributes["Description"].Value, childNode.Attributes["LDAPQuery"].Value, groupType); //Change Store Group SID MergeUtilities.changeSid(childNode.OwnerDocument.DocumentElement, childNode.Attributes["Sid"].Value, sid); } //newStoreGroup.ImportChildren(childNode, includeWindowsUsersAndGroups, includeAuthorizations); } } } else if (node.Name == "StoreGroup") { GroupType groupType = GroupType.Basic; if (node.Attributes["GroupType"].Value == GroupType.LDapQuery.ToString()) { groupType = GroupType.LDapQuery; } IAzManStoreGroup storeGroup = null; string sid = null; if (this.StoreGroups.ContainsKey(node.Attributes["Name"].Value)) { storeGroup = this.StoreGroups[node.Attributes["Name"].Value]; sid = storeGroup.SID.StringValue; //Change Store Group SID MergeUtilities.changeSid(node.OwnerDocument.DocumentElement, node.Attributes["Sid"].Value, sid); } else { sid = SqlAzManSID.NewSqlAzManSid().StringValue; storeGroup = this.CreateStoreGroup(new SqlAzManSID(sid), node.Attributes["Name"].Value, node.Attributes["Description"].Value, node.Attributes["LDAPQuery"].Value, groupType); //Change Store Group SID MergeUtilities.changeSid(node.OwnerDocument.DocumentElement, node.Attributes["Sid"].Value, sid); } //newStoreGroup.ImportChildren(node, includeWindowsUsersAndGroups, includeAuthorizations); } } //Create Applications & Store Group Members foreach (XmlNode node in xmlNode.ChildNodes) { System.Windows.Forms.Application.DoEvents(); if (node.Name == "Applications") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Application") { IAzManApplication newApplication = this.Applications.ContainsKey(childNode.Attributes["Name"].Value) ? this.Applications[childNode.Attributes["Name"].Value] : this.CreateApplication(childNode.Attributes["Name"].Value, childNode.Attributes["Description"].Value); newApplication.ImportChildren(childNode, includeWindowsUsersAndGroups, includeDBUsers, includeAuthorizations, mergeOptions); } } } else if (node.Name == "Application") { IAzManApplication newApplication = this.Applications.ContainsKey(node.Attributes["Name"].Value) ? this.Applications[node.Attributes["Name"].Value] : this.CreateApplication(node.Attributes["Name"].Value, node.Attributes["Description"].Value); newApplication.ImportChildren(node, includeWindowsUsersAndGroups, includeDBUsers, includeAuthorizations, mergeOptions); } else if (node.Name == "StoreGroups") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "StoreGroup") { GroupType groupType = GroupType.Basic; if (childNode.Attributes["GroupType"].Value == GroupType.LDapQuery.ToString()) { groupType = GroupType.LDapQuery; } if (groupType == GroupType.Basic) { IAzManStoreGroup newStoreGroup = this.StoreGroups[childNode.Attributes["Name"].Value]; newStoreGroup.ImportChildren(childNode, includeWindowsUsersAndGroups, includeDBUsers, includeAuthorizations, mergeOptions); } } } } else if (node.Name == "StoreGroup") { GroupType groupType = GroupType.Basic; if (node.Attributes["GroupType"].Value == GroupType.LDapQuery.ToString()) { groupType = GroupType.LDapQuery; } if (groupType == GroupType.Basic) { IAzManStoreGroup newStoreGroup = this.StoreGroups[node.Attributes["Name"].Value]; newStoreGroup.ImportChildren(node, includeWindowsUsersAndGroups, includeDBUsers, includeAuthorizations, mergeOptions); } } } this.applications = null; //Force refresh }
/// <summary> /// Imports the specified XML reader. /// </summary> /// <param name="xmlNode">The XML node.</param> /// <param name="includeWindowsUsersAndGroups">if set to <c>true</c> [include windows users and groups].</param> /// <param name="includeDBUsers">if set to <c>true</c> [include DB users].</param> /// <param name="includeAuthorizations">if set to <c>true</c> [include authorizations].</param> /// <param name="mergeOptions">The merge options.</param> public void ImportChildren(XmlNode xmlNode, bool includeWindowsUsersAndGroups, bool includeDBUsers, bool includeAuthorizations, SqlAzManMergeOptions mergeOptions) { List<IAzManAuthorization> importedAuthorizations = new List<IAzManAuthorization>(); foreach (XmlNode node in xmlNode.ChildNodes) { if (node.Name == "Attributes") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Attribute") { if (!this.Attributes.ContainsKey(childNode.Attributes["Key"].Value)) { IAzManAttribute<IAzManItem> newItemAttribute = this.CreateAttribute(childNode.Attributes["Key"].Value, childNode.Attributes["Value"].Value); } } } } else if (node.Name == "Attribute") { if (!this.Attributes.ContainsKey(node.Attributes["Key"].Value)) { IAzManAttribute<IAzManItem> newItemAttribute = this.CreateAttribute(node.Attributes["Key"].Value, node.Attributes["Value"].Value); } } System.Windows.Forms.Application.DoEvents(); if (node.Name == "BizRule") { string sLang = node.Attributes["BizRuleSourceLanguage"].Value; NetSqlAzMan.BizRuleSourceLanguage lang = NetSqlAzMan.BizRuleSourceLanguage.CSharp; if (String.Compare(sLang, NetSqlAzMan.BizRuleSourceLanguage.VBNet.ToString(), true) == 0) { lang = NetSqlAzMan.BizRuleSourceLanguage.VBNet; } string source = node.InnerText; this.ReloadBizRule(source, lang); } if (node.Name == "Member") { IAzManItem member = this.application.GetItem(node.Attributes["Name"].Value); if (!this.Members.ContainsKey(member.Name)) this.AddMember(member); } else if (node.Name == "Members") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Member") { IAzManItem member = this.application.GetItem(childNode.Attributes["Name"].Value); if (!this.Members.ContainsKey(member.Name)) this.AddMember(member); } } } else if (includeAuthorizations && node.Name == "Authorizations") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "Authorization") { WhereDefined sidWhereDefined; switch (childNode.Attributes["SidWhereDefined"].Value) { case "Application": sidWhereDefined = WhereDefined.Application; break; case "LDAP": sidWhereDefined = WhereDefined.LDAP; break; case "Local": sidWhereDefined = WhereDefined.Local; break; case "Store": sidWhereDefined = WhereDefined.Store; break; case "Database": sidWhereDefined = WhereDefined.Database; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("WhereDefined attribute not valid."); } WhereDefined ownerSidWhereDefined; switch (childNode.Attributes["OwnerSidWhereDefined"].Value) { case "Application": ownerSidWhereDefined = WhereDefined.Application; break; case "LDAP": ownerSidWhereDefined = WhereDefined.LDAP; break; case "Local": ownerSidWhereDefined = WhereDefined.Local; break; case "Store": ownerSidWhereDefined = WhereDefined.Store; break; case "Database": ownerSidWhereDefined = WhereDefined.Database; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("OwnerSidWhereDefined attribute not valid."); } AuthorizationType authorizationType; switch (childNode.Attributes["AuthorizationType"].Value) { case "Allow": authorizationType = AuthorizationType.Allow; break; case "AllowWithDelegation": authorizationType = AuthorizationType.AllowWithDelegation; break; case "Deny": authorizationType = AuthorizationType.Deny; break; case "Neutral": authorizationType = AuthorizationType.Neutral; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("AuthorizationType attribute not valid."); } DateTime? validFrom = null; DateTime? validTo = null; DateTime app; if (DateTime.TryParse(childNode.Attributes["ValidFrom"].Value, out app)) validFrom = app; if (DateTime.TryParse(childNode.Attributes["ValidTo"].Value, out app)) validTo = app; if (includeWindowsUsersAndGroups || !includeWindowsUsersAndGroups && sidWhereDefined != WhereDefined.LDAP && sidWhereDefined != WhereDefined.Local && this.application.Store.Storage.Mode != NetSqlAzManMode.Developer || includeDBUsers && sidWhereDefined == WhereDefined.Database || sidWhereDefined == WhereDefined.Store || sidWhereDefined == WhereDefined.Application) { IAzManSid authSid = new SqlAzManSID(childNode.Attributes["Sid"].Value, sidWhereDefined == WhereDefined.Database); IAzManSid ownerSid = new SqlAzManSID(childNode.Attributes["Owner"].Value, sidWhereDefined == WhereDefined.Database); IAzManAuthorization authorization = null; if (MergeUtilities.IsOn(mergeOptions, SqlAzManMergeOptions.OverwritesExistingItemAuthorization)) { authorization = this.CreateAuthorization(ownerSid, ownerSidWhereDefined, authSid, sidWhereDefined, authorizationType, validFrom, validTo); importedAuthorizations.Add(authorization); } else if (MergeUtilities.IsOn(mergeOptions, SqlAzManMergeOptions.CreatesNewItemAuthorizations)) { bool alreadyExists = false; foreach (var auth in this.GetAuthorizations(ownerSid, authSid)) { if (auth.ValidFrom == validFrom && auth.ValidTo == validTo && auth.AuthorizationType == authorizationType) { alreadyExists = true; break; } } if (!alreadyExists) { authorization = this.CreateAuthorization(ownerSid, ownerSidWhereDefined, authSid, sidWhereDefined, authorizationType, validFrom, validTo); importedAuthorizations.Add(authorization); } } if (authorization != null) authorization.ImportChildren(childNode, includeWindowsUsersAndGroups, includeDBUsers, includeAuthorizations, mergeOptions); } } } } } //Delete missing item Authorizations if (MergeUtilities.IsOn(mergeOptions, SqlAzManMergeOptions.DeleteMissingItemAuthorizations)) { foreach (var auth in this.GetAuthorizations()) { bool exists = false; foreach (var iauth in importedAuthorizations) { if (this.areEquals(auth, iauth)) { exists = true; break; } } if (!exists) { auth.Delete(); } } } }
/// <summary> /// Imports the specified XML reader. /// </summary> /// <param name="xmlNode">The XML node.</param> /// <param name="includeWindowsUsersAndGroups">if set to <c>true</c> [include windows users and groups].</param> /// <param name="includeDBUsers">if set to <c>true</c> [include DB users].</param> /// <param name="includeAuthorizations">if set to <c>true</c> [include authorizations].</param> /// <param name="mergeOptions">The merge options.</param> public void ImportChildren(XmlNode xmlNode, bool includeWindowsUsersAndGroups, bool includeDBUsers, bool includeAuthorizations, SqlAzManMergeOptions mergeOptions) { foreach (XmlNode node in xmlNode.ChildNodes) { if (node.Name == "StoreGroupMembers") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "StoreGroupMember") { WhereDefined whereDefined; switch (childNode.Attributes["WhereDefined"].Value) { case "Application": whereDefined = WhereDefined.Application; break; case "LDAP": whereDefined = WhereDefined.LDAP; break; case "Local": whereDefined = WhereDefined.Local; break; case "Store": whereDefined = WhereDefined.Store; break; case "Database": whereDefined = WhereDefined.Database; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("WhereDefined attribute valid"); } bool isMember = false; if (childNode.Attributes["IsMember"].Value == "True") { isMember = true; } if (includeWindowsUsersAndGroups || !includeWindowsUsersAndGroups && whereDefined != WhereDefined.LDAP && whereDefined != WhereDefined.Local && this.Store.Storage.Mode != NetSqlAzManMode.Developer || includeDBUsers && whereDefined == WhereDefined.Database || whereDefined == WhereDefined.Store || whereDefined == WhereDefined.Application) { IAzManSid sid = new SqlAzManSID(childNode.Attributes["Sid"].Value, whereDefined == WhereDefined.Database); if (this.Members.Where(m => m.Key.StringValue == sid.StringValue).Count() == 0) { this.CreateStoreGroupMember(sid, whereDefined, isMember); } } } } } else if (node.Name == "StoreGroupMember") { WhereDefined whereDefined; switch (node.Attributes["WhereDefined"].Value) { case "Application": whereDefined = WhereDefined.Application; break; case "LDAP": whereDefined = WhereDefined.LDAP; break; case "Local": whereDefined = WhereDefined.Local; break; case "Store": whereDefined = WhereDefined.Store; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("WhereDefined attribute not valid."); } bool isMember = false; if (node.Attributes["IsMember"].Value == "True") { isMember = true; } if (includeWindowsUsersAndGroups || !includeWindowsUsersAndGroups && whereDefined != WhereDefined.LDAP && whereDefined != WhereDefined.Local && this.Store.Storage.Mode != NetSqlAzManMode.Developer || whereDefined == WhereDefined.Store || whereDefined == WhereDefined.Application) { IAzManSid sid = new SqlAzManSID(node.Attributes["Sid"].Value, whereDefined == WhereDefined.Database); if (this.Members.Where(m => m.Key.StringValue == sid.StringValue).Count() == 0) { this.CreateStoreGroupMember(sid, whereDefined, isMember); } } } } }
/// <summary> /// Create a Full Storage through .NET code /// </summary> private void CreateFullStorage() { // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Administrators //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); //Open Storage Connection storage.OpenConnection(); //Begin a new Transaction storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); //Create a new Store IAzManStore newStore = storage.CreateStore("My Store", "Store description"); //Create a new Basic StoreGroup IAzManStoreGroup newStoreGroup = newStore.CreateStoreGroup(SqlAzManSID.NewSqlAzManSid(), "My Store Group", "Store Group Description", String.Empty, GroupType.Basic); //Retrieve current user SID IAzManSid mySid = new SqlAzManSID(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User); //Add myself as sid of "My Store Group" IAzManStoreGroupMember storeGroupMember = newStoreGroup.CreateStoreGroupMember(mySid, WhereDefined.Local, true); //Create a new Application IAzManApplication newApp = newStore.CreateApplication("New Application", "Application description"); //Create a new Role IAzManItem newRole = newApp.CreateItem("New Role", "Role description", ItemType.Role); //Create a new Task IAzManItem newTask = newApp.CreateItem("New Task", "Task description", ItemType.Task); //Create a new Operation IAzManItem newOp = newApp.CreateItem("New Operation", "Operation description", ItemType.Operation); //Add "New Operation" as a sid of "New Task" newTask.AddMember(newOp); //Add "New Task" as a sid of "New Role" newRole.AddMember(newTask); //Create an authorization for myself on "New Role" IAzManAuthorization auth = newRole.CreateAuthorization(mySid, WhereDefined.Local, mySid, WhereDefined.Local, AuthorizationType.AllowWithDelegation, null, null); //Create a custom attribute IAzManAttribute<IAzManAuthorization> attr = auth.CreateAttribute("New Key", "New Value"); //Create an authorization for DB User "Andrea" on "New Role" IAzManAuthorization auth2 = newRole.CreateAuthorization(mySid, WhereDefined.Local, storage.GetDBUser("Andrea").CustomSid, WhereDefined.Local, AuthorizationType.AllowWithDelegation, null, null); //Commit transaction storage.CommitTransaction(); //Close connection storage.CloseConnection(); }
/// <summary> /// Remove Authorization Delegate /// </summary> private void RemoveDelegate() { // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Users //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); IAzManStore mystore = storage.GetStore("My Store"); //or storage["My Store"] IAzManApplication myapp = mystore.GetApplication("My Application"); IAzManItem myop = myapp.GetItem("My Operation"); //Retrieve current user identity (delegating user) WindowsIdentity userIdentity = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()); //for Windows Applications //WindowsIdentity userIdentity = this.Request.LogonUserIdentity; //for ASP.NET Applications //Retrieve delegate user Login NTAccount delegateUserLogin = new NTAccount("DOMAIN", "delegateuseraccount"); //Retrieve delegate user SID SecurityIdentifier delegateSID = (SecurityIdentifier)delegateUserLogin.Translate(typeof(SecurityIdentifier)); IAzManSid delegateNetSqlAzManSID = new SqlAzManSID(delegateSID); //Estabilish delegate authorization (only Allow or Deny) RestrictedAuthorizationType delegateAuthorization = RestrictedAuthorizationType.Allow; //Remove delegate and all custom attributes myop.DeleteDelegateAuthorization(userIdentity, delegateNetSqlAzManSID, delegateAuthorization); }
/// <summary> /// Creates the delegation [Windows Users]. /// </summary> /// <param name="delegatingUser">The delegating user.</param> /// <param name="delegateUser">The delegate user.</param> /// <param name="authorizationType">Type of the authorization.</param> /// <param name="validFrom">The valid from.</param> /// <param name="validTo">The valid to.</param> /// <returns>IAzManAuthorization</returns> public IAzManAuthorization CreateDelegateAuthorization(WindowsIdentity delegatingUser, IAzManSid delegateUser, RestrictedAuthorizationType authorizationType, DateTime? validFrom, DateTime? validTo) { //DateTime range check if (validFrom.HasValue && validTo.HasValue) { if (validFrom.Value > validTo.Value) throw new InvalidOperationException("ValidFrom cannot be greater then ValidTo if supplied."); } string delegatedName; bool isLocal; DirectoryServicesUtils.GetMemberInfo(delegateUser.StringValue, out delegatedName, out isLocal); //Check if user has AllowWithDelegation permission on this Item. if (this.CheckAccess(delegatingUser, DateTime.Now) != AuthorizationType.AllowWithDelegation) { string msg = String.Format("Create Delegate permission deny for user '{0}' ({1}) to user '{2}' ({3}).", delegatingUser.Name, delegatingUser.User.Value, delegatedName, delegateUser.StringValue); throw new SqlAzManException(msg); } WhereDefined sidWhereDefined = isLocal ? WhereDefined.Local : WhereDefined.LDAP; if (this.application.Store.Storage.Mode == NetSqlAzManMode.Administrator && sidWhereDefined == WhereDefined.Local) { throw new SqlAzManException("Cannot create a Delegate defined on local in Administrator Mode"); } IAzManSid owner = new SqlAzManSID(delegatingUser.User.Value); string ownerName; bool ownerIsLocal; DirectoryServicesUtils.GetMemberInfo(delegatingUser.User.Value, out ownerName, out ownerIsLocal); WhereDefined ownerSidWhereDefined = ownerIsLocal ? WhereDefined.Local : WhereDefined.LDAP; int? authorizationId = 0; this.db.CreateDelegate(this.itemId, owner.BinaryValue, (byte)ownerSidWhereDefined, delegateUser.BinaryValue, (byte)sidWhereDefined, (byte)authorizationType, (validFrom.HasValue ? validFrom.Value : new DateTime?()), (validTo.HasValue ? validTo.Value : new DateTime?()), ref authorizationId); IAzManAuthorization result = new SqlAzManAuthorization(this.db, this, authorizationId.Value, owner, ownerSidWhereDefined, delegateUser, sidWhereDefined, (AuthorizationType)authorizationType, validFrom, validTo, this.ens); this.raiseDelegateCreated(this, result); if (this.ens != null) this.ens.AddPublisher(result); return result; }
/// <summary> /// Imports the specified XML reader. /// </summary> /// <param name="xmlNode">The XML node.</param> /// <param name="includeWindowsUsersAndGroups">if set to <c>true</c> [include windows users and groups].</param> /// <param name="includeDBUsers">if set to <c>true</c> [include DB users].</param> /// <param name="includeAuthorizations">if set to <c>true</c> [include authorizations].</param> /// <param name="mergeOptions">The merge options.</param> public void ImportChildren(XmlNode xmlNode, bool includeWindowsUsersAndGroups, bool includeDBUsers, bool includeAuthorizations, SqlAzManMergeOptions mergeOptions) { foreach (XmlNode node in xmlNode.ChildNodes) { if (node.Name == "ApplicationGroupMembers") { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "ApplicationGroupMember") { WhereDefined whereDefined; switch (childNode.Attributes["WhereDefined"].Value) { case "Application": whereDefined = WhereDefined.Application; break; case "LDAP": whereDefined = WhereDefined.LDAP; break; case "Local": whereDefined = WhereDefined.Local; break; case "Store": whereDefined = WhereDefined.Store; break; case "Database": whereDefined = WhereDefined.Database; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("WhereDefined attribute valid"); } bool isMember = false; if (childNode.Attributes["IsMember"].Value == "True") { isMember = true; } if (includeWindowsUsersAndGroups || !includeWindowsUsersAndGroups && whereDefined != WhereDefined.LDAP && whereDefined != WhereDefined.Local && this.application.Store.Storage.Mode != NetSqlAzManMode.Developer || includeDBUsers && whereDefined == WhereDefined.Database || whereDefined == WhereDefined.Store || whereDefined == WhereDefined.Application) { IAzManSid sid = new SqlAzManSID(childNode.Attributes["Sid"].Value, whereDefined == WhereDefined.Database); if (this.Members.Where(m => m.Key.StringValue == sid.StringValue).Count() == 0) this.CreateApplicationGroupMember(sid, whereDefined, isMember); } } } } else if (node.Name == "ApplicationGroupMember") { WhereDefined whereDefined; switch (node.Attributes["WhereDefined"].Value) { case "Application": whereDefined = WhereDefined.Application; break; case "LDAP": whereDefined = WhereDefined.LDAP; break; case "Local": whereDefined = WhereDefined.Local; break; case "Store": whereDefined = WhereDefined.Store; break; case "Database": whereDefined = WhereDefined.Database; break; default: throw new System.Xml.Schema.XmlSchemaValidationException("WhereDefined attribute not valid."); } bool isMember = false; if (node.Attributes["IsMember"].Value == "True") { isMember = true; } if (includeWindowsUsersAndGroups || !includeWindowsUsersAndGroups && whereDefined != WhereDefined.LDAP && whereDefined != WhereDefined.Local && this.application.Store.Storage.Mode != NetSqlAzManMode.Developer || includeDBUsers && whereDefined == WhereDefined.Database || whereDefined == WhereDefined.Store || whereDefined == WhereDefined.Application) { IAzManSid sid = new SqlAzManSID(node.Attributes["Sid"].Value, whereDefined == WhereDefined.Database); if (this.Members.Where(m => m.Key.StringValue == sid.StringValue).Count() == 0) this.CreateApplicationGroupMember(sid, whereDefined, isMember); } } } }
/// <summary> /// SIDs to int32. /// </summary> /// <param name="n">The n.</param> /// <returns></returns> public static SqlAzManSID SIDToInt32(int n) { return(new SqlAzManSID(SqlAzManSID.GetBytesFromInt32(n), true)); }
/// <summary> /// Removes the delegate [Windows Users]. /// </summary> /// <param name="delegatingUser">The delegating user.</param> /// <param name="delegateUser">The delegate user.</param> /// <param name="authorizationType">Type of the authorization.</param> public void DeleteDelegateAuthorization(WindowsIdentity delegatingUser, IAzManSid delegateUser, RestrictedAuthorizationType authorizationType) { string delegatedName; bool isLocal; DirectoryServicesUtils.GetMemberInfo(delegateUser.StringValue, out delegatedName, out isLocal); //Check if user has AllowWithDelegation permission on this Item. if (this.CheckAccess(delegatingUser, DateTime.Now) != AuthorizationType.AllowWithDelegation) { string msg = String.Format("Remove Delegate permission deny for user '{0}' ({1}) to user '{2}' ({3}).", delegatingUser.Name, delegatingUser.User.Value, delegatedName, delegateUser.StringValue); throw new SqlAzManException(msg); } WhereDefined memberWhereDefined = isLocal ? WhereDefined.Local : WhereDefined.LDAP; if (this.application.Store.Storage.Mode == NetSqlAzManMode.Administrator && memberWhereDefined == WhereDefined.Local) { throw new SqlAzManException("Cannot remove Delegates defined on local in Administrator Mode"); } IAzManSid owner = new SqlAzManSID(delegatingUser.User.Value); string ownerName; bool ownerIsLocal; DirectoryServicesUtils.GetMemberInfo(delegatingUser.User.Value, out ownerName, out ownerIsLocal); WhereDefined ownerSidWhereDefined = ownerIsLocal ? WhereDefined.Local : WhereDefined.LDAP; foreach (IAzManAuthorization auth in this.GetAuthorizations(owner, delegateUser)) { if ((byte)auth.AuthorizationType == (byte)authorizationType) { int affectedRecords = db.DeleteDelegate(auth.AuthorizationId, owner.BinaryValue); if (affectedRecords != 0) this.raiseDelegateDeleted(this, new SqlAzManSID(delegatingUser.User.Value), delegateUser, authorizationType); } } }