Пример #1
0
        public static Program.ExitCode AddAssignment(AuthUserRole assgnUR, rbacLINQ2SQLDataContext db)
        {
            //check if the role exists
            var query = from  aur in db.AuthUserRole
                        where aur.Role_Id == assgnUR.Role_Id && aur.User_Id == assgnUR.User_Id
                        select aur;
            //if does not exist, add:
            if (query.Count() == 0)
            {
                //here must be checking role addition posibility within SSOD
                //...

                db.AuthUserRole.InsertOnSubmit(assgnUR);
                try
                {
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch (Exception exc)
                {
                    return Program.ExitCode.Error;
                }
            }
            //if exists, Ignore or Update:
            else
            {
                return Program.ExitCode.ElementExists;
            }
        }
Пример #2
0
        public static Program.ExitCode ExportToXML(rbacLINQ2SQLDataContext db, string fname)
        {
            try
            {
                // Create an XmlWriter with custom formatting settings
                XmlWriter xmlWriter;
                XmlWriterSettings xmlWriterSettigns = new XmlWriterSettings();
                xmlWriterSettigns.Indent = true;
                xmlWriterSettigns.IndentChars = "\t";
                xmlWriterSettigns.NewLineOnAttributes = true;
                xmlWriterSettigns.NewLineChars = "\n";
                xmlWriter = XmlWriter.Create(fname, xmlWriterSettigns);

                // Write document
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("MCD_PMTOOL_RBAC_DATABASE");

                XMLWritePolicyBlock(db, xmlWriter);
                XMLWriteActionBlock(db, xmlWriter);
                XMLWriteObjectBlock(db, xmlWriter);

                xmlWriter.WriteEndElement();
                xmlWriter.Close();
            }
            catch
            {
                return Program.ExitCode.Error;
            }
            return Program.ExitCode.Success;
        }
Пример #3
0
 public static Program.ExitCode AddAction(Action a_in, rbacLINQ2SQLDataContext db)
 {
     //check if exists
     var query = from act in db.Action
                 where act.Name == a_in.Name
                 select act;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Action.InsertOnSubmit(a_in);
         try
         {
             db.SubmitChanges();
             return Program.ExitCode.Success;
         }
         catch (Exception exc)
         {
             return Program.ExitCode.Error;
         }
     }
     //if exists, Ignore or Update:
     else
     {
         return Program.ExitCode.ElementExists;
     }
 }
Пример #4
0
 public static void AddAction_noTryCatch(Action a_in, rbacLINQ2SQLDataContext db)
 {
     //check if exists
     var query = from act in db.Action
                 where act.Name == a_in.Name
                 select act;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Action.InsertOnSubmit(a_in);
         db.SubmitChanges();
         System.Diagnostics.Debug.WriteLine("Added Action: {0}", a_in.Name);
     }
     else
     {
         System.Diagnostics.Debug.WriteLine("Existing Action: {0}", a_in.Name);
     }
 }
Пример #5
0
        public MainForm()
        {
            InitializeComponent();

            //Create LINQ classes for database
            db = new rbacLINQ2SQLDataContext();

            //Create bindings to rbacDataSet (local in-memory copy for rbac.mdf, IMHO)
            dataGV_Tables.DataSource = bindingSource_Tables;

            /////combobox_Tables initialization with Table names in <dbo.Table_name> format
            //var q = from t in db.Mapping.GetTables()
            //        select t.TableName;
            //cb_Tables.Items.AddRange(q.ToArray());

            /////testing auto-generated forms for tables
            //new Form1().Show();
            /////1. testing TableAdapterManager for the Role-table edit procedure
            //roleTableAdapter1.Fill(rbacDataSet.Role);

            //axDrawing
            axDrawingControl = axDrawingControl1;
        }
Пример #6
0
        public static Program.ExitCode RmPermissionPerObject(PermissionPerObject ppo_in, rbacLINQ2SQLDataContext db)
        {
            var query_ppo = from ppo in db.PermissionPerObject
                            where ppo.Action_Id == ppo_in.Action_Id && ppo.Object_Id == ppo_in.Object_Id && ppo.Permission_Id == ppo_in.Permission_Id
                            select ppo;
            // if there's no such an element - return corresponding status:
            if (query_ppo.Count() == 0)
                return Program.ExitCode.ElementDoesNotExists;

            //Otherwise, delete from PermissionPerObject:
            db.PermissionPerObject.DeleteOnSubmit(query_ppo.First());
            try { db.SubmitChanges(); }
            catch (Exception exc) { return Program.ExitCode.Error; }

            // Check, if there's a PpO entity for the ppo.Permission_Id permission.
            query_ppo = from ppo in db.PermissionPerObject
                        where ppo.Permission_Id == ppo_in.Permission_Id
                        select ppo;
            // If not, delete this "empty" ppo.Permission_Id from Permission and from RolePermission
            // Otherwise, return success
            if (query_ppo.Count() != 0)
            {
                return Program.ExitCode.Success;
            }
            else
            {
                var query_p = from p in db.Permission
                              where p.Id == ppo_in.Permission_Id
                              select p;
                db.RolePermission.DeleteAllOnSubmit(query_p.First().RolePermission);
                db.Permission.DeleteOnSubmit(query_p.First());
                try { db.SubmitChanges(); }
                catch (Exception exc) { return Program.ExitCode.Error; }
            }

            return Program.ExitCode.Success;
        }
Пример #7
0
        public static Program.ExitCode RmPolicy(Policy policy_in, rbacLINQ2SQLDataContext db)
        {
            Program.ExitCode status;

            //check if the policy exists
            var query = from policy in db.Policy
                        where policy.Id == policy_in.Id
                        select policy;
            //if does exist, remove:
            if (query.Count() != 0)
            {
                Policy p = query.First();

                foreach (User u in p.User)
                {
                    status = RmUser(u, db, false);
                    if (status != Program.ExitCode.Success)
                        return status;
                }
                foreach (Role r in p.Role)
                {
                    status = RmRole(r, db, false);
                    if (status != Program.ExitCode.Success)
                        return status;
                }
                foreach (Permission perm in p.Permission)
                {
                    status = RmPermission(perm, db, false);
                    if (status != Program.ExitCode.Success)
                        return status;
                }
                db.Policy.DeleteOnSubmit(p);
                try
                {
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch (Exception exc)
                {
                    return Program.ExitCode.Error;
                }
            }
            //if doesn't exist:
            else
            {
                return Program.ExitCode.ElementDoesNotExists;
            }
        }
Пример #8
0
 public static Program.ExitCode AddRole(Role r, rbacLINQ2SQLDataContext db)
 {
     //check if the role exists
     var query = from role in db.Role
                 where role.Name == r.Name && role.Policy_Id == r.Policy_Id
                 select role;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Role.InsertOnSubmit(r);
         try
         {
             db.SubmitChanges();
             return Program.ExitCode.Success;
         }
         catch (Exception exc)
         {
             return Program.ExitCode.Error;
         }
     }
     //if exists, Ignore or Update:
     else
     {
         return Program.ExitCode.ElementExists;
     }
 }
Пример #9
0
 public static Program.ExitCode RmPermission(Permission p_in, rbacLINQ2SQLDataContext db, bool submitChanges = true)
 {
     var query_p = from p in db.Permission
                     where p.Name == p_in.Name && p.Policy_Id == p_in.Policy_Id
                     select p;
     if (query_p.Count() == 0)
     {
         return Program.ExitCode.ElementDoesNotExists;
     }
     db.PermissionPerObject.DeleteAllOnSubmit(query_p.First().PermissionPerObject);
     db.RolePermission.DeleteAllOnSubmit(query_p.First().RolePermission);
     db.Permission.DeleteOnSubmit(query_p.First());
     try
     {
         if (submitChanges)
             db.SubmitChanges();
         return Program.ExitCode.Success;
     }
     catch (Exception exc) { return Program.ExitCode.Error; }
 }
Пример #10
0
 public static Program.ExitCode UpdateRole(Role r, rbacLINQ2SQLDataContext db)
 {
     var query = from role in db.Role
                 where role.Name == r.Name && role.Policy_Id == r.Policy_Id
                 select role;
     query.First().Cardinality = r.Cardinality;
     try
     {
         db.SubmitChanges();
         return Program.ExitCode.Success;
     }
     catch (Exception exc)
     {
         return Program.ExitCode.Error;
     }
 }
Пример #11
0
        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
                return;
            string fname = openFileDialog1.FileName;

            Program.ExitCode status = XMLManager.ImportFromXML(this.db,fname);
            if (status != Program.ExitCode.Success)
            {
                MessageBox.Show("Import was not successful!");
            }
            else
            {
                MessageBox.Show(String.Format("DataBase was successfully imported from \n\n{0}!", fname));
            }

            db = new rbacLINQ2SQLDataContext();
            cb_Tables.Text = "Policy";
            RenewDataGV_Tables("Policy");
        }
Пример #12
0
 public static Program.ExitCode AddUser(User u, rbacLINQ2SQLDataContext db)
 {
     //check if the user exists
     var query = from usr in db.User
                 where usr.Name == u.Name && usr.Policy_Id == u.Policy_Id
                 select usr;
     //if doesn't exist, add:
     if (query.Count() == 0)
     {
         db.User.InsertOnSubmit(u);
         try
         {
             db.SubmitChanges();
             return Program.ExitCode.Success;
         }
         catch (Exception exc)
         {
             return Program.ExitCode.Error;
         }
     }
     //if exists:
     else
     {
         return Program.ExitCode.ElementExists;
     }
 }
Пример #13
0
        public static Program.ExitCode RmUser(User u, rbacLINQ2SQLDataContext db, bool submitChanges = true)
        {
            try
            {
                User user = db.User.Single(u1 => (u1.Id == u.Id && u1.Name == u.Name &&
                                                  u1.Policy_Id == u.Policy_Id));

                //Можем запрещать удалять Юзера, у которого есть assigned roles.
                //if (user.AuthUserRole.Count != 0)
                //{
                //    return Program.ExitCode.HasAssigned;
                //}
                foreach (Session s in user.Session)
                {
                    db.ActiveRole.DeleteAllOnSubmit(s.ActiveRole);
                }
                db.Session.DeleteAllOnSubmit(user.Session);
                db.AuthUserRole.DeleteAllOnSubmit(user.AuthUserRole);
                db.User.DeleteOnSubmit(db.User.Single(u1 =>
                                                (u1.Id == u.Id &&
                                                u1.Policy_Id == u.Policy_Id)));
                if (submitChanges)
                    db.SubmitChanges();

                return Program.ExitCode.Success;
            }
            catch (Exception exc)
            {
                return Program.ExitCode.Error;
            }
        }
Пример #14
0
 public static void AddRole_noTryCatch(Role r, rbacLINQ2SQLDataContext db)
 {
     //check if the role exists
     var query = from role in db.Role
                 where role.Name == r.Name && role.Policy_Id == r.Policy_Id
                 select role;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Role.InsertOnSubmit(r);
         db.SubmitChanges();
         System.Diagnostics.Debug.WriteLine("Added Role: {0}", r.Name);
     }
     else
     {
         System.Diagnostics.Debug.WriteLine("Existing Role: {0}", r.Name);
     }
 }
Пример #15
0
        // StaticSOD and DynamicSOD are not fully implemented
        // (with paying no attention to Role Hierarchy relations)
        public static Program.ExitCode AddStaticSOD(Role r1, Role r2, rbacLINQ2SQLDataContext db)
        {
            // Check if roles exist
            var role1 = from r in db.Role
                        where r.Name == r1.Name && r.Policy_Id == r1.Policy_Id
                        select r;
            var role2 = from r in db.Role
                        where r.Name == r2.Name && r.Policy_Id == r2.Policy_Id
                        select r;
            if (role1.Count() == 1 || role2.Count() == 1)
            {
                StaticSOD ssod1 = new StaticSOD()
                {
                    Role_Id = role1.First().Id,
                    ExclusiveRole_Id = role2.First().Id,
                };

                StaticSOD ssod2 = new StaticSOD()
                {
                    Role_Id = role2.First().Id,
                    ExclusiveRole_Id = role1.First().Id,
                };

                // Check if SSOD exists:
                var query1 = from t in db.StaticSOD
                             where t.Role_Id == ssod1.Role_Id && t.ExclusiveRole_Id == ssod1.ExclusiveRole_Id
                             select t;
                var query2 = from t in db.StaticSOD
                             where t.Role_Id == ssod2.Role_Id && t.ExclusiveRole_Id == ssod2.ExclusiveRole_Id
                             select t;
                if (query1.Count() == 1 && query2.Count() == 1)
                {
                    return Program.ExitCode.ElementExists;
                }
                try
                {
                    if (query1.Count() != 1)
                        db.StaticSOD.InsertOnSubmit(ssod1);
                    if (query2.Count() != 1)
                        db.StaticSOD.InsertOnSubmit(ssod2);
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch
                {
                    return Program.ExitCode.Error;
                }
            }
            else
            {
                return Program.ExitCode.ElementDoesNotExists;
            }
        }
Пример #16
0
        public static void AddRolePermission_noTryCatch(RolePermission rp_in, rbacLINQ2SQLDataContext db)
        {
            //check if the role exists
            var query = from rp in db.RolePermission
                        where rp.Role_Id == rp_in.Role_Id && rp.Permission_Id == rp_in.Permission_Id
                        select rp;
            //if does not exist, add:
            if (query.Count() == 0)
            {
                //here must be checking of role-permission addition posibility within Constraints of RBAC2.
                //...

                db.RolePermission.InsertOnSubmit(rp_in);
                db.SubmitChanges();
                System.Diagnostics.Debug.WriteLine("Added RolePermission {0}->{1}:", rp_in.Role_Id, rp_in.Permission_Id);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Existing RolePermission {0}->{1}:", rp_in.Role_Id, rp_in.Permission_Id);
            }
        }
Пример #17
0
        public static Program.ExitCode AddRolePermission(RolePermission rp_in, rbacLINQ2SQLDataContext db)
        {
            //check if the role exists
            var query = from rp in db.RolePermission
                        where rp.Role_Id == rp_in.Role_Id && rp.Permission_Id == rp_in.Permission_Id
                        select rp;
            //if does not exist, add:
            if (query.Count() == 0)
            {
                //here must be checking of role-permission addition posibility within Constraints of RBAC2.
                //...

                db.RolePermission.InsertOnSubmit(rp_in);
                try
                {
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch (Exception exc)
                {
                    return Program.ExitCode.Error;
                }
            }
            //if exists:
            else
            {
                return Program.ExitCode.ElementExists;
            }
        }
Пример #18
0
 public static void AddPolicy_noTryCatch(Policy p, rbacLINQ2SQLDataContext db)
 {
     //check if the role exists
     var query = from policy in db.Policy
                 where policy.Name == p.Name
                 select policy;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Policy.InsertOnSubmit(p);
         db.SubmitChanges();
         System.Diagnostics.Debug.WriteLine("Added Policy: {0}", p.Name);
     }
     else
     {
         System.Diagnostics.Debug.WriteLine("Existing Policy: {0}", p.Name);
     }
 }
Пример #19
0
        public static Program.ExitCode RmRole(Role r, rbacLINQ2SQLDataContext db, bool submitChanges = true)
        {
            try
            {
                Role role = db.Role.Single(r1 => (r1.Id == r.Id &&
                                                  r1.Policy_Id == r.Policy_Id));
                //Можем запрещать удалять Роли, которые привязаны к каким-то Юзерам
                //if (role.AuthUserRole.Count != 0)
                //{
                //    return Program.ExitCode.HasAssigned;
                //}

                //здесь не удаляется роль из SSOD, DSOD, RH
                db.ActiveRole.DeleteAllOnSubmit(role.ActiveRole);
                db.AuthUserRole.DeleteAllOnSubmit(role.AuthUserRole);
                db.RolePermission.DeleteAllOnSubmit(role.RolePermission);
                db.Role.DeleteOnSubmit(role);

                if (submitChanges)
                    db.SubmitChanges();

                return Program.ExitCode.Success;
            }
            catch (Exception exc)
            {
                return Program.ExitCode.Error;
            }
        }
Пример #20
0
 public static void AddUser_noTryCatch(User u, rbacLINQ2SQLDataContext db)
 {
     //check if the user exists
     var query = from usr in db.User
                 where usr.Name == u.Name && usr.Policy_Id == u.Policy_Id
                 select usr;
     //if doesn't exist, add:
     if (query.Count() == 0)
     {
         db.User.InsertOnSubmit(u);
         db.SubmitChanges();
         System.Diagnostics.Debug.WriteLine("Added User: {0}", u.Name);
     }
     else
     {
         System.Diagnostics.Debug.WriteLine("Existing User: {0}", u.Name);
     }
 }
Пример #21
0
        public static Program.ExitCode RmRolePermission(RolePermission rp_in, rbacLINQ2SQLDataContext db)
        {
            //check if the role exists
            var query = from rp in db.RolePermission
                        where rp.Role_Id == rp_in.Role_Id && rp.Permission_Id == rp_in.Permission_Id
                        select rp;
            //if does exist, remove:
            if (query.Count() != 0)
            {
                //here must be checking of role-permission addition posibility within Constraints of RBAC2.
                //...

                /*
                 * Без учета Активных ролей. Вообще, эта операция должна выполняться, когда выбранная роль не залогинена ни у одного пользователя
                 * Т.е. когда query.First().Role.ActiveRole.Count == 0
                 * Более того, когда все роли, лежащие Выше по ролевой иерархии, не залогинены. (чтобы спокойно у них отобрать permission)
                 * */
                db.RolePermission.DeleteOnSubmit(query.First());
                try
                {
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch (Exception exc)
                {
                    return Program.ExitCode.Error;
                }
            }
            //if doesn't exist:
            else
            {
                return Program.ExitCode.ElementExists;
            }
        }
Пример #22
0
        // TODO:
        // 1. Вычислять макс.длину строки и делать размер Контейнера соответствующим
        //
        public static Program.ExitCode VisualizeUsers(Visio.Page targetPage,
            rbacLINQ2SQLDataContext db)
        {
            Visio.Application visioApplication = null;
            Visio.Document stencilUML = null;
            Visio.Shape shapeUser = null;
            Visio.Shape shapeUserContainer = null;
            int lastElemInContainer = 0;
            Visio.Document targetDocument = null;
            Visio.ContainerProperties containerProperties = null;
            int currentDiagramServices = -1;
            int prevDiagramServices;
            System.Array containerMembers = null;

            if (targetPage == null)
            {
                return Program.ExitCode.Error;
            }

            try
            {
                // Turn on all Visio diagram services
                targetDocument = targetPage.Document;
                visioApplication = targetPage.Application;
                stencilUML = visioApplication.Documents.
                            OpenEx(@"C:\MyTestProjects\MCD\diploma\pmtool\pmt\pmt\UML_Class.vssx",
                                    (short)Visio.VisOpenSaveArgs.visOpenHidden);
                // Enable All Diagram Services to enable adding huge-named members to the container
                prevDiagramServices = targetDocument.DiagramServicesEnabled;
                targetDocument.DiagramServicesEnabled = currentDiagramServices;

                // DO NOT REMOVE NEXT LINE!
                //-- WTF?! Добавление этой строчки убирает из Container'а дефолтные члены.
                //-- Причем только для первого раза. Если создавать еще сущности, то уже будет опять с дефолтными.
                //
                //-- Вместо этой строки сейчас просто удаляются дефолтные члены контейнеров.
                //-- Благо, их генерится всего два, и удаление не занимает много времени.
                //targetPage.Document.OpenStencilWindow();

                // Just drop elements from User Table:
                //foreach (User u in db.User)
                //{
                //    System.Diagnostics.Debug.WriteLine(lastElemInContainer);
                //    shapeUser = targetPage.Drop(stencilUML.Masters["Member"], 0, 0);
                //    shapeUser.Text = String.Format("name: {0}|password: {1}|policy: {2}", u.Name, u.Password, u.Policy_Id);
                //    //shapeUser.Text = String.Format("name: {0}", u.Name);
                //    targetPage.Application.ActiveWindow.Select(shapeUser, (short)Visio.VisSelectArgs.visSelect);
                //}

                // Drop a container
                shapeUserContainer = targetPage.DropContainer(stencilUML.Masters["Class"], null);
                // Same as prev.row:
                //shapeUserContainer = targetPage.Drop(stencilUML.Masters["Class"], 5, 5);
                shapeUserContainer.Text = "User Table";

                // Get/Set Container List Spacing Interval (gap between members in list)
                //shapeUserContainer.ContainerProperties.SetListSpacing(Visio.VisUnitCodes.visInches, 0.2);
                //System.Diagnostics.Debug.WriteLine(shapeUserContainer.ContainerProperties.GetListSpacing(Visio.VisUnitCodes.visInches));

                // Delete default members, that appear right after a container was dropped on a page
                foreach (int o in shapeUserContainer.ContainerProperties.GetMemberShapes((int)Visio.VisContainerFlags.visContainerFlagsDefault))
                {
                    targetPage.Shapes.get_ItemFromID(o).Delete();
                }

                // Drop elements to the container
                lastElemInContainer = shapeUserContainer.ContainerProperties.GetListMembers().Length+1;
                foreach (User u in db.User)
                {
                    System.Diagnostics.Debug.WriteLine(lastElemInContainer);
                    if (lastElemInContainer != 1)
                    {
                        shapeUser = targetPage.DropIntoList(stencilUML.Masters["Separator"],
                                                            shapeUserContainer,
                                                            lastElemInContainer);
                        lastElemInContainer += 1;
                    }
                    shapeUser = targetPage.DropIntoList(stencilUML.Masters["Member"],
                                                            shapeUserContainer,
                                                            lastElemInContainer);
                    lastElemInContainer += 1;
                    shapeUser.Text = String.Format("name: {0}|password: {1}|policy: {2}", u.Name, u.Password, u.Policy_Id);

                    // Same with Insert method:
                    //shapeUserContainer.ContainerProperties.InsertListMember(
                    //    shapeUser = targetPage.Drop(stencilUML.Masters.get_ItemU("Member"),0,0), lastElemInContainer);
                    //shapeUser.Text = String.Format("Name: {0}|Password: {1}|Policy: {2}", u.Name, u.Password, u.Policy_Id);
                    //lastElemInContainer += 1;
                }

                containerProperties = shapeUserContainer.ContainerProperties;
                // Report on contents of container
                containerMembers = containerProperties.GetMemberShapes((int)Visio.VisContainerFlags.visContainerFlagsDefault);
                foreach (int member in containerMembers)
                {
                    System.Diagnostics.Debug.WriteLine(targetPage.Shapes.get_ItemFromID(member).NameU +
                        " |===> "+ targetPage.Shapes.get_ItemFromID(member).Text);
                }

                targetPage.Application.ActiveWindow.DeselectAll();
                targetPage.CenterDrawing();
                stencilUML.Close();
                targetDocument.DiagramServicesEnabled = prevDiagramServices;
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err.Message);
                // Return the Diagram Services status to its previous state if it was set in
                // the try block.
                if (currentDiagramServices != -1 && targetDocument != null)
                {
                    targetDocument.DiagramServicesEnabled = currentDiagramServices;
                }
                throw;
            }

            return Program.ExitCode.Success;
        }
Пример #23
0
        public static void AddAssignment_noTryCatch(AuthUserRole assgnUR, rbacLINQ2SQLDataContext db)
        {
            //check if the role exists
            var query = from aur in db.AuthUserRole
                        where aur.Role_Id == assgnUR.Role_Id && aur.User_Id == assgnUR.User_Id
                        select aur;
            //if does not exist, add:
            if (query.Count() == 0)
            {
                //here must be checking role addition posibility within SSOD
                //...

                db.AuthUserRole.InsertOnSubmit(assgnUR);
                db.SubmitChanges();
                System.Diagnostics.Debug.WriteLine("Added User->Role: {0}->{1}", assgnUR.User_Id, assgnUR.Role_Id);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Existing User->Role: {0}->{1}", assgnUR.User_Id, assgnUR.Role_Id);
            }
        }
Пример #24
0
 public static Program.ExitCode AddPolicy(Policy p, rbacLINQ2SQLDataContext db)
 {
     //check if the role exists
     var query = from policy in db.Policy
                 where policy.Name == p.Name
                 select policy;
     //if does not exist, add:
     if (query.Count() == 0)
     {
         db.Policy.InsertOnSubmit(p);
         try
         {
             db.SubmitChanges();
             return Program.ExitCode.Success;
         }
         catch (Exception exc)
         {
             return Program.ExitCode.Error;
         }
     }
     //if exists, Ignore or Update:
     else
     {
         return Program.ExitCode.ElementExists;
     }
 }
Пример #25
0
 public static Program.ExitCode UpdateUser(User u, rbacLINQ2SQLDataContext db)
 {
     var query = from usr in db.User
                 where usr.Name == u.Name && usr.Policy_Id == u.Policy_Id
                 select usr;
     query.First().Password = u.Password;
     try
     {
         db.SubmitChanges();
         return Program.ExitCode.Success;
     }
     catch (Exception exc)
     {
         return Program.ExitCode.Error;
     }
 }
Пример #26
0
        public static Program.ExitCode RmObject(Object o_in, rbacLINQ2SQLDataContext db)
        {
            var query = from obj in db.Object
                        where obj.Name == o_in.Name
                        select obj;
            if (query.Count() == 0)
                return Program.ExitCode.ElementDoesNotExists;

            Object o = query.First();

            HashSet<int> pids = new HashSet<int>();

            foreach (var ppo in o.PermissionPerObject)
            {
                pids.Add(ppo.Permission_Id);
                db.PermissionPerObject.DeleteOnSubmit(ppo);
            }

            try { db.SubmitChanges(); }
            catch (Exception exc) { return Program.ExitCode.Error; }

            //check if there're entities for PPOs deleted. If not - delete these Permission entities:
            var prmsn = db.PermissionPerObject.Where(x => (pids.Contains<int>(x.Permission_Id)))
                                              .Select(x => x.Permission_Id);
            foreach (int i in prmsn)
                pids.Remove(i);

            var query1 = db.Permission.Where(x => pids.Contains<int>(x.Id));
            foreach (var q in query1)
            {
                RmPermission(q, db, false);
            }

            db.Object.DeleteOnSubmit(o);
            try
            {
                db.SubmitChanges();
                return Program.ExitCode.Success;
            }
            catch (Exception exc) { return Program.ExitCode.Error; }
        }
Пример #27
0
        public static void AddPermission_noTryCatch(Permission p_in, Action a_in, Object o_in, rbacLINQ2SQLDataContext db)
        {
            bool ppo_exists = false;
            bool p_exists = false;

            var query_p = from p in db.Permission
                          where p.Name == p_in.Name && p.Policy_Id == p_in.Policy_Id
                          select p;
            if (query_p.Count() != 0)
                p_exists = true;
            // if does not exist in Permission_Table, add:
            if (!p_exists)
            {
                db.Permission.InsertOnSubmit(p_in);
                db.SubmitChanges();
                System.Diagnostics.Debug.WriteLine("Added Permission {0}:", p_in.Name);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Existing Permission {0}:", p_in.Name);
            }
            Permission perm = db.Permission.Single(p => p.Name == p_in.Name && p.Policy_Id == p_in.Policy_Id);

            var query_ppo = from ppo in db.PermissionPerObject
                            where ppo.Action_Id == a_in.Id && ppo.Object_Id == o_in.Id && ppo.Permission_Id == perm.Id
                            select ppo;
            if (query_ppo.Count() != 0)
            {
                ppo_exists = true;
                System.Diagnostics.Debug.WriteLine("Existing PermissionPerObject {0}->({1},{2}):",p_in.Name,a_in.Name,o_in.Name);
            }
            // if does not exist in PermissionPerObject_Table, add:
            else
            {
                db.PermissionPerObject.InsertOnSubmit(new PermissionPerObject
                {
                    Action_Id = a_in.Id,
                    Object_Id = o_in.Id,
                    Permission_Id = perm.Id
                });
                db.SubmitChanges();
                System.Diagnostics.Debug.WriteLine("Added PermissionPerObject {0}->({1},{2}):", p_in.Name, a_in.Name, o_in.Name);
            }
        }
Пример #28
0
        public static Program.ExitCode AddRH(Role senior, Role junior, rbacLINQ2SQLDataContext db)
        {
            // Check if roles exist
            var roleS = from r in db.Role
                        where r.Name == senior.Name && r.Policy_Id == senior.Policy_Id
                        select r;
            var roleJ = from r in db.Role
                        where r.Name == junior.Name && r.Policy_Id == junior.Policy_Id
                        select r;
            if (roleS.Count() == 1 && roleJ.Count() == 1)
            {
                RoleHierarchy rh = new RoleHierarchy()
                {
                    SeniorRole_Id = roleS.First().Id,
                    JuniorRole_Id = roleJ.First().Id,
                };

                // Check if RH exists:
                var query = from t in db.RoleHierarchy
                            where  t.SeniorRole_Id == rh.SeniorRole_Id
                                && t.JuniorRole_Id == rh.JuniorRole_Id
                            select t;
                if (query.Count() == 1)
                {
                    return Program.ExitCode.ElementExists;
                }
                try
                {
                    db.RoleHierarchy.InsertOnSubmit(rh);
                    db.SubmitChanges();
                    return Program.ExitCode.Success;
                }
                catch
                {
                    return Program.ExitCode.Error;
                }
            }
            else
            {
                return Program.ExitCode.ElementDoesNotExists;
            }
        }
Пример #29
0
        public static Program.ExitCode VisualizeURP(Visio.Page targetPage, rbacLINQ2SQLDataContext db, User user_in)
        {
            Visio.Application visioApplication = null;
            Visio.Document stencilUMLUseCase = null;
            Visio.Document stencilBasicU = null;
            Visio.Shape shape = null;
            Visio.Shape shapeContainer = null;
            Visio.Shape shapeConnector = null;
            List<Visio.Shape> shapeRoles = null;
            List<Visio.Shape> shapePermissions = null;
            Visio.Selection selection = null;
            Visio.Document targetDocument = null;
            Visio.ContainerProperties containerProperties = null;
            int currentDiagramServices = -1;
            int prevDiagramServices;
            System.Array containerMembers = null;

            if (user_in == null || targetPage == null)
                return Program.ExitCode.Error;
            var users = from usr in db.User
                        where usr.Name == user_in.Name && usr.Policy_Id == user_in.Policy_Id
                        select usr;
            //if doesn't exist, return Error status:
            if (users.Count() == 0)
                return Program.ExitCode.ElementDoesNotExists;

            try
            {
                // Turn on all Visio diagram services
                targetDocument = targetPage.Document;
                visioApplication = targetPage.Application;

                // Enable All Diagram Services to enable adding huge-named members to the container
                prevDiagramServices = targetDocument.DiagramServicesEnabled;
                targetDocument.DiagramServicesEnabled = currentDiagramServices;

                stencilUMLUseCase = visioApplication.Documents.
                                        OpenEx(@"C:\MyTestProjects\MCD\diploma\pmtool\pmt\pmt\UML_Use_Case.vssx",
                                        (short)Visio.VisOpenSaveArgs.visOpenHidden);
                stencilBasicU = visioApplication.Documents.
                                        OpenEx(@"Basic_U.vssx",
                                        (short)Visio.VisOpenSaveArgs.visOpenHidden);

                selection = targetPage.CreateSelection(Visio.VisSelectionTypes.visSelTypeEmpty,
                                                       Visio.VisSelectMode.visSelModeOnlySuper, null);
                //=======================================

                // Get all necessary data for drawing a diagram
                User u = users.First();
                var roles = from auth in u.AuthUserRole
                            select auth.Role;
                Dictionary<Role, List<Permission>> rpSet = new Dictionary<Role, List<Permission>>();
                shapePermissions = new List<Visio.Shape>();

                foreach (Role r in roles)
                {
                    var perms = from roleperm in r.RolePermission
                                select roleperm.Permission;
                    rpSet.Add(r, perms.ToList<Permission>());
                }

                double H = 0.5;
                double W = 4;
                double gap = 0.5;
                double centerX = 5;
                double centerY = 1;
                double border = 0.1;

                // Draw permissions with general method DropConnected
                List<string> strPerms = new List<string>();
                int maxStrLenPerms = 0;
                foreach (var rp in rpSet)
                {
                    if (rp.Value.Count == 0)
                    {
                        strPerms.Add("NO PERMISSION ASSIGNED");
                        maxStrLenPerms = strPerms.Last().Length;
                    }
                    else
                    {
                        foreach (Permission p in rp.Value)
                        {
                            if (maxStrLenPerms == 0)
                                strPerms.Add(String.Format("Name: {0}, Policy_Id: {1}", p.Name, p.Policy_Id));
                            else
                                strPerms.Add(String.Format("\nName: {0}, Policy_Id: {1}", p.Name, p.Policy_Id));

                            if (strPerms.Last().Length > maxStrLenPerms)
                                maxStrLenPerms = strPerms.Last().Length;
                        }
                    }
                    shape = targetPage.Drop(stencilBasicU.Masters["Rectangle"],centerX, centerY += H + gap);
                    double charSize = shape.get_Cells("Char.Size").ResultIU;
                    shape.get_Cells("Height").ResultIU = charSize * strPerms.Count + 2 * border;
                    shape.get_Cells("Width").ResultIU = charSize * maxStrLenPerms;
                    shape.Text = String.Concat(strPerms);

                    shapePermissions.Add(shape);

                    strPerms.Clear();
                    maxStrLenPerms = 0;
                }

                //Left-Side Alignment of Permission Rectangles
                if (shapePermissions.Count != 0)
                {
                    foreach (var sh in shapePermissions)
                        selection.Select(sh, (short)Visio.VisSelectArgs.visSelect);
                    selection.Align(Visio.VisHorizontalAlignTypes.visHorzAlignLeft,
                                    Visio.VisVerticalAlignTypes.visVertAlignNone);
                    selection.DeselectAll();
                }

                // Drop Roles (Use Case Objects)
                shapeRoles = new List<Visio.Shape>();
                int i = 0;
                foreach (var rp in rpSet)
                {
                    shape = targetPage.DropConnected(stencilUMLUseCase.Masters["Use Case"],
                                                    shapePermissions.ElementAt(i),
                                                    Visio.VisAutoConnectDir.visAutoConnectDirLeft);
                    shape.Text = String.Format("name: {0}|policy: {1}|cardinality:{2}",
                                                rp.Key.Name, rp.Key.Policy_Id, rp.Key.Cardinality);
                    shapeRoles.Add(shape);
                    selection.Select(shape, (short)Visio.VisSelectArgs.visSelect);
                    i++;
                }

                // Drop a container
                shapeContainer = targetPage.DropContainer(stencilUMLUseCase.Masters["Subsystem"],
                                                            (shapeRoles.Count==0?null:selection));
                shapeContainer.Text = (shapeRoles.Count==0?"NO ROLE AUTHORIZED":"Authorized roles");
                selection.DeselectAll();

                // Move Container to the left to avoid overlapping with Permission Rectangles
                selection.Select(shapeContainer, (short)Visio.VisSelectArgs.visSelect);
                selection.Move(-1, 0);
                selection.DeselectAll();

                // Get height of the container and add a User to the left.
                // Can't use general method DropConnected, cause the container doesn't have such a property
                double containerH = shapeContainer.get_Cells("Height").ResultIU;
                double containerW = shapeContainer.get_Cells("Width").ResultIU;
                double containerXPos = shapeContainer.get_Cells("PinX").ResultIU;
                double containerYPos = shapeContainer.get_Cells("PinY").ResultIU;
                shape = targetPage.Drop(stencilUMLUseCase.Masters["Actor"], containerXPos - containerW / 2 - 1, containerYPos);
                shape.Text = String.Format("USER\nName: {0}\nPassword: {1}\nPolicy_Id: {2}",
                                            user_in.Name,
                                            user_in.Password,
                                            user_in.Policy_Id);
                shapeConnector = targetPage.Drop(stencilUMLUseCase.Masters["Association"], 0, 0);
                ConnectShapes(shape, shapeContainer, shapeConnector);

                // Report on contents of container
                containerProperties = shapeContainer.ContainerProperties;
                containerMembers = containerProperties.GetMemberShapes((int)Visio.VisContainerFlags.visContainerFlagsDefault);
                foreach (int member in containerMembers)
                {
                    System.Diagnostics.Debug.WriteLine(targetPage.Shapes.get_ItemFromID(member).NameU +
                        " |---> " + targetPage.Shapes.get_ItemFromID(member).Text);
                }

                // Finalize
                targetPage.Application.ActiveWindow.DeselectAll();
                targetPage.CenterDrawing();
                stencilUMLUseCase.Close();
                //targetPage.Name = String.Format("URP | Usr:{0};Pol:{1}",user_in.Name,user_in.Policy_Id);
                targetDocument.DiagramServicesEnabled = prevDiagramServices;
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err.Message);
                // Return the Diagram Services status to its previous state if it was set in the try block.
                if (currentDiagramServices != -1 && targetDocument != null)
                    targetDocument.DiagramServicesEnabled = currentDiagramServices;
                throw;
                //return Program.ExitCode.Error;
            }

            return Program.ExitCode.Success;
        }
Пример #30
0
 public static Program.ExitCode RmAssignment(AuthUserRole assgnUR, rbacLINQ2SQLDataContext db)
 {
     //check if the Assignment exists
     var query = from aur in db.AuthUserRole
                 where aur.Role_Id == assgnUR.Role_Id && aur.User_Id == assgnUR.User_Id
                 select aur;
     //if does exist, delete:
     if (query.Count() != 0)
     {
         //Без учета Активных ролей.
         db.AuthUserRole.DeleteOnSubmit(query.First());
         try
         {
             db.SubmitChanges();
             return Program.ExitCode.Success;
         }
         catch (Exception exc)
         {
             return Program.ExitCode.Error;
         }
     }
     else
     {
         return Program.ExitCode.ElementDoesNotExists;
     }
 }