Пример #1
0
        public Result DeleteRole(Role role)
        {
            if (OnBeforeRoleDeleted != null)
            {
                StateChangingEventArgs args = new StateChangingEventArgs();
                OnBeforeRoleDeleted(role, args);
                if (args.CancelStateChange)
                    return new Result(args.ReasonForCancellation);
            }

            IDbCommand cmd = Database.Main.CreateCommand("DeleteRole", CommandType.StoredProcedure);
            Database.Main.AddParameter(cmd, "@RoleID", role.RoleID);
            cmd.ExecuteNonQuery();

            if (OnRoleDeleted != null)
                OnRoleDeleted(role);

            return new Result();
        }
        void OnSaveForm(AjaxFormSubmittedValues form)
        {
            List<string> roleCodes = new List<string>(), permissionTypeCodes = new List<string>();
            switch (form.FormName)
            {
                case "UserEditForm":
                    if (!WebAuthentication.VerifyAccess(PermissionType.UserAdministrator))
                        return;
                    AjaxFormSubmittedValues.Block block = form.Blocks["MainUserFields"];
                    string pw = block.Fields["Password"].Value;
                    bool enabled = block.Fields["Enabled"].Value == "True";
                    if (pw.Length == 0) pw = null;
                    User user;

                    if (form.RecordID == null)
                    {
                        user = new User(
                            SecurityProvider.ClientSpaceID,
                            block.Fields["Username"].Value,
                            pw,
                            block.Fields["FirstName"].Value,
                            block.Fields["Surname"].Value,
                            block.Fields["Email"].Value,
                            enabled, false, false, 0);
                        Result result = SecurityProvider.DataLayer.Store(user);
                        if (!result.Succeeded)
                            throw new AjaxException(result.Message);
                        if (OnUserSaved != null)
                            OnUserSaved(form, user);

                        form.RecordID = user.UserID;
                    }
                    else
                    {
                        user = User.Select(form.RecordID.Value);
                        //if (!CurrentUser.CanModifyUser(user))
                        //    throw new AjaxException("You don't have access to modify that user.");
                        user.Username = block.Fields["Username"].Value;
                        if (pw != null) user.Password = pw;
                        user.FirstName = block.Fields["FirstName"].Value;
                        user.Surname = block.Fields["Surname"].Value;
                        user.Email = block.Fields["Email"].Value;
                        user.Enabled = enabled;
                        SecurityProvider.DataLayer.Store(user);
                        //user.Save();
                        if (OnUserSaved != null)
                            OnUserSaved(form, user);

                        if (user.Locked) return; // don't muck with permissions/roles
                    }

                    if (user.Username != SecurityProvider.CurrentUser.Username) // users can't alter their own permissions
                    {
                        if (form.Blocks.ContainsKey("Roles"))
                            foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                                if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                    if (kvp.Value.Value == "True")
                                        roleCodes.Add(kvp.Value.Name);
                                        //sql.AppendFormat("exec AssignUserToRole '{0}', '{1}'\r\n", user.UserID, kvp.Value.Name.Replace("'", "''"));
                        if (form.Blocks.ContainsKey("Permissions"))
                            foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                                if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                    if (kvp.Value.Value == "True")
                                        permissionTypeCodes.Add(kvp.Value.Name);
                                        //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), user.UserID);
                        //if (sql.Length == 0) return;

                        SecurityProvider.DataLayer.SetRolesAndPermissionsForUser(user.UserID, roleCodes, permissionTypeCodes);
                        //user.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                        //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                    }
                    break;

                case "RoleEditForm":
                    if (!WebAuthentication.VerifyAccess(PermissionType.RoleAdministrator))
                        return;
                    block = form.Blocks["RoleDetails"];
                    string name = block.Fields["Name"].Value;
                    enabled = block.Fields["Enabled"].Value == "True";
                    Role role;
                    if (form.RecordID == null)
                    {
                        role = new Role();
                        role.RoleID = DatabaseManager.GetUniqueID();
                        role.RoleCode = role.RoleID.ToString(); // role codes are only used by system roles
                        role.ClientSpaceID = SecurityProvider.ClientSpaceID;
                    }
                    else
                    {
                        role = Role.Select(form.RecordID.Value);
                        if (role == null) return;
                        if (role.Locked) return; // locked roles aren't supposed to be edited by users
                    }
                    role.Name = name;
                    role.Enabled = enabled;
                    SecurityProvider.DataLayer.Store(role);
                    //((SecurityProvider)Core.Instance["SecurityProvider"]).SaveRole(role);

                    //sql = new StringBuilder();
                    if (form.Blocks.ContainsKey("Roles"))
                        foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                if (kvp.Value.Value == "True")
                                    roleCodes.Add(kvp.Value.Name);
                                    //sql.AppendFormat("exec InheritRoleFrom '{0}', '{1}'\r\n", role.RoleID, kvp.Value.Name.Replace("'", "''"));
                    if (form.Blocks.ContainsKey("Permissions"))
                        foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                if (kvp.Value.Value == "True")
                                    permissionTypeCodes.Add(kvp.Value.Name);
                                    //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), role.RoleID);

                    SecurityProvider.DataLayer.SetRolesAndPermissionsForRole(role.RoleID, roleCodes, permissionTypeCodes);
                    //role.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                    //if (sql.Length == 0) return;
                    //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                    break;
            }
        }
Пример #3
0
 public RoleState(Role role, bool accessible, PermissionState state)
 {
     this.role = role;
     this.isAccessible = accessible;
     this.state = state;
 }
Пример #4
0
        public AjaxForm GetRoleEditForm(long? roleID)
        {
            Role role;
            if (roleID == null)
                role = new Role();
            else
            {
                role = Role.Select(roleID.Value);
                if (role == null)
                    throw new AjaxUserMessageException("The requested role does not exist in the database.");
                if (role.Locked)
                    throw new AjaxUserMessageException("This is a system role and cannot be modified.");
            }

            AjaxForm form = new AjaxForm("RoleEditForm");
            form.RecordID = roleID;

            AjaxFormFieldBlock block = new AjaxFormFieldBlock("RoleDetails", "Role Details");
            block.Add(new AjaxFormInputField("Role Name",
                "Name", 100, role.Locked, null, null, role.Name, null,
                "function(value){{if(value.length==0) return 'A name is required'; return null;}}",
                true, 0));
            block.Add(new AjaxFormCheckboxField("Role is enabled", "Enabled", role.Enabled, role.Locked, null, null, false, 1));
            block.Rank = 0;
            form.FieldBlocks.Add(block);

            //List<Guid> roleDescendents = new List<Guid>();
            //List<Role> roleDescendents = SecurityProvider.DataLayer.ListDescendentRoles(role.RoleID);
            //IDbCommand cmd = Database.Main.CreateCommand("ListDescendentRoles", CommandType.StoredProcedure);
            //Database.Main.AddParameter(cmd, "@RoleID", role.RoleID);
            //DataSet ds = Database.Main.GetDataSet(cmd);
            //foreach (Role role in roleDescendents)
            //    roleDescendents.Add((Guid)row["RoleID"]);

            List<RoleState> roles = SecurityProvider.DataLayer.ListAllRolesAgainstRole(role.RoleID);
            //cmd = Database.Main.CreateCommand("ListRoleToRoleAssignmentStates", CommandType.StoredProcedure);
            //Database.Main.AddParameter(cmd, "@RoleID", role.RoleID);
            //ds = Database.Main.GetDataSet(cmd);

            block = new AjaxFormFieldBlock("Roles", "Roles that this role should adopt");
            block.Rank = 1;
            int c = 0;
            foreach (RoleState r in roles)
                //if (CurrentUser.HasPermission(row["RoleCode"].ToString()) && !roleDescendents.Contains((Guid)row["RoleID"]))
                    block.Add(new AjaxFormCheckboxField(
                        r.Role.Name, r.Role.RoleCode, r.State == PermissionState.Inherited, r.Role.Locked, null, null, false, c++));
                        //(bool)row["Inherited"], role.Locked, null, null, false, c++));
            if (block.Count > 0)
                form.FieldBlocks.Add(block);

            //cmd = Database.Main.CreateCommand("ListPermissionValuesForRole", CommandType.StoredProcedure);
            //Database.Main.AddParameter(cmd, "@RoleID", role.RoleID);
            //Database.Main.AddParameter(cmd, "@ShowAllPermissions", true);
            //ds = Database.Main.GetDataSet(cmd);

            block = new AjaxFormFieldBlock("Permissions", "Permission Settings");
            c  = 0;
            foreach (PermissionTypeState pts in SecurityProvider.DataLayer.ListAllPermissionTypesAgainstRole(role.RoleID))
                //if (CurrentUser.HasPermission(row["PermissionTypeCode"].ToString()))
                block.Add(new AjaxFormCheckboxField(
                    pts.PermissionType.Description, pts.PermissionType.PermissionTypeCode, pts.PermissionState == PermissionState.Specified,
                    role.Locked, null, null, false, c++));
                    //row["Description"].ToString(), row["PermissionTypeCode"].ToString(),
                    //row["Value"] == DBNull.Value ? false : (bool)row["Value"], role.Locked, null, null, false, c++));

            AjaxFormButtonGroup buttons = new AjaxFormButtonGroup();
            block.Rank = 2;
            buttons.Rank = 10000;
            buttons.AddSubmitButton(null, "Save", "SecurityInterface.OnRoleSaved", null);
            if (roleID != null)
                if (!role.Locked) buttons.AddButton(null, "Delete", "SecurityInterface.DeleteRole('" + roleID.ToString() + "')");
            buttons.AddButton(null, "Cancel", "$('security-permissionlist').innerHTML = '';");
            block.Add(buttons);

            if (block.Count > 0)
                form.FieldBlocks.Add(block);

            return form;
        }
		public Role SelectRole(long roleID)
		{
			using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
			{
				using (SqlConnection conn = new SqlConnection(DatabaseManager.DatabaseEngine.ConnectionString))
				{
					conn.Open();
					SqlCommand cmd = new SqlCommand("SelectRole", conn);
					cmd.CommandType = CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@RoleID", roleID));
					SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
					Role role;
					if (!reader.Read())
						role = null;
					else
						role = new Role(reader);
					reader.Close();
					return role;
				}
			}
		}
		public Result Delete(Role role)
		{
			Result result = new Result();
			if (OnBeforeDeleteRole != null)
				OnBeforeDeleteRole(role, result);
			SqlConnection conn = null;
			if (result.Succeeded)
			{
				try
				{
					using (TransactionScope scope = new TransactionScope())
					{
						conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
						try
						{
							SqlCommand cmd = new SqlCommand("DeleteRole", conn);
							cmd.CommandType = CommandType.StoredProcedure;
							cmd.Parameters.Add(new SqlParameter("@RoleID", role.RoleID));
							cmd.ExecuteNonQuery();
							scope.Complete();
						}
						catch (Exception ex)
						{
							return new Result(ex.Message);
						}
					}
				}
				finally
				{
					DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
				}
				if (OnRoleDeleted != null)
					OnRoleDeleted(role);
			}
			return result;
		}
		public Result Store(Role role)
		{
			SqlConnection conn = null;
			try
			{
				using (TransactionScope scope = new TransactionScope())
				{
					conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
					try
					{
						SqlCommand cmd = new SqlCommand("StoreRole", conn);
						cmd.CommandType = CommandType.StoredProcedure;
						SqlParameter prm = new SqlParameter("@RoleID", role.RoleID);
						prm.Direction = ParameterDirection.InputOutput;
						cmd.Parameters.Add(prm);
						cmd.Parameters.Add(new SqlParameter("@RoleCode", role.RoleCode));
						cmd.Parameters.Add(new SqlParameter("@ClientSpaceID", role.ClientSpaceID));
						cmd.Parameters.Add(new SqlParameter("@Name", role.Name));
						cmd.Parameters.Add(new SqlParameter("@Enabled", role.Enabled));
						cmd.Parameters.Add(new SqlParameter("@Locked", role.Locked));
						cmd.Parameters.Add(new SqlParameter("@Hidden", role.Hidden));
						for (int i = 0; i < cmd.Parameters.Count; i++)
							if (cmd.Parameters[i].Value == null)
								cmd.Parameters[i].Value = DBNull.Value;
						cmd.ExecuteNonQuery();
						role.RoleID = (long)prm.Value;
						scope.Complete();
					}
					catch (Exception ex)
					{
						return new Result(ex.Message);
					}
				}
			}
			finally
			{
				DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
			}
			return new Result();
		}
Пример #8
0
        public Result SaveRole(Role role)
        {
            if (OnBeforeRoleSaved != null)
            {
                StateChangingEventArgs args = new StateChangingEventArgs();
                OnBeforeRoleSaved(role, args);
                if (args.CancelStateChange)
                    return new Result(args.ReasonForCancellation);
            }

            IDbCommand cmd = Database.Main.CreateCommand(role.IsNew ? "CreateRole" : "UpdateRole", CommandType.StoredProcedure);
            Database.Main.AddParameter(cmd, "@RoleID", role.RoleID);
            Database.Main.AddParameter(cmd, "@RoleCode", role.RoleCode);
            Database.Main.AddParameter(cmd, "@ClientID", role.ClientID);
            Database.Main.AddParameter(cmd, "@Name", role.Name);
            Database.Main.AddParameter(cmd, "@Enabled", role.Enabled);
            Database.Main.AddParameter(cmd, "@Locked", role.Locked);
            Database.Main.AddParameter(cmd, "@Hidden", role.Hidden);
            cmd.ExecuteNonQuery();
            bool isNew = role.IsNew;
            role.SetSaved();

            if (OnRoleSaved != null)
                OnRoleSaved(role, isNew);

            return new Result();
        }