protected void btnBrowseDBUser_Click(object sender, EventArgs e)
 {
     try
     {
         IAzManDBUser[] selectedDBUsers = (IAzManDBUser[])this.Session["selectedDBUsers"];
         if (selectedDBUsers.Length > 1)
         {
             this.ShowError("Please choose only one DB User");
         }
         if (selectedDBUsers.Length == 1)
         {
             this.wid = null;
             this.dbuser = selectedDBUsers[0];
             this.txtDBUser.Text = this.dbuser.UserName;
         }
         this.rbDBUser.Checked = true;
         this.txtWindowsUser.Text = String.Empty;
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message);
     }
     finally
     {
         this.Session["selectedDBUsers"] = null;
     }
 }
Exemple #2
0
        /// <summary>
        /// Check Access from your Application [FOR Windows Users ONLY].
        /// </summary>
        /// <param name="dbUserName">DB Username</param>
        private void CheckAccessPermissionsForDBUsers(string dbUserName)
        {
            // REMBER:
            // Modify dbo.GetDBUsers Table-Function to customize DB User list.
            // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Readers
            //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);
            //Retrieve DB User identity from dbo.GetDBUsers Table-Function
            IAzManDBUser      dbUser = storage.GetDBUser(dbUserName);
            AuthorizationType auth   = storage.CheckAccess("My Store", "My Application", "My Operation", dbUser, DateTime.Now, true);

            switch (auth)
            {
            case AuthorizationType.AllowWithDelegation:
                //Yes, I can ... and I can delegate
                break;

            case AuthorizationType.Allow:
                //Yes, I can
                break;

            case AuthorizationType.Neutral:
            case AuthorizationType.Deny:
                //No, I cannot
                break;
            }
        }
 private void btnBrowseDBUser_Click(object sender, EventArgs e)
 {
     try
     {
         this.rbDBUser.Checked = true;
         frmDBUsersList frm = new frmDBUsersList();
         frm.application = this.application;
         DialogResult dr = frm.ShowDialog(this);
         if (dr == DialogResult.OK)
         {
             if (frm.selectedDBUsers.Length > 1)
             {
                 this.ShowError(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg80"), Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
             }
             if (frm.selectedDBUsers.Length == 1)
             {
                 this.wid            = null;
                 this.dbuser         = frm.selectedDBUsers[0];
                 this.txtDBUser.Text = this.dbuser.UserName;
             }
         }
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
     }
     finally
     {
         this.FormValidate();
     }
 }
        private void SaveRecord()
        {
            _Storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted);
            foreach (ListViewItem item in lvwStoreGroups.Items)
            {
                #region update checked items only, not selected
                if (item.Checked)
                {
                    _SelectedItems.Add(item);

                    #region 立即 save
                    IAzManDBUser        dbUser = _Storage.GetDBUser(item.SubItems[0].Text);
                    IAzManAuthorization auth   = _AuthItem.CreateAuthorization(
                        new SqlAzManSID(dbUser.CustomSid.ToString(), this._CurrentOwnerSidWhereDefined == WhereDefined.Database),
                        this._CurrentOwnerSidWhereDefined,
                        new SqlAzManSID(dbUser.CustomSid.ToString(), true),
                        WhereDefined.Database,
                        AuthorizationType.Neutral,
                        null,
                        null);
                    #endregion
                }
                #endregion
            }
            _Storage.CommitTransaction();
        }
        private void btnBrowseWindowsUser_Click(object sender, EventArgs e)
        {
            string userName = String.Empty;

            try
            {
                this.rbWindowsUser.Checked = true;
                ADObject[] res = DirectoryServicesUtils.ADObjectPickerShowDialog(this, false, true, false);
                /*Application.DoEvents();*/
                if (res != null)
                {
                    if (res.Length > 1)
                    {
                        this.ShowError(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg20"), Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
                    }
                    if (res.Length == 1)
                    {
                        userName = res[0].UPN;
                        this.wid = new WindowsIdentity(userName);
                        this.txtWindowsUser.Text = userName;
                        this.dbuser = null;
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
            }
            finally
            {
                this.FormValidate();
            }
        }
Exemple #6
0
        private void SaveRecord()
        {
            try
            {
                _Storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted);
                foreach (ListViewItem item in lvwStoreGroups.Items)
                {
                    #region update checked items only, not selected
                    if (item.Checked)
                    {
                        _SelectedItems.Add(item);

                        #region 立即 save
                        IAzManDBUser dbUser = _Storage.GetDBUser(item.SubItems[0].Text);
                        _StoreGroup.CreateStoreGroupMember(dbUser.CustomSid, WhereDefined.Database, _IsMember);
                        #endregion
                    }
                    #endregion
                }
                _Storage.CommitTransaction();
            }
            catch (Exception ex)
            {
                _Storage.RollBackTransaction();
                throw (ex);
            }
        }
Exemple #7
0
 protected void btnBrowseDBUser_Click(object sender, EventArgs e)
 {
     try
     {
         IAzManDBUser[] selectedDBUsers = (IAzManDBUser[])this.Session["selectedDBUsers"];
         if (selectedDBUsers.Length > 1)
         {
             this.ShowError("Please choose only one DB User");
         }
         if (selectedDBUsers.Length == 1)
         {
             this.wid            = null;
             this.dbuser         = selectedDBUsers[0];
             this.txtDBUser.Text = this.dbuser.UserName;
         }
         this.rbDBUser.Checked    = true;
         this.txtWindowsUser.Text = String.Empty;
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message);
     }
     finally
     {
         this.Session["selectedDBUsers"] = null;
     }
 }
 /// <summary>
 /// Determines whether [is in group] [the specified windows identity].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <returns>
 ///     <c>true</c> if [is in group] [the specified windows identity]; otherwise, <c>false</c>.
 /// </returns>
 public bool IsInGroup(IAzManDBUser dbUser)
 {
     if (dbUser == null)
     {
         throw new ArgumentNullException("dbUser");
     }
     return(this.isAMemberOfGroup(false, this.sid.BinaryValue, this.Store.Storage.Mode == NetSqlAzManMode.Developer, DirectoryServicesUtils.rootDsePath, dbUser.CustomSid.BinaryValue, 0));
 }
 /// <summary>
 /// Initializes the context.
 /// </summary>
 /// <param name="storageConnectionString">The storage connection string.</param>
 /// <param name="storeName">Name of the store.</param>
 /// <param name="applicationName">Name of the application.</param>
 /// <param name="dbUserIdentity">The db user identity.</param>
 /// <param name="useStorageCache">if set to <c>true</c> [use storage cache].</param>
 public NetSqlAzManAuthorizationContext(string storageConnectionString, string storeName, string applicationName, IAzManDBUser dbUserIdentity, bool useStorageCache)
 {
     this.StorageConnectionString = storageConnectionString;
     this.StoreName = storeName;
     this.ApplicationName = applicationName;
     this.DBUserIdentity = dbUserIdentity;
     this.UseStorageCache = useStorageCache;
 }
Exemple #10
0
 private void cmdCheckAccess_Click(object sender, EventArgs e)
 {
     if (txtUser.Tag != null)
     {
         _DbUser = (IAzManDBUser)txtUser.Tag;
         GetDetails(_DbUser);
     }
 }
        protected void Button2_Click(object sender, EventArgs e)
        {
            IAzManStorage       storage = new SqlAzManStorage("data source=(local);Initial Catalog=NetSqlAzManStorage;user id=sa;password="******"Andrea");
            UserPermissionCache cache   = new UserPermissionCache(storage, "Store Stress Test", "Application0", andrea, true, true);

            Session["cache"] = cache;
        }
Exemple #12
0
 protected void btnCheckAccessTest_Click(object sender, EventArgs e)
 {
     try
     {
         NTAccount nta            = (NTAccount)(this.Request.LogonUserIdentity.User.Translate(typeof(NTAccount)));
         string    currentUpnName = nta.Value;
         if (currentUpnName.IndexOf('\\') != -1)
         {
             currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1);
         }
         if (String.IsNullOrEmpty(this.txtWindowsUser.Text) && this.rbWindowsUser.Checked)
         {
             this.txtWindowsUser.Text = currentUpnName;
         }
         if (this.rbWindowsUser.Checked)
         {
             this.dbuser = null;
             if (this.txtWindowsUser.Text == currentUpnName)
             {
                 //Current Windows User
                 this.wid = this.Request.LogonUserIdentity;
             }
             else
             {
                 //Kerberos Protocol Transition
                 this.wid = new WindowsIdentity(this.txtWindowsUser.Text);
             }
         }
         else if (this.rbDBUser.Checked && !String.IsNullOrEmpty(this.txtDBUser.Text))
         {
             this.wid    = null;
             this.dbuser = this.application.GetDBUser(this.txtDBUser.Text);
         }
         this.txtDetails.Text = String.Empty;
         this.WriteLineDetailMessage("Check Access Test started at " + DateTime.Now.ToString());
         this.WriteLineDetailMessage(String.Empty);
         this.WriteIdentityDetails();
         this.WriteLineDetailMessage(String.Empty);
         this.WriteDetailMessage("Building Items Hierarchy ...");
         this.RefreshItemsHierarchy();
         this.WriteLineDetailMessage("Done.");
         this.WriteLineDetailMessage(String.Empty);
         TreeNode applicationTreeNode = this.itemsHierarchyTreeView.Nodes[0].ChildNodes[0].ChildNodes[0];
         foreach (TreeNode itemTreeNode in applicationTreeNode.ChildNodes)
         {
             this.checkAccessTest(itemTreeNode);
         }
         this.WriteLineDetailMessage(String.Empty);
         this.WriteLineDetailMessage("Check Access Test finished at " + DateTime.Now.ToString());
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message);
     }
 }
Exemple #13
0
 /// <summary>
 /// Checks the Store access [FOR DB Users ONLY].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>
 /// [true] for access allowd, [false] otherwise.
 /// </returns>
 public bool CheckStoreAccess(IAzManDBUser dbUser, DateTime validFor, params KeyValuePair <string, object>[] contextParameters)
 {
     foreach (IAzManApplication application in this.GetApplications())
     {
         if (application.CheckApplicationAccess(dbUser, validFor, contextParameters) == true)
         {
             return(true);
         }
     }
     return(false);
 }
Exemple #14
0
 /// <summary>
 /// Constructor that builds a hierarchical menu based upon authorization right of the user
 /// in the given store.
 /// </summary>
 /// <param name="store">String that represents the store that the menu is built upon.</param>
 /// <param name="user">User name.</param>
 /// <param name="baseUrl">Base url for generated menu urls.</param>
 /// <param name="menuUrl">Base url for menu resolved.</param>
 /// <param name="displayFullMenu">Whether to display full menu</param>
 public PemsMenu(string store, string user, string baseUrl, string menuUrl, bool displayFullMenu)
 {
     _displayFullMenu = displayFullMenu;
     _storage         = new SqlAzManStorage(connectionString: ConfigurationManager.ConnectionStrings[Constants.Security.RbacConnectionStringName].ConnectionString);
     _dbUser          = _storage.GetDBUser(user);
     _baseUrl         = baseUrl;
     _store           = store;
     _menuUrl         = menuUrl;
     // Create the menu
     GetMenu();
 }
Exemple #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserPermissionCache"/> class.
 /// </summary>
 /// <param name="storage">The storage.</param>
 /// <param name="storeName">Name of the store.</param>
 /// <param name="applicationName">Name of the application.</param>
 /// <param name="dbUser">The db user.</param>
 /// <param name="retrieveAttributes">if set to <c>true</c> [retrieve attributes].</param>
 /// <param name="multiThreadBuild">if set to <c>true</c> [multi thread build].</param>
 /// <param name="contextParameters">The context parameters.</param>
 public UserPermissionCache(IAzManStorage storage, string storeName, string applicationName, IAzManDBUser dbUser, bool retrieveAttributes, bool multiThreadBuild, params KeyValuePair <string, object>[] contextParameters)
     : this(storage, storeName, applicationName, retrieveAttributes, contextParameters)
 {
     this.dbUser = dbUser;
     if (multiThreadBuild)
     {
         this.buildApplicationCacheMultiThread();
     }
     else
     {
         this.buildApplicationCache();
     }
 }
Exemple #16
0
        /// <summary>
        /// Gets the DB users.
        /// </summary>
        /// <returns></returns>
        public IAzManDBUser[] GetDBUsers()
        {
            var dtDBUsers = this.db.GetDBUsersEx(this.name, null, null, null);

            IAzManDBUser[] result = new IAzManDBUser[dtDBUsers.Rows.Count];
            int            i      = 0;

            foreach (DataRow row in dtDBUsers.Rows)
            {
                result[i++] = new SqlAzManDBUser(row);
            }
            return(result);
        }
Exemple #17
0
        private void GetDetails(IAzManDBUser dbUser)
        {
            txtDetails.Text = String.Format(@"
Check Access Test started at {0}

Identity Details:
Name: {1}Custom Sid: {2}
", DateTime.Now.ToString(), dbUser.UserName + "\t", dbUser.CustomSid);

            txtDetails.Text += "Member of these Store Groups:" + Environment.NewLine;

            foreach (IAzManStoreGroup storeGroup in _Application.Store.GetStoreGroups())
            {
                if (storeGroup.IsInGroup(dbUser))
                {
                    txtDetails.Text += storeGroup.Name + Environment.NewLine;
                }
            }

            txtDetails.Text += "Member of these Application Groups:" + Environment.NewLine;
            foreach (IAzManApplicationGroup applicationGroup in _Application.GetApplicationGroups())
            {
                if (applicationGroup.IsInGroup(dbUser))
                {
                    txtDetails.Text += applicationGroup.Name + Environment.NewLine;
                }
            }

            #region Load Hierarchy();
            txtDetails.Text += Environment.NewLine;
            txtDetails.Text += "Building Items Hierarchy ...";

            tvwResults.Nodes.Clear();
            BuildApplicationsTreeView();
            tvwResults.ExpandAll();

            txtDetails.Text += "Done." + Environment.NewLine + Environment.NewLine;
            #endregion

            #region Check Access
            TreeNode applicationTreeNode = tvwResults.Nodes[0].Nodes[0];
            foreach (TreeNode itemTreeNode in applicationTreeNode.Nodes)
            {
                CheckNodeAccess(itemTreeNode);
            }

            txtDetails.Text += Environment.NewLine;
            txtDetails.Text += "Check Access Test finished at " + DateTime.Now.ToString();
            #endregion
        }
Exemple #18
0
 private void rbCheckedChanged()
 {
     if (this.rbWindowsUser.Checked)
     {
         this.txtWindowsUser.Enabled = true;
         this.txtDBUser.Enabled      = false;
     }
     else
     {
         this.txtDBUser.Enabled      = false;
         this.txtWindowsUser.Enabled = false;
     }
     this.txtWindowsUser.Text = String.Empty;
     this.txtDBUser.Text      = String.Empty;
     this.cache  = null;
     this.wid    = null;
     this.dbuser = null;
 }
        private DataRow AddDBUserDataRow(IAzManDBUser member)
        {
            DataRow dr = this.dtAuthorizations.NewRow();

            dr["Owner"]                 = this.currentOwnerName;
            dr["OwnerSID"]              = this.currentOwnerSid;
            dr["Name"]                  = member.UserName;
            dr["MemberType"]            = this.RenderMemberType(MemberType.DatabaseUser, member.CustomSid);
            dr["MemberTypeEnum"]        = MemberType.DatabaseUser;
            dr["ObjectSID"]             = member.CustomSid.StringValue;
            dr["WhereDefined"]          = WhereDefined.Database.ToString();
            dr["WhereDefinedEnum"]      = WhereDefined.Database;
            dr["AuthorizationType"]     = this.RenderAuthorizationType(AuthorizationType.Neutral);
            dr["AuthorizationTypeEnum"] = AuthorizationType.Neutral;
            dr["ValidFrom"]             = DBNull.Value;
            dr["ValidTo"]               = DBNull.Value;
            this.dtAuthorizations.Rows.Add(dr);
            return(dr);
        }
Exemple #20
0
        /// <summary>
        /// Retrive a complete Authorization for the current user and populate the string array
        /// from .NetSqlAzMan store
        /// </summary>
        /// <param name="userName">User name identifying the current user</param>
        /// <returns>Array of strings containing all of the permissions from .NetSqlAzMan store</returns>

        private bool CheckAccess(IAzManDBUser dbUser, string app, string role, IAzManStorage storage)
        {
            var result = false;
            //IAzManDBUser dbUser = storage.GetDBUser(dbUserName);
            AuthorizationType auth = storage.CheckAccess("CATS", app, role, dbUser, DateTime.Now, false);

            switch (auth)
            {
            case AuthorizationType.AllowWithDelegation:
            case AuthorizationType.Allow:
                result = true;
                break;

            case AuthorizationType.Neutral:
            case AuthorizationType.Deny:
                result = false;
                break;
            }
            return(result);
        }
 private void rbCheckedChanged()
 {
     if (this.rbWindowsUser.Checked)
     {
         this.txtWindowsUser.ReadOnly  = false;
         this.txtWindowsUser.BackColor = SystemColors.Window;
         this.txtDBUser.BackColor      = SystemColors.Control;
         this.txtWindowsUser.Text      = String.Empty;
     }
     else
     {
         this.txtWindowsUser.ReadOnly  = true;
         this.txtWindowsUser.BackColor = SystemColors.Control;
         this.txtDBUser.BackColor      = SystemColors.Window;
     }
     this.txtWindowsUser.Text = String.Empty;
     this.txtDBUser.Text      = String.Empty;
     this.cache  = null;
     this.wid    = null;
     this.dbuser = null;
 }
Exemple #22
0
        private void DBUserList_FormClosed(object sender, FormClosedEventArgs e)
        {
            var form = (DBUsersList)sender;

            if (form.SelectedItems != null)
            {
                if (form.SelectedItems.Count > 0)
                {
                    var item = form.SelectedItems[0];
                    if (item != null)
                    {
                        IAzManDBUser dbUser = _Application.GetDBUser(item.SubItems[0].Text);
                        txtUser.Tag  = dbUser;
                        txtUser.Text = dbUser.UserName;

                        txtDetails.Text = String.Empty;
                        tvwResults.Nodes.Clear();
                    }
                }
            }
        }
 private void rbCheckedChanged()
 {
     if (this.rbWindowsUser.Checked)
     {
         this.txtWindowsUser.ReadOnly = false;
         this.txtWindowsUser.BackColor = SystemColors.Window;
         this.txtDBUser.BackColor = SystemColors.Control;
         this.txtWindowsUser.Text = String.Empty;
     }
     else
     {
         this.txtWindowsUser.ReadOnly = true;
         this.txtWindowsUser.BackColor = SystemColors.Control;
         this.txtDBUser.BackColor = SystemColors.Window;
     }
     this.txtWindowsUser.Text = String.Empty;
     this.txtDBUser.Text = String.Empty;
     this.cache = null;
     this.wid = null;
     this.dbuser = null;
 }
 private void btnBrowseWindowsUser_Click(object sender, EventArgs e)
 {
     string userName = String.Empty;
     try
     {
         this.rbWindowsUser.Checked = true;
         ADObject[] res = DirectoryServicesUtils.ADObjectPickerShowDialog(this, false, true, false);
         /*Application.DoEvents();*/
         if (res != null)
         {
             if (res.Length > 1)
             {
                 this.ShowError(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg20"), Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
             }
             if (res.Length == 1)
             {
                 userName = res[0].UPN;
                 this.wid = new WindowsIdentity(userName);
                 this.txtWindowsUser.Text = userName;
                 this.dbuser = null;
             }
         }
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
     }
     finally
     {
         this.FormValidate();
     }
 }
        private void btnCheckAccessTest_Click(object sender, EventArgs e)
        {
            try
            {
                NTAccount nta = (NTAccount)(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User.Translate(typeof(NTAccount)));
                string currentUpnName = nta.Value;
                if (currentUpnName.IndexOf('\\') != -1)
                {
                    currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1);
                }
                if (this.rbWindowsUser.Checked && !String.IsNullOrEmpty(this.txtWindowsUser.Text))
                {
                    this.dbuser = null;
                    if (this.txtWindowsUser.Text == currentUpnName)
                    {
                        //Current Windows User
                        this.wid = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent());
                    }
                    else
                    {
                        //Kerberos Protocol Transition
                        this.wid = new WindowsIdentity(this.txtWindowsUser.Text);
                    }
                }
                else if (this.rbDBUser.Checked && !String.IsNullOrEmpty(this.txtDBUser.Text))
                {
                    this.wid = null;
                    this.dbuser = this.application.GetDBUser(this.txtDBUser.Text);
                }
                this.HourGlass(true);
                this.txtDetails.Text = String.Empty;
                this.btnCheckAccessTest.Enabled = this.btnClose.Enabled =
                    this.btnBrowseWindowsUser.Enabled = this.btnBrowseDBUser.Enabled =
                    this.rbWindowsUser.Enabled = this.rbDBUser.Enabled = false;
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg30") + " " + DateTime.Now.ToString());
                this.WriteLineDetailMessage(String.Empty);
                this.WriteIdentityDetails();
                this.WriteLineDetailMessage(String.Empty);
                this.WriteDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg40"));
                this.checkAccessTestTreeView.BeginUpdate();
                this.RefreshItemsHierarchy();
                this.checkAccessTestTreeView.EndUpdate();
                Application.DoEvents();
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("Done_Msg10"));
                this.WriteLineDetailMessage(String.Empty);
                TreeNode applicationTreeNode = this.checkAccessTestTreeView.Nodes[0].Nodes[0].Nodes[0];
                Boolean turboMode = this.application.Items.Count>50;
                Hashtable resultCache = new Hashtable();
                Hashtable attributesCache = new Hashtable();
                if (turboMode)
                    this.checkAccessTestTreeView.BeginUpdate();
                foreach (TreeNode itemTreeNode in applicationTreeNode.Nodes)
                {
                    this.checkAccessTest(itemTreeNode, turboMode, resultCache, attributesCache);
                }

                if (turboMode)
                    this.checkAccessTestTreeView.EndUpdate();
                this.WriteLineDetailMessage(String.Empty);
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg50") + " " + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
            }
            finally
            {
                this.btnCheckAccessTest.Enabled = this.btnClose.Enabled =
                    this.btnBrowseWindowsUser.Enabled = this.btnBrowseDBUser.Enabled =
                    this.rbWindowsUser.Enabled = this.rbDBUser.Enabled = true;
                this.HourGlass(false);
            }
        }
 private void rbCheckedChanged()
 {
     if (this.rbWindowsUser.Checked)
     {
         this.txtWindowsUser.Enabled = true;
         this.txtDBUser.Enabled = false;
     }
     else
     {
         this.txtDBUser.Enabled = false;
         this.txtWindowsUser.Enabled = false;
     }
     this.txtWindowsUser.Text = String.Empty;
     this.txtDBUser.Text = String.Empty;
     this.cache = null;
     this.wid = null;
     this.dbuser = null;
 }
Exemple #27
0
 /// <summary>
 /// Retrive a complete Authorization for the current user and populate the string array
 /// from .NetSqlAzMan store 
 /// </summary>
 /// <param name="userName">User name identifying the current user</param>
 /// <returns>Array of strings containing all of the permissions from .NetSqlAzMan store</returns>
 private bool CheckAccess(IAzManDBUser dbUser, string app, string role, IAzManStorage storage)
 {
     var result = false;
     //IAzManDBUser dbUser = storage.GetDBUser(dbUserName);
     AuthorizationType auth = storage.CheckAccess("CATS", app, role, dbUser, DateTime.Now, false);
     switch (auth)
     {
         case AuthorizationType.AllowWithDelegation:
         case AuthorizationType.Allow:
             result = true;
             break;
         case AuthorizationType.Neutral:
         case AuthorizationType.Deny:
             result = false;
             break;
     }
     return result;
 }
 private AuthorizationType internalCheckAccess(string StoreName, string ApplicationName, string ItemName, IAzManDBUser dbUser, DateTime ValidFor, bool OperationsOnly, bool retrieveAttributes, out List<KeyValuePair<string, string>> attributes, params KeyValuePair<string, object>[] contextParameters)
 {
     int userGroupsCount = 0;
     SqlConnection conn = new SqlConnection(this.db.Connection.ConnectionString);
     conn.Open();
     System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "dbo.netsqlazman_DirectCheckAccess";
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@STORENAME", StoreName);
     cmd.Parameters.AddWithValue("@APPLICATIONNAME", ApplicationName);
     cmd.Parameters.AddWithValue("@ITEMNAME", ItemName);
     cmd.Parameters.AddWithValue("@OPERATIONSONLY", OperationsOnly);
     cmd.Parameters.AddWithValue("@TOKEN", dbUser.CustomSid.BinaryValue);
     cmd.Parameters.AddWithValue("@USERGROUPSCOUNT", (object)userGroupsCount);
     cmd.Parameters.AddWithValue("@VALIDFOR", ValidFor);
     cmd.Parameters.AddWithValue("@LDAPPATH", DirectoryServicesUtils.rootDsePath);
     cmd.Parameters.AddWithValue("@RETRIEVEATTRIBUTES", retrieveAttributes);
     System.Data.SqlClient.SqlParameter pAuthorizationType = new System.Data.SqlClient.SqlParameter("@AUTHORIZATION_TYPE", (object)0);
     pAuthorizationType.Direction = System.Data.ParameterDirection.InputOutput;
     cmd.Parameters.Add(pAuthorizationType);
     //BizRule Check CallBack
     SqlDataAdapter checkAccessPartialResultsDataAdapter = new SqlDataAdapter(cmd);
     DataSet checkAccessResults = new DataSet();
     try
     {
         checkAccessPartialResultsDataAdapter.Fill(checkAccessResults);
     }
     catch (SqlException sqlex)
     {
         if (sqlex.Message.StartsWith("Store not found", StringComparison.CurrentCultureIgnoreCase))
         {
             throw SqlAzManException.StoreNotFoundException(StoreName, sqlex);
         }
         else if (sqlex.Message.StartsWith("Application not found", StringComparison.CurrentCultureIgnoreCase))
         {
             throw SqlAzManException.ApplicationNotFoundException(ApplicationName, StoreName, sqlex);
         }
         else if (sqlex.Message.StartsWith("Item not found", StringComparison.CurrentCultureIgnoreCase))
         {
             throw SqlAzManException.ItemNotFoundException(ItemName, StoreName, ApplicationName, sqlex);
         }
         else
         {
             throw SqlAzManException.GenericException(sqlex);
         }
     }
     finally
     {
         conn.Close();
     }
     DataTable checkAccessPartialResultsDataTable = checkAccessResults.Tables[0];
     DataTable checkAccessAttributesDataTable = (retrieveAttributes ? checkAccessResults.Tables[1] : new DataTable());
     AuthorizationType result;
     if (checkAccessPartialResultsDataTable.Select("BizRuleId IS NOT NULL").Length == 0)
     {
         //No business rules to check ... just return check access authorizationType
         result = (AuthorizationType)((int)pAuthorizationType.Value);
     }
     else
     {
         //Transform DataRows into a Hierarchical Tree of Node(s)
         IAzManApplication application = this[StoreName][ApplicationName];
         ItemNode itemNode = this.buildTreeOfNodes(application, checkAccessPartialResultsDataTable, ItemName);
         //Execute Biz Rules and Cut Nodes that returns false
         Hashtable ctxParameters = new Hashtable();
         if (contextParameters != null)
         {
             foreach (KeyValuePair<string, object> kv in contextParameters)
             {
                 ctxParameters.Add(kv.Key, kv.Value);
             }
         }
         itemNode = this.executeBizRules(itemNode, dbUser.CustomSid, ctxParameters);
         //Compute final CheckAccess authorizationType
         result = this.computeCheckAccessResult(itemNode, ref checkAccessAttributesDataTable);
         if (result == AuthorizationType.Deny || result == AuthorizationType.Neutral)
         {
             checkAccessAttributesDataTable = new DataTable(); //no attributes
         }
     }
     if (retrieveAttributes)
     {
         //Populate Attributes authorizationType
         attributes = new List<KeyValuePair<string, string>>(checkAccessAttributesDataTable.Rows.Count);
         foreach (DataRow dr in checkAccessAttributesDataTable.Rows)
         {
             KeyValuePair<string, string> kvp = new KeyValuePair<string, string>((string)dr[0], (string)dr[1]);
             if (!attributes.Contains(kvp))
             {
                 attributes.Add(kvp);
             }
         }
     }
     else
     {
         attributes = new List<KeyValuePair<string, string>>();
     }
     return result;
 }
 /// <summary>
 /// Gets the DB users.
 /// </summary>
 /// <returns></returns>
 public IAzManDBUser[] GetDBUsers()
 {
     var dtDBUsers = this.db.GetDBUsersEx(null, null, null, null);
     IAzManDBUser[] result = new IAzManDBUser[dtDBUsers.Rows.Count];
     for (int i = 0; i < dtDBUsers.Rows.Count; i++)
     {
         result[i] = new SqlAzManDBUser(dtDBUsers.Rows[i]);
     }
     return result;
 }
 private void btnBrowseDBUser_Click(object sender, EventArgs e)
 {
     try
     {
         this.rbDBUser.Checked = true;
         frmDBUsersList frm = new frmDBUsersList();
         frm.application = this.application;
         DialogResult dr = frm.ShowDialog(this);
         if (dr == DialogResult.OK)
         {
             if (frm.selectedDBUsers.Length > 1)
             {
                 this.ShowError(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg80"), Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
             }
             if (frm.selectedDBUsers.Length == 1)
             {
                 this.wid = null;
                 this.dbuser = frm.selectedDBUsers[0];
                 this.txtDBUser.Text = this.dbuser.UserName;
             }
         }
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
     }
     finally
     {
         this.FormValidate();
     }
 }
        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="username">The user name to search for.</param>
        /// <param name="roleName">The role to search in.</param>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        public override bool IsUserInRole(string username, string roleName)
        {
            if (this.userLookupType == "LDAP")
            {
                WindowsIdentity wid = null;
                if (String.Compare(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).Name, this.getFQUN(username), true) == 0)
                {
                    wid = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent());
                }
                if (wid == null)
                {
                    wid = new WindowsIdentity(this.getUpn(this.getFQUN(username))); //Kerberos Protocol Transition: Works in W2K3 native domain only
                }

                if (!this.useWCFCacheService)
                {
                    return((from t in this.storageCache.GetAuthorizedItems(this.storeName, this.applicationName, wid.GetUserBinarySSid(), wid.GetGroupsBinarySSid(), DateTime.Now)
                            where
                            t.Type == ItemType.Role
                            &&
                            (t.Authorization == AuthorizationType.Allow || t.Authorization == AuthorizationType.AllowWithDelegation)
                            &&
                            t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)
                            select t).Count() > 0);
                }
                else
                {
                    using (NetSqlAzManWCFCacheService.CacheServiceClient csc = new NetSqlAzManWCFCacheService.CacheServiceClient())
                    {
                        try
                        {
                            return((from t in csc.GetAuthorizedItemsForWindowsUsers(this.storeName, this.applicationName, wid.GetUserBinarySSid(), wid.GetGroupsBinarySSid(), DateTime.Now, null)
                                    where
                                    t.Type == NetSqlAzManWCFCacheService.ItemType.Role
                                    &&
                                    (t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.Allow || t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.AllowWithDelegation)
                                    &&
                                    t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)
                                    select t).Count() > 0);
                        }
                        finally
                        {
                            ((IDisposable)csc).Dispose();
                        }
                    }
                }
            }
            else
            {
                using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString))
                {
                    IAzManApplication application = storage[this.storeName][this.applicationName];
                    IAzManDBUser      dbUser      = application.GetDBUser(username);

                    if (!this.useWCFCacheService)
                    {
                        return((from t in this.storageCache.GetAuthorizedItems(this.storeName, this.applicationName, dbUser.CustomSid.StringValue, DateTime.Now)
                                where
                                t.Type == ItemType.Role
                                &&
                                (t.Authorization == AuthorizationType.Allow || t.Authorization == AuthorizationType.AllowWithDelegation)
                                &&
                                t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)
                                select t).Count() > 0);
                    }
                    else
                    {
                        using (NetSqlAzManWCFCacheService.CacheServiceClient csc = new NetSqlAzManWCFCacheService.CacheServiceClient())
                        {
                            try
                            {
                                return((from t in csc.GetAuthorizedItemsForDatabaseUsers(this.storeName, this.applicationName, dbUser.CustomSid.StringValue, DateTime.Now, null)
                                        where
                                        t.Type == NetSqlAzManWCFCacheService.ItemType.Role
                                        &&
                                        (t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.Allow || t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.AllowWithDelegation)
                                        &&
                                        t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)
                                        select t).Count() > 0);
                            }
                            finally
                            {
                                ((IDisposable)csc).Dispose();
                            }
                        }
                    }
                }
            }
        }
 private DataRow AddDBUserDataRow(IAzManDBUser member)
 {
     DataRow dr = this.dtAuthorizations.NewRow();
     dr["Owner"] = this.currentOwnerName;
     dr["OwnerSID"] = this.currentOwnerSid;
     dr["Name"] = member.UserName;
     dr["MemberType"] = this.RenderMemberType(MemberType.DatabaseUser, member.CustomSid);
     dr["MemberTypeEnum"] = MemberType.DatabaseUser;
     dr["ObjectSID"] = member.CustomSid.StringValue;
     dr["WhereDefined"] = WhereDefined.Database.ToString();
     dr["WhereDefinedEnum"] = WhereDefined.Database;
     dr["AuthorizationType"] = this.RenderAuthorizationType(AuthorizationType.Neutral);
     dr["AuthorizationTypeEnum"] = AuthorizationType.Neutral;
     dr["ValidFrom"] = DBNull.Value;
     dr["ValidTo"] = DBNull.Value;
     this.dtAuthorizations.Rows.Add(dr);
     return dr;
 }
Exemple #33
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            // Check if the supplied credentials are correct.
            ViewBag.HasError  = false;
            ViewBag.returnUrl = returnUrl;

            // Create logger instance to record activities
            var log = new Logger();

            try
            {
                if (_userAccountService.Authenticate(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, true);

                    // Will be refactored
                    var user = _userAccountService.GetUserDetail(model.UserName);
                    user.LogginDate      = DateTime.Now;
                    user.NumberOfLogins += 1;
                    // Session["USER_PROFILE"] = user;
                    _userAccountService.UpdateUser(user);

                    // Add user information to session variable to avoid frequent trip to the databas
                    var service  = (IUserAccountService)DependencyResolver.Current.GetService(typeof(IUserAccountService));
                    var userInfo = service.GetUserInfo(model.UserName);
                    Session["USER_INFO"]    = userInfo;
                    Session["USER_PROFILE"] = service.GetUserDetail(model.UserName);

                    // Before trying to go and look for user permissions, check if the user is logged in or not

                    //// Load user permissions
                    IAzManStorage storage = new SqlAzManStorage(ConfigurationManager.ConnectionStrings["CatsContext"].ConnectionString);
                    IAzManDBUser  dbUser  = storage.GetDBUser(user.UserName);

                    // Early Warning user permissions
                    UserPermissionCache earlyWarningPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.EARLY_WARNING, dbUser, true, false);
                    Session[CatsGlobals.EARLY_WARNING_PERMISSIONS] = earlyWarningPermissionCache;


                    //PSNP user permission
                    UserPermissionCache psnpPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.PSNP, dbUser, true, false);
                    Session[CatsGlobals.PSNP_PERMISSIONS] = psnpPermissionCache;

                    // Logistics user permissions
                    UserPermissionCache logisticsPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.LOGISTICS, dbUser, true, false);
                    Session[CatsGlobals.LOGISTICS_PERMISSIONS] = logisticsPermissionCache;

                    // Procurement user permissions
                    UserPermissionCache procurementPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.PROCUREMENT, dbUser, true, false);
                    Session[CatsGlobals.PROCUREMENT_PERMISSIONS] = procurementPermissionCache;

                    // Hub user permissions
                    UserPermissionCache hubPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.HUB, dbUser, true, false);
                    Session[CatsGlobals.HUB_PERMISSIONS] = hubPermissionCache;

                    // Regional user permissions
                    UserPermissionCache regionalPermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.REGION, dbUser, true, false);
                    Session[CatsGlobals.REGION_PERMISSIONS] = regionalPermissionCache;

                    // Regional user permissions
                    UserPermissionCache financePermissionCache = new UserPermissionCache(storage, CatsGlobals.CATS, CatsGlobals.FINANCE, dbUser, true, false);
                    Session[CatsGlobals.FINANCE_PERMISSIONS] = financePermissionCache;
                    // Whatever permission we are going to have!
                    _log.Info("Logged in User: "******"Administrator", "Manage User Account");
                    //service.GetUserPermissions(model.UserName, "CATS", "Finance");
                    return(RedirectToLocal(returnUrl));
                }
            }
            catch (UserNotFoundException unfe)
            {
                log.LogAllErrorsMesseges(unfe, _log);
                ViewBag.HasError     = true;
                ViewBag.Error        = unfe.ToString();
                ViewBag.ErrorMessage = "Your user name is not registered as a user on CATS. Please contact your system administrator.";
            }
            catch (DisabledUserException due)
            {
                log.LogAllErrorsMesseges(due, _log);
                ViewBag.HasError     = true;
                ViewBag.Error        = due.ToString();
                ViewBag.ErrorMessage = "Your user account is disabled. Please contact your system administrator.";
            }
            catch (UnmatchingUsernameAndPasswordException uuape)
            {
                log.LogAllErrorsMesseges(uuape, _log);
                ViewBag.HasError     = true;
                ViewBag.Error        = uuape.ToString();
                ViewBag.ErrorMessage = "The user name and password you provided do not match. Please try again with a correct combination.";
            }
            catch (Exception exception)
            {
                log.LogAllErrorsMesseges(exception, _log);

                ViewBag.HasError     = true;
                ViewBag.Error        = exception.ToString();
                ViewBag.ErrorMessage = "Login failed. Try logging in with the right user name and password.";

                ModelState.AddModelError("", exception.Message);
            }

            return(View());
        }
 /// <summary>
 /// Determines whether [is in group] [the specified windows identity].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <returns>
 /// 	<c>true</c> if [is in group] [the specified windows identity]; otherwise, <c>false</c>.
 /// </returns>
 public bool IsInGroup(IAzManDBUser dbUser)
 {
     if (dbUser == null)
         throw new ArgumentNullException("dbUser");
     return this.isAMemberOfGroup(true, this.sid.BinaryValue, this.application.Store.Storage.Mode == NetSqlAzManMode.Developer, DirectoryServicesUtils.rootDsePath, dbUser.CustomSid.BinaryValue, 0);
 }
Exemple #35
0
        private bool isInFilter(IAzManDBUser dbuser, string fieldName, string filterOperator, string fieldValue)
        {
            if (fieldValue.Trim() == String.Empty)
            {
                return(true);
            }
            //Left Value
            string leftValue = String.Empty;

            if (String.Compare(fieldName, "Name", true) == 0)
            {
                leftValue = dbuser.UserName;
            }
            else if (String.Compare(fieldName, "Custom Sid", true) == 0)
            {
                leftValue = dbuser.CustomSid.StringValue;
            }
            else
            {
                foreach (var customColumn in dbuser.CustomColumns)
                {
                    if (String.Compare(fieldName, customColumn.Key, true) == 0)
                    {
                        leftValue = customColumn.Value.ToString();
                        break;
                    }
                }
            }
            //Right Value
            string rightValue = fieldValue.Trim();

            //Operator
            if (filterOperator == "Is" && String.Compare(leftValue, rightValue, true) == 0)
            {
                return(true);
            }
            if (filterOperator == "Is not" && String.Compare(leftValue, rightValue, true) != 0)
            {
                return(true);
            }
            if (filterOperator == "Starts with" && leftValue.StartsWith(rightValue, StringComparison.CurrentCultureIgnoreCase))
            {
                return(true);
            }
            if (filterOperator == "Ends with" && leftValue.EndsWith(rightValue, StringComparison.CurrentCultureIgnoreCase))
            {
                return(true);
            }
            if (filterOperator == "Does not start with" && !leftValue.StartsWith(rightValue, StringComparison.CurrentCultureIgnoreCase))
            {
                return(true);
            }
            if (filterOperator == "Does not end with" && !leftValue.EndsWith(rightValue, StringComparison.CurrentCultureIgnoreCase))
            {
                return(true);
            }
            if (filterOperator == "Contains" && leftValue.IndexOf(rightValue, StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                return(true);
            }
            if (filterOperator == "Does not contain" && leftValue.IndexOf(rightValue, StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                return(true);
            }
            //otherwise
            return(false);
        }
 protected void btnCheckAccessTest_Click(object sender, EventArgs e)
 {
     try
     {
         NTAccount nta = (NTAccount)(this.Request.LogonUserIdentity.User.Translate(typeof(NTAccount)));
         string currentUpnName = nta.Value;
         if (currentUpnName.IndexOf('\\') != -1)
         {
             currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1);
         }
         if (String.IsNullOrEmpty(this.txtWindowsUser.Text) && this.rbWindowsUser.Checked)
         {
             this.txtWindowsUser.Text = currentUpnName;
         }
         if (this.rbWindowsUser.Checked)
         {
             this.dbuser = null;
             if (this.txtWindowsUser.Text == currentUpnName)
             {
                 //Current Windows User
                 this.wid = this.Request.LogonUserIdentity;
             }
             else
             {
                 //Kerberos Protocol Transition
                 this.wid = new WindowsIdentity(this.txtWindowsUser.Text);
             }
         }
         else if (this.rbDBUser.Checked && !String.IsNullOrEmpty(this.txtDBUser.Text))
         {
             this.wid = null;
             this.dbuser = this.application.GetDBUser(this.txtDBUser.Text);
         }
         this.txtDetails.Text = String.Empty;
         this.WriteLineDetailMessage("Check Access Test started at " + DateTime.Now.ToString());
         this.WriteLineDetailMessage(String.Empty);
         this.WriteIdentityDetails();
         this.WriteLineDetailMessage(String.Empty);
         this.WriteDetailMessage("Building Items Hierarchy ...");
         this.RefreshItemsHierarchy();
         this.WriteLineDetailMessage("Done.");
         this.WriteLineDetailMessage(String.Empty);
         TreeNode applicationTreeNode = this.itemsHierarchyTreeView.Nodes[0].ChildNodes[0].ChildNodes[0];
         foreach (TreeNode itemTreeNode in applicationTreeNode.ChildNodes)
         {
             this.checkAccessTest(itemTreeNode);
         }
         this.WriteLineDetailMessage(String.Empty);
         this.WriteLineDetailMessage("Check Access Test finished at " + DateTime.Now.ToString());
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message);
     }
 }
 private bool isInFilter(IAzManDBUser dbuser, string fieldName, string filterOperator, string fieldValue)
 {
     if (fieldValue.Trim() == String.Empty)
         return true;
     //Left Value
     string leftValue = String.Empty;
     if (String.Compare(fieldName, "Name", true) == 0)
         leftValue = dbuser.UserName;
     else if (String.Compare(fieldName, "Custom Sid", true) == 0)
         leftValue = dbuser.CustomSid.StringValue;
     else
     {
         foreach (var customColumn in dbuser.CustomColumns)
         {
             if (String.Compare(fieldName, customColumn.Key, true) == 0)
             {
                 leftValue = customColumn.Value.ToString();
                 break;
             }
         }
     }
     //Right Value
     string rightValue = fieldValue.Trim();
     //Operator
     if (filterOperator == "Is" && String.Compare(leftValue, rightValue, true) == 0) return true;
     if (filterOperator == "Is not" && String.Compare(leftValue, rightValue, true) != 0) return true;
     if (filterOperator == "Starts with" && leftValue.StartsWith(rightValue, StringComparison.CurrentCultureIgnoreCase)) return true;
     if (filterOperator == "Ends with" && leftValue.EndsWith(rightValue, StringComparison.CurrentCultureIgnoreCase)) return true;
     if (filterOperator == "Does not start with" && !leftValue.StartsWith(rightValue, StringComparison.CurrentCultureIgnoreCase)) return true;
     if (filterOperator == "Does not end with" && !leftValue.EndsWith(rightValue, StringComparison.CurrentCultureIgnoreCase)) return true;
     if (filterOperator == "Contains" && leftValue.IndexOf(rightValue, StringComparison.CurrentCultureIgnoreCase)!=-1) return true;
     if (filterOperator == "Does not contain" && leftValue.IndexOf(rightValue, StringComparison.CurrentCultureIgnoreCase) == -1) return true;
     //otherwise
     return false;
 }
 /// <summary>
 /// Checks the Application access [FOR DB Users ONLY].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>
 /// [true] for access allowd, [false] otherwise.
 /// </returns>
 public bool CheckApplicationAccess(IAzManDBUser dbUser, DateTime validFor, params KeyValuePair<string, object>[] contextParameters)
 {
     foreach (IAzManItem item in this.GetItems())
     {
         AuthorizationType auth = item.CheckAccess(dbUser, validFor, contextParameters);
         if (auth == AuthorizationType.AllowWithDelegation || auth == AuthorizationType.Allow)
         {
             return true;
         }
     }
     return false;
 }
        private void btnCheckAccessTest_Click(object sender, EventArgs e)
        {
            try
            {
                NTAccount nta            = (NTAccount)(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User.Translate(typeof(NTAccount)));
                string    currentUpnName = nta.Value;
                if (currentUpnName.IndexOf('\\') != -1)
                {
                    currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1);
                }
                if (this.rbWindowsUser.Checked && !String.IsNullOrEmpty(this.txtWindowsUser.Text))
                {
                    this.dbuser = null;
                    if (this.txtWindowsUser.Text == currentUpnName)
                    {
                        //Current Windows User
                        this.wid = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent());
                    }
                    else
                    {
                        //Kerberos Protocol Transition
                        this.wid = new WindowsIdentity(this.txtWindowsUser.Text);
                    }
                }
                else if (this.rbDBUser.Checked && !String.IsNullOrEmpty(this.txtDBUser.Text))
                {
                    this.wid    = null;
                    this.dbuser = this.application.GetDBUser(this.txtDBUser.Text);
                }
                this.HourGlass(true);
                this.txtDetails.Text                  = String.Empty;
                this.btnCheckAccessTest.Enabled       = this.btnClose.Enabled =
                    this.btnBrowseWindowsUser.Enabled = this.btnBrowseDBUser.Enabled =
                        this.rbWindowsUser.Enabled    = this.rbDBUser.Enabled = false;
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg30") + " " + DateTime.Now.ToString());
                this.WriteLineDetailMessage(String.Empty);
                this.WriteIdentityDetails();
                this.WriteLineDetailMessage(String.Empty);
                this.WriteDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg40"));
                this.checkAccessTestTreeView.BeginUpdate();
                this.RefreshItemsHierarchy();
                this.checkAccessTestTreeView.EndUpdate();
                Application.DoEvents();
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("Done_Msg10"));
                this.WriteLineDetailMessage(String.Empty);
                TreeNode  applicationTreeNode = this.checkAccessTestTreeView.Nodes[0].Nodes[0].Nodes[0];
                Boolean   turboMode           = this.application.Items.Count > 50;
                Hashtable resultCache         = new Hashtable();
                Hashtable attributesCache     = new Hashtable();
                if (turboMode)
                {
                    this.checkAccessTestTreeView.BeginUpdate();
                }
                foreach (TreeNode itemTreeNode in applicationTreeNode.Nodes)
                {
                    this.checkAccessTest(itemTreeNode, turboMode, resultCache, attributesCache);
                }

                if (turboMode)
                {
                    this.checkAccessTestTreeView.EndUpdate();
                }
                this.WriteLineDetailMessage(String.Empty);
                this.WriteLineDetailMessage(Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg50") + " " + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message, Globalization.MultilanguageResource.GetString("frmCheckAccessTest_Msg10"));
            }
            finally
            {
                this.btnCheckAccessTest.Enabled       = this.btnClose.Enabled =
                    this.btnBrowseWindowsUser.Enabled = this.btnBrowseDBUser.Enabled =
                        this.rbWindowsUser.Enabled    = this.rbDBUser.Enabled = true;
                this.HourGlass(false);
            }
        }
 /// <summary>
 /// Checks the access [FOR DB Users only].
 /// </summary>
 /// <param name="StoreName">Name of the store.</param>
 /// <param name="ApplicationName">Name of the application.</param>
 /// <param name="ItemName">Name of the itemName.</param>
 /// <param name="dbUser">The db user.</param>
 /// <param name="ValidFor">The valid for.</param>
 /// <param name="OperationsOnly">if set to <c>true</c> [operations only].</param>
 /// <param name="attributes">The attributes readed.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 public AuthorizationType CheckAccess(string StoreName, string ApplicationName, string ItemName, IAzManDBUser dbUser, DateTime ValidFor, bool OperationsOnly, out List<KeyValuePair<string, string>> attributes, params KeyValuePair<string, object>[] contextParameters)
 {
     return this.internalCheckAccess(StoreName, ApplicationName, ItemName, dbUser, ValidFor, OperationsOnly, true, out attributes, contextParameters);
 }
        /// <summary>
        /// Creates the delegation [DB 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(IAzManDBUser 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.UserName, delegatingUser.CustomSid.StringValue, 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 = delegatingUser.CustomSid;
            string ownerName = delegatingUser.UserName;

            WhereDefined ownerSidWhereDefined = WhereDefined.Database;
            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>
        /// Removes the delegate [DB 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(IAzManDBUser 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.UserName, delegatingUser.CustomSid.StringValue, 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 = delegatingUser.CustomSid;
            string ownerName = delegatingUser.UserName;

            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, delegatingUser.CustomSid, delegateUser, authorizationType);
                }
            }
        }
 /// <summary>
 /// Checks the access in async way [FOR DB Users ONLY].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="callBack">The call back.</param>
 /// <param name="stateObject">The state object.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 /// <remarks>
 /// 	<para>Remeber to: </para>
 /// 	<para>1) add "Asynchronous Processing=true" in the Storage Connection String</para>
 /// 	<para>2) Storage Connection must be manually opened and closed.</para>
 /// </remarks>
 public IAsyncResult BeginCheckAccess(IAzManDBUser dbUser, DateTime validFor, AsyncCallback callBack, object stateObject, params KeyValuePair<string, object>[] contextParameters)
 {
     List<KeyValuePair<string, string>> attributes;
     return this.BeginCheckAccess(dbUser, validFor, callBack, stateObject, out attributes, contextParameters);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="UserPermissionCache"/> class.
 /// </summary>
 /// <param name="storage">The storage.</param>
 /// <param name="storeName">Name of the store.</param>
 /// <param name="applicationName">Name of the application.</param>
 /// <param name="dbUser">The db user.</param>
 /// <param name="retrieveAttributes">if set to <c>true</c> [retrieve attributes].</param>
 /// <param name="multiThreadBuild">if set to <c>true</c> [multi thread build].</param>
 /// <param name="contextParameters">The context parameters.</param>
 public UserPermissionCache(IAzManStorage storage, string storeName, string applicationName, IAzManDBUser dbUser, bool retrieveAttributes, bool multiThreadBuild, params KeyValuePair<string, object>[] contextParameters)
     : this(storage, storeName, applicationName, retrieveAttributes, contextParameters)
 {
     this.dbUser = dbUser;
     if (multiThreadBuild)
         this.buildApplicationCacheMultiThread();
     else
         this.buildApplicationCache();
 }
 /// <summary>
 /// Initializes the context.
 /// </summary>
 /// <param name="storageConnectionString">The storage connection string.</param>
 /// <param name="storeName">Name of the store.</param>
 /// <param name="applicationName">Name of the application.</param>
 /// <param name="dbUserIdentity">The db user identity.</param>
 /// <param name="useStorageCache">if set to <c>true</c> [use storage cache].</param>
 public NetSqlAzManAuthorizationContext(string storageConnectionString, string storeName, string applicationName, IAzManDBUser dbUserIdentity, bool useStorageCache)
 {
     this.StorageConnectionString = storageConnectionString;
     this.StoreName       = storeName;
     this.ApplicationName = applicationName;
     this.DBUserIdentity  = dbUserIdentity;
     this.UseStorageCache = useStorageCache;
 }
 /// <summary>
 /// Checks the access in async way [FOR DB Users ONLY].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="callBack">The call back.</param>
 /// <param name="stateObject">The state object.</param>
 /// <param name="attributes">The attributes readed.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 /// <remarks>
 /// 	<para>Remeber to: </para>
 /// 	<para>1) add "Asynchronous Processing=true" in the Storage Connection String</para>
 /// 	<para>2) Storage Connection must be manually opened and closed.</para>
 /// </remarks>
 public IAsyncResult BeginCheckAccess(IAzManDBUser dbUser, DateTime validFor, AsyncCallback callBack, object stateObject, out List<KeyValuePair<string, string>> attributes, params KeyValuePair<string, object>[] contextParameters)
 {
     return this.application.Store.Storage.BeginCheckAccess(this.application.Store.Name, this.application.Name, this.name, dbUser, validFor, (this.itemType == ItemType.Operation ? true : false), callBack, stateObject, out attributes, contextParameters);
 }
 /// <summary>
 /// Checks the access [FOR Windows Users only].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 public AuthorizationType CheckAccess(IAzManDBUser dbUser, DateTime validFor, params KeyValuePair<string, object>[] contextParameters)
 {
     List<KeyValuePair<string, string>> attributes;
     return this.CheckAccess(dbUser, validFor, out attributes, contextParameters);
 }
 /// <summary>
 /// Checks the access [FOR Windows Users only].
 /// </summary>
 /// <param name="dbUser">The db user.</param>
 /// <param name="validFor">The valid for.</param>
 /// <param name="attributes">The attributes readed.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 public AuthorizationType CheckAccess(IAzManDBUser dbUser, DateTime validFor, out List<KeyValuePair<string, string>> attributes, params KeyValuePair<string, object>[] contextParameters)
 {
     return this.application.Store.Storage.CheckAccess(this.application.Store.Name, this.application.Name, this.name, dbUser, validFor, this.itemType == ItemType.Operation, out attributes, contextParameters);
 }
 /// <summary>
 /// Gets the DB users.
 /// </summary>
 /// <returns></returns>
 public IAzManDBUser[] GetDBUsers()
 {
     var dtDBUsers = this.db.GetDBUsersEx(this.store.Name, this.name, null, null);
     IAzManDBUser[] result = new IAzManDBUser[dtDBUsers.Rows.Count];
     int i = 0;
     foreach (DataRow row in dtDBUsers.Rows)
     {
         result[i++] = new SqlAzManDBUser(row);
     }
     return result;
 }
 /// <summary>
 /// Checks the access in async way [ONLY FOR DB Users].
 /// </summary>
 /// <param name="StoreName">Name of the store.</param>
 /// <param name="ApplicationName">Name of the application.</param>
 /// <param name="ItemName">Name of the itemName.</param>
 /// <param name="dbUser">The db user.</param>
 /// <param name="ValidFor">The valid for.</param>
 /// <param name="OperationsOnly">if set to <c>true</c> [operations only].</param>
 /// <param name="callBack">The call back.</param>
 /// <param name="stateObject">The state object.</param>
 /// <param name="attributes">The attributes readed.</param>
 /// <param name="contextParameters">The context parameters.</param>
 /// <returns>AuthorizationType</returns>
 /// <remarks>
 /// 	<para>Remeber to: </para>
 /// 	<para>1) add "Asynchronous Processing=true" in the Storage Connection String</para>
 /// 	<para>2) Storage Connection must be manually opened and closed.</para>
 /// </remarks>
 public IAsyncResult BeginCheckAccess(string StoreName, string ApplicationName, string ItemName, IAzManDBUser dbUser, DateTime ValidFor, bool OperationsOnly, AsyncCallback callBack, object stateObject, out List<KeyValuePair<string, string>> attributes, params KeyValuePair<string, object>[] contextParameters)
 {
     this.asyncCheckAccessForDBUsers = new AsyncCheckAccessForDBUsers(this.CheckAccess);
     return this.asyncCheckAccessForDBUsers.BeginInvoke(StoreName, ApplicationName, ItemName, dbUser, ValidFor, OperationsOnly, out attributes, contextParameters, callBack, stateObject);
 }