Ejemplo n.º 1
0
    /// <summary>
    /// Prints out the object permissions for one of the groups inside a given workspace
    /// </summary>
    /// <param name="mgr">Object that implements IPermissionManager</param>
    /// <param name="workspaceId">Artifact ID of the workspace whose permissions we want to read</param>
    /// <returns></returns>
    public static async Task PrintGroupPermissions(IPermissionManager mgr, int workspaceId)
    {
        // get an enabled group
        GroupSelector sel = await mgr.GetWorkspaceGroupSelectorAsync(workspaceId);

        if (sel.EnabledGroups.Count > 0)
        {
            GroupRef firstGroup = sel.EnabledGroups.FirstOrDefault();
            // get the permissions associated with said group
            GroupPermissions permissions = await mgr.GetWorkspaceGroupPermissionsAsync(workspaceId, firstGroup);

            // print out Object Permissions
            Console.WriteLine("Permissions for members of {0}", firstGroup.Name);
            foreach (ObjectPermission objPerm in permissions.ObjectPermissions)
            {
                Console.WriteLine("Object Name: {0}", objPerm.Name);
                // we could print out others, but let's just print out if group
                // members can edit the object (true/false)
                Console.WriteLine("Can Edit: {0}", objPerm.EditSelected);
                Console.WriteLine();
            }
        }
        else
        {
            Console.WriteLine("No groups enabled for this workspace ({0})", workspaceId);
        }
    }
Ejemplo n.º 2
0
        public IActionResult SetPermission(long groupId, long screenId, long permissionId, bool allow)
        {
            bool isOk = true;

            try
            {
                if (allow)
                {
                    var gp = new GroupPermissions();
                    gp.GroupId      = groupId;
                    gp.ScreenId     = screenId;
                    gp.PermissionId = permissionId;
                    _uow.GroupPermissionsRepository.Add(gp);
                }
                else
                {
                    _uow.ExecuteSqlCommand("Delete From GroupPermissions Where GroupId=" + groupId + " AND ScreenId=" + screenId + " AND PermissionId=" + permissionId);
                }
                _uow.Save();
            }
            catch (Exception ex)
            { isOk = false; }

            return(Json(isOk));
        }
Ejemplo n.º 3
0
        public IActionResult ModulePermissions(long groupId, long moduleId, bool allow)
        {
            bool isOk    = true;
            var  screens = _uow.ScreensRepository.GetMany(ent => ent.IsActive && !ent.IsDeleted && ent.ModuleId == moduleId).Select(ent => ent.Id).ToHashSet();

            try
            {
                if (allow && screens.Count() > 0)
                {
                    var screenPermissions = _uow.ScreenPermissionsRepository.GetMany(ent => screens.Contains(ent.ScreenId)).ToHashSet();
                    foreach (var item in screenPermissions)
                    {
                        var gp = new GroupPermissions();
                        gp.GroupId      = groupId;
                        gp.ScreenId     = item.ScreenId;
                        gp.PermissionId = item.PermissionId;
                        _uow.GroupPermissionsRepository.Add(gp);
                    }
                    _uow.Save();
                }
                else
                {
                    _uow.ExecuteSqlCommand("Delete From GroupPermissions Where GroupId=" + groupId + " AND ScreenId IN(" + string.Join(",", screens) + ")");
                }
            }
            catch (Exception)
            { isOk = false; }
            return(Json(isOk));
        }
Ejemplo n.º 4
0
        public IActionResult SetAllScreenPermissions(long groupId, long screenId, bool allow)
        {
            bool isOk = true;

            try
            {
                if (allow)
                {
                    var screenPermissions = _uow.ScreenPermissionsRepository.GetMany(ent => ent.ScreenId == screenId).ToHashSet();
                    foreach (var permission in screenPermissions)
                    {
                        var gp = new GroupPermissions();
                        gp.GroupId      = groupId;
                        gp.ScreenId     = screenId;
                        gp.PermissionId = permission.PermissionId;
                        _uow.GroupPermissionsRepository.Add(gp);
                    }
                }
                else
                {
                    _uow.ExecuteSqlCommand("Delete From GroupPermissions Where GroupId=" + groupId + " AND ScreenId=" + screenId);
                }
                _uow.Save();
            }
            catch (Exception ex)
            { isOk = false; }

            return(Json(isOk));
        }
        private void butOK_Click(object sender, EventArgs e)
        {
            if (textDate.errorProvider1.GetError(textDate) != "")
            {
                MessageBox.Show(this, "Please fix data entry errors first.");
                return;
            }
            int newerDays = PIn.Int(textDays.Text);

            if (newerDays > 3000)
            {
                MessageBox.Show(this, "Days must be less than 3000.");
                return;
            }
            _permCur.NewerDays = newerDays;
            _permCur.NewerDate = PIn.Date(textDate.Text);
            try{
                if (_permCur.IsNew)
                {
                    GroupPermissions.Insert(_permCur);
                }
                else
                {
                    GroupPermissions.Update(_permCur);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            }
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Disables the "add document" permission for a list of group IDs for a particular workspace.
        /// </summary>
        /// <param name="mgr">Permission manager service</param>
        /// <param name="rsapi">RSAPI client</param>
        /// <param name="workspaceId">the ID of the workspace whose permissions we are modifying</param>
        /// <param name="groupIds">the groups whose permissions we are modifying</param>
        /// <returns></returns>
        public static async Task <bool> DisableAddDocInWorkspaceForGroups(
            IPermissionManager mgr,
            IRSAPIClient rsapi,
            int workspaceId,
            List <int> groupIds)
        {
            // get group selector for workspace
            GroupSelector sel;

            try
            {
                sel = await mgr.GetWorkspaceGroupSelectorAsync(workspaceId);
            }
            catch (Exception)
            {
                return(false);
            }

            // get group names
            HashSet <string> groupNames = GetGroupNames(rsapi, groupIds);

            foreach (GroupRef group in sel.EnabledGroups)
            {
                // see if the group is one whose permissions
                // we would like to disable
                if (groupNames.Contains(group.Name))
                {
                    GroupPermissions permissions = await mgr.GetWorkspaceGroupPermissionsAsync(workspaceId, group);

                    // get object permissions
                    List <ObjectPermission> objPermissions = permissions.ObjectPermissions;

                    // get the document permission
                    ObjectPermission docPerm = objPermissions.FirstOrDefault(x => x.Name == "Document");
                    if (docPerm != null)
                    {
                        if (docPerm.AddSelected)
                        {
                            // disable Add permission
                            docPerm.AddSelected = false;
                        }
                    }

                    // make changes
                    try
                    {
                        await mgr.SetWorkspaceGroupPermissionsAsync(workspaceId, permissions);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 7
0
 private void butOK_Click(object sender,EventArgs e)
 {
     GroupPermissions.Sync(userControlReportSetup.ListGroupPermissionsForReports,userControlReportSetup.ListGroupPermissionsOld);
     if(userControlReportSetup.ListGroupPermissionsForReports.Exists(x => x.UserGroupNum==_userGroupNum)) {
         HasReportPerms=true;
     }
     GroupPermissions.RefreshCache();
     DialogResult=DialogResult.OK;
 }
Ejemplo n.º 8
0
        public void AddPermissions(List <AppPermission> permissions)
        {
            if (permissions == null || !permissions.Any())
            {
                throw new ArgumentException("No permissions are provided");
            }

            permissions.ForEach(permission =>
                                GroupPermissions.ToList().Add(new AppGroupPermission(permission)));
        }
Ejemplo n.º 9
0
 public void InitializeOnStartup(bool refreshData, long userGroupNum, bool isPermissionMode, bool isCEMT = false)
 {
     _userGroupNum     = userGroupNum;
     _isPermissionMode = isPermissionMode;
     _isCEMT           = isCEMT;
     if (_isPermissionMode)
     {
         butUp.Visible          = false;
         butDown.Visible        = false;
         butSetAll.Visible      = true;
         comboUserGroup.Visible = true;
         labelUserGroup.Visible = true;
         label1.Text            = Lan.g(this, "The current selection's internal name is:");
     }
     else
     {
         butUp.Visible          = true;
         butDown.Visible        = true;
         butSetAll.Visible      = false;
         comboUserGroup.Visible = false;
         labelUserGroup.Visible = false;
         label1.Text            = Lan.g(this, "Move the selected item within its list.") + "\r\n" + Lan.g(this, "The current selection's internal name is:");
     }
     if (refreshData)
     {
         ListDisplayReportAll           = DisplayReports.GetAll(true);
         ListGroupPermissionsForReports = GroupPermissions.GetPermsForReports();
         ListGroupPermissionsOld        = new List <GroupPermission>();
         foreach (GroupPermission perm in ListGroupPermissionsForReports)
         {
             ListGroupPermissionsOld.Add(perm.Copy());
         }
         if (!isCEMT)
         {
             _listUserGroups = UserGroups.GetList();
         }
         else
         {
             _listUserGroups = UserGroups.GetList(true);
         }
         for (int i = 0; i < _listUserGroups.Count; i++)
         {
             comboUserGroup.Items.Add(_listUserGroups[i].Description);
             if (_listUserGroups[i].UserGroupNum == _userGroupNum)
             {
                 comboUserGroup.SelectedIndex = i;
             }
         }
         if (comboUserGroup.SelectedIndex == -1)
         {
             comboUserGroup.SelectedIndex = 0;
         }
     }
     FillGrids();
 }
Ejemplo n.º 10
0
            public string[] GetGroupPerms(string group)
            {
                GroupPermissions perms = null;

                lock (Groups)
                {
                    perms = Groups.Find((x) => x.Group == group.ToUpperInvariant());

                    if (perms == null)
                    {
                        return(new string[0]);
                    }

                    return(perms.Permissions.ToArray());
                }
            }
 private void FormCentralGroupPermEdit_Load(object sender, EventArgs e)
 {
     textName.Text = GroupPermissions.GetDesc(_permCur.PermType);
     if (_permCur.NewerDate.Year < 1880)
     {
         textDate.Text = "";
     }
     else
     {
         textDate.Text = _permCur.NewerDate.ToShortDateString();
     }
     if (_permCur.NewerDays == 0)
     {
         textDays.Text = "";
     }
     else
     {
         textDays.Text = _permCur.NewerDays.ToString();
     }
 }
Ejemplo n.º 12
0
        public void UpdatePermissions(List <AppPermission> permissions)
        {
            // mark deleted revoked permissions
            GroupPermissions.ForEach(permission =>
            {
                if (!permissions.Any(d => d.Id == permission.PermissionId))
                {
                    permission.Delete();
                }
            });


            // add new permissions
            permissions.ForEach(permission =>
            {
                if (!GroupPermissions.Any(d => d.PermissionId == permission.Id))
                {
                    GroupPermissions.Add(new AppGroupPermission(permission));
                }
            });
        }
Ejemplo n.º 13
0
 private void FillListBox()
 {
     Userods.RefreshCache();
     UserGroups.RefreshCache();
     GroupPermissions.RefreshCache();
     listUser.BeginUpdate();
     listUser.Items.Clear();
     if (PrefC.GetBool(PrefName.UserNameManualEntry))
     {
         //Because _listUsers is used to verify the user name typed in, we need to include both non-hidden and CEMT users for offices that type in their credentials instead of picking.
         _listUsers = Userods.GetUsers(true);
     }
     else              //This will be the most common way to fill the user list.  Includes CEMT users.
     {
         _listUsers = Userods.GetUsers(true);
     }
     for (int i = 0; i < _listUsers.Count; i++)
     {
         listUser.Items.Add(_listUsers[i]);
     }
     listUser.SelectedIndex = 0;
     listUser.EndUpdate();
 }
Ejemplo n.º 14
0
        public IActionResult GiveGroupAllPermissions(long groupId)
        {
            bool isOk = true;

            try
            {
                var groupPsermissions = _security.GetGroupPermissions(groupId).ToHashSet();
                var screenPermissions = _uow.ScreenPermissionsRepository.GetMany(ent => !groupPsermissions.Any(gp => gp.ScreenId == ent.ScreenId && gp.PermissionId == ent.PermissionId)).ToHashSet();
                foreach (var item in screenPermissions)
                {
                    var gp = new GroupPermissions();
                    gp.GroupId      = groupId;
                    gp.ScreenId     = item.ScreenId;
                    gp.PermissionId = item.PermissionId;
                    _uow.GroupPermissionsRepository.Add(gp);
                }
                _uow.Save();
            }
            catch (Exception ex)
            { isOk = false; }

            return(Json(isOk));
        }
Ejemplo n.º 15
0
        private DialogResult userControlSecurityTabs_ReportPermissionChecked(object sender, SecurityEventArgs e)
        {
            GroupPermission        perm    = e.Perm;
            FormCentralReportSetup FormCRS = new FormCentralReportSetup(perm.UserGroupNum, true);

            FormCRS.ShowDialog();
            if (FormCRS.DialogResult == DialogResult.Cancel)
            {
                return(FormCRS.DialogResult);
            }
            if (!FormCRS.HasReportPerms)             //Only insert base Reports permission if the user actually has any reports allowed
            {
                return(FormCRS.DialogResult);
            }
            try {
                GroupPermissions.Insert(perm);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return(DialogResult.Cancel);
            }
            return(FormCRS.DialogResult);
        }
Ejemplo n.º 16
0
            static void CreateGroup(string name, bool guest, string parent, byte r, byte g, byte b, string[] nodes, MySQLConnector conn)
            {
                long id;

                using (var bl = new MySQLQueryBuilder(SqlPermissions.SQLSafeName))
                {
                    bl.InsertInto(TableName,
                                  new DataParameter(ColumnNames.Name, name),
                                  new DataParameter(ColumnNames.ApplyToGuests, guest),
                                  new DataParameter(ColumnNames.Parent, parent),
                                  new DataParameter(ColumnNames.Chat_Red, r),
                                  new DataParameter(ColumnNames.Chat_Green, g),
                                  new DataParameter(ColumnNames.Chat_Blue, b)
                                  );

                    id = ((IDataConnector)conn).ExecuteInsert(bl);
                }

                foreach (var nd in nodes)
                {
                    var nodeId = PermissionTable.Insert(conn, nd, false);
                    GroupPermissions.Insert(conn, id, nodeId);
                }
            }
Ejemplo n.º 17
0
 public string GenerateLink(LinkType type, int clientId, IEnumerable <int> groupIds, GroupPermissions scope)
 {
     return(GenerateLink(type, clientId, groupIds, scope, null));
 }
Ejemplo n.º 18
0
        public string GenerateLink(LinkType type, int clientId, IEnumerable <int> groupIds, string redirectUri, DisplayOptions display, GroupPermissions scope, string state)
        {
            var sb  = new StringBuilder($"https://oauth.vk.com/authorize?client_id={clientId}");
            var uri = string.IsNullOrWhiteSpace(redirectUri) ? "https://oauth.vk.com/blank.html" : redirectUri;

            sb.Append($"&group_ids={string.Join(",", groupIds)}");
            sb.Append($"&scope={scope:D}");
            sb.Append($"&response_type={type.ToString().ToLower()}");
            sb.Append($"&v={RequestSettings.ApiVersion}");
            sb.Append($"&redirect_uri={uri}");

            if (display != DisplayOptions.Default)
            {
                sb.Append($"&display={display.ToString().ToLower()}");
            }

            if (!string.IsNullOrWhiteSpace(state))
            {
                sb.Append($"&state={state}");
            }

            return(sb.ToString());
        }
Ejemplo n.º 19
0
        public static string GetSnippet(Type typeClass, SnippetType snipType, bool isMobile)
        {
            //bool isMobile=CrudGenHelper.IsMobile(typeClass);
            string Sname = GetSname(typeClass.Name);

            FieldInfo[] fields  = typeClass.GetFields();         //We can't assume they are in the correct order.
            FieldInfo   priKey  = null;
            FieldInfo   priKey1 = null;
            FieldInfo   priKey2 = null;

            if (isMobile)
            {
                priKey1 = CrudGenHelper.GetPriKeyMobile1(fields, typeClass.Name);
                priKey2 = CrudGenHelper.GetPriKeyMobile2(fields, typeClass.Name);
            }
            else
            {
                priKey = CrudGenHelper.GetPriKey(fields, typeClass.Name);
            }
            string priKeyParam  = null;
            string priKeyParam1 = null;
            string priKeyParam2 = null;

            if (isMobile)
            {
                priKeyParam1 = priKey1.Name.Substring(0, 1).ToLower() + priKey1.Name.Substring(1);           //lowercase initial letter.  Example customerNum
                priKeyParam2 = priKey2.Name.Substring(0, 1).ToLower() + priKey2.Name.Substring(1);           //lowercase initial letter.  Example patNum
            }
            else
            {
                priKeyParam = priKey.Name.Substring(0, 1).ToLower() + priKey.Name.Substring(1);                        //lowercase initial letter.  Example patNum
            }
            string           obj             = typeClass.Name.Substring(0, 1).ToLower() + typeClass.Name.Substring(1); //lowercase initial letter.  Example feeSched
            string           tablename       = CrudGenHelper.GetTableName(typeClass);                                  //in lowercase now.  Example feesched
            List <FieldInfo> fieldsExceptPri = null;

            if (isMobile)
            {
                fieldsExceptPri = CrudGenHelper.GetFieldsExceptPriKey(fields, priKey2);             //for mobile, only excludes PK2
            }
            else
            {
                fieldsExceptPri = CrudGenHelper.GetFieldsExceptPriKey(fields, priKey);
            }
            switch (snipType)
            {
            default:
                return("snippet type not found.");

            case SnippetType.Insert:
                if (isMobile)
                {
                    return(GetInsert(typeClass.Name, obj, null, true));
                }
                else
                {
                    return(GetInsert(typeClass.Name, obj, priKey.Name, false));
                }

            case SnippetType.Update:
                return(GetUpdate(typeClass.Name, obj, isMobile));

            case SnippetType.EntireSclass:
                if (isMobile)
                {
                    return(GetEntireSclassMobile(typeClass.Name, obj, priKey1.Name, priKey2.Name, Sname, tablename, priKeyParam1, priKeyParam2));
                }
                else
                {
                    List <Permissions> listAuditTrailPerms = GroupPermissions.GetPermsFromCrudAuditPerm(CrudGenHelper.GetCrudAuditPermForClass(typeClass));
                    return(GetEntireSclass(typeClass.Name, obj, priKey.Name, Sname, tablename, priKeyParam, listAuditTrailPerms));
                }

            case SnippetType.CreateTable:
                return("Currently unavailable.");

                /*
                 * if(isMobile) {
                 *      return GetCreateTable(tablename,priKey1.Name,priKey2.Name,fieldsExceptPri);
                 * }
                 * else {
                 *      return GetCreateTable(tablename,priKey.Name,null,fieldsExceptPri);
                 * }*/
            }
        }
Ejemplo n.º 20
0
        public static string GetSnippet(Type typeClass, SnippetType snipType, bool isMobile)
        {
            //bool isMobile=CrudGenHelper.IsMobile(typeClass);
            string Sname = GetSname(typeClass.Name);

            FieldInfo[] fields  = typeClass.GetFields();         //We can't assume they are in the correct order.
            FieldInfo   priKey  = null;
            FieldInfo   priKey1 = null;
            FieldInfo   priKey2 = null;

            if (isMobile)
            {
                priKey1 = CrudGenHelper.GetPriKeyMobile1(fields, typeClass.Name);
                priKey2 = CrudGenHelper.GetPriKeyMobile2(fields, typeClass.Name);
            }
            else
            {
                priKey = CrudGenHelper.GetPriKey(fields, typeClass.Name);
            }
            string priKeyParam  = null;
            string priKeyParam1 = null;
            string priKeyParam2 = null;

            if (isMobile)
            {
                priKeyParam1 = priKey1.Name.Substring(0, 1).ToLower() + priKey1.Name.Substring(1);           //lowercase initial letter.  Example customerNum
                priKeyParam2 = priKey2.Name.Substring(0, 1).ToLower() + priKey2.Name.Substring(1);           //lowercase initial letter.  Example patNum
            }
            else
            {
                priKeyParam = priKey.Name.Substring(0, 1).ToLower() + priKey.Name.Substring(1);                        //lowercase initial letter.  Example patNum
            }
            string           obj             = typeClass.Name.Substring(0, 1).ToLower() + typeClass.Name.Substring(1); //lowercase initial letter.  Example feeSched
            string           tablename       = CrudGenHelper.GetTableName(typeClass);                                  //in lowercase now.  Example feesched
            List <FieldInfo> fieldsExceptPri = null;

            if (isMobile)
            {
                fieldsExceptPri = CrudGenHelper.GetFieldsExceptPriKey(fields, priKey2);             //for mobile, only excludes PK2
            }
            else
            {
                fieldsExceptPri = CrudGenHelper.GetFieldsExceptPriKey(fields, priKey);
            }
            bool isTableHist        = CrudGenHelper.IsTableHist(typeClass);
            List <DbSchemaCol> cols = CrudQueries.GetListColumns(priKey.Name, null, fieldsExceptPri, false);

            switch (snipType)
            {
            default:
                return("snippet type not found.");

            case SnippetType.Insert:
                if (isMobile)
                {
                    return(GetInsert(typeClass.Name, obj, null, true));
                }
                else
                {
                    return(GetInsert(typeClass.Name, obj, priKey.Name, false));
                }

            case SnippetType.Update:
                return(GetUpdate(typeClass.Name, obj, isMobile, isTableHist));

            case SnippetType.EntireSclass:
                if (isMobile)
                {
                    return(GetEntireSclassMobile(typeClass.Name, obj, priKey1.Name, priKey2.Name, Sname, tablename, priKeyParam1, priKeyParam2, isTableHist));
                }
                else
                {
                    List <Permissions> listAuditTrailPerms = GroupPermissions.GetPermsFromCrudAuditPerm(CrudTableAttribute.GetCrudAuditPermForClass(typeClass));
                    return(GetEntireSclass(typeClass.Name, obj, priKey.Name, Sname, tablename, priKeyParam, listAuditTrailPerms, isTableHist));
                }

            case SnippetType.AddTable:
                return(CrudSchemaRaw.AddTable(tablename, cols, 0, false, false));

            case SnippetType.AddColumnEnd:
                return(string.Join("\r\n\r\n", cols.Select(x => CrudSchemaRaw.AddColumnEnd(tablename, x, 0, false, typeClass).Trim())));

            case SnippetType.AddIndex:
                return(string.Join("\r\n\r\n", cols.Select(x => CrudSchemaRaw.AddIndex(tablename, x.ColumnName, 0).Trim())));

            case SnippetType.DropColumn:
                return(string.Join("\r\n\r\n", cols.Select(x => CrudSchemaRaw.DropColumn(tablename, x.ColumnName, 0).Trim())));
            }
        }
Ejemplo n.º 21
0
 public List <Permission> GetPermissions()
 {
     return(GroupPermissions.Select(x => x.Permission).ToList());
 }
        ///<summary>Syncs the database to reflect what is contained within listNew.</summary>
        public static void Sync(List <GroupPermission> listNew, List <GroupPermission> listDB)
        {
            //Adding items to lists changes the order of operation. All inserts are completed first, then updates, then deletes.
            List <GroupPermission> listIns    = new List <GroupPermission>();
            List <GroupPermission> listUpdNew = new List <GroupPermission>();
            List <GroupPermission> listUpdDB  = new List <GroupPermission>();
            List <GroupPermission> listDel    = new List <GroupPermission>();

            listNew.Sort((GroupPermission x, GroupPermission y) => { return(x.GroupPermNum.CompareTo(y.GroupPermNum)); });         //Anonymous function, sorts by compairing PK.  Lambda expressions are not allowed, this is the one and only exception.  JS approved.
            listDB.Sort((GroupPermission x, GroupPermission y) => { return(x.GroupPermNum.CompareTo(y.GroupPermNum)); });          //Anonymous function, sorts by compairing PK.  Lambda expressions are not allowed, this is the one and only exception.  JS approved.
            int             idxNew = 0;
            int             idxDB  = 0;
            GroupPermission fieldNew;
            GroupPermission fieldDB;

            //Because both lists have been sorted using the same criteria, we can now walk each list to determine which list contians the next element.  The next element is determined by Primary Key.
            //If the New list contains the next item it will be inserted.  If the DB contains the next item, it will be deleted.  If both lists contain the next item, the item will be updated.
            while (idxNew < listNew.Count || idxDB < listDB.Count)
            {
                fieldNew = null;
                if (idxNew < listNew.Count)
                {
                    fieldNew = listNew[idxNew];
                }
                fieldDB = null;
                if (idxDB < listDB.Count)
                {
                    fieldDB = listDB[idxDB];
                }
                //begin compare
                if (fieldNew != null && fieldDB == null)             //listNew has more items, listDB does not.
                {
                    listIns.Add(fieldNew);
                    idxNew++;
                    continue;
                }
                else if (fieldNew == null && fieldDB != null)             //listDB has more items, listNew does not.
                {
                    listDel.Add(fieldDB);
                    idxDB++;
                    continue;
                }
                else if (fieldNew.GroupPermNum < fieldDB.GroupPermNum)               //newPK less than dbPK, newItem is 'next'
                {
                    listIns.Add(fieldNew);
                    idxNew++;
                    continue;
                }
                else if (fieldNew.GroupPermNum > fieldDB.GroupPermNum)               //dbPK less than newPK, dbItem is 'next'
                {
                    listDel.Add(fieldDB);
                    idxDB++;
                    continue;
                }
                //Both lists contain the 'next' item, update required
                listUpdNew.Add(fieldNew);
                listUpdDB.Add(fieldDB);
                idxNew++;
                idxDB++;
            }
            //Commit changes to DB
            for (int i = 0; i < listIns.Count; i++)
            {
                GroupPermissions.InsertNoCache(listIns[i]);
            }
            for (int i = 0; i < listUpdNew.Count; i++)
            {
                GroupPermissions.UpdateNoCache(listUpdNew[i]);
            }
            for (int i = 0; i < listDel.Count; i++)
            {
                GroupPermissions.DeleteNoCache(listDel[i]);
            }
        }
Ejemplo n.º 23
0
        ///<summary>Function used by threads to connect to remote databases and sync user settings.</summary>
        private static void ConnectAndSyncUsers(ODThread odThread)
        {
            CentralConnection      connection          = (CentralConnection)odThread.Parameters[0];
            List <CentralUserData> listCentralUserData = (List <CentralUserData>)odThread.Parameters[1];
            string serverName = "";

            if (connection.ServiceURI != "")
            {
                serverName = connection.ServiceURI;
            }
            else
            {
                serverName = connection.ServerName + ", " + connection.DatabaseName;
            }
            if (!CentralConnectionHelper.UpdateCentralConnection(connection, false))            //No updating the cache since we're going to be connecting to multiple remote servers at the same time.
            {
                odThread.Tag = new List <string>()
                {
                    serverName + "\r\n", "", ""
                };
                connection.ConnectionStatus = "OFFLINE";
                return;
            }
            string remoteSyncCode = PrefC.GetStringNoCache(PrefName.CentralManagerSyncCode);

            if (remoteSyncCode != _syncCode)
            {
                if (remoteSyncCode == "")
                {
                    Prefs.UpdateStringNoCache(PrefName.CentralManagerSyncCode, _syncCode);                   //Lock in the sync code for the remote server.
                }
                else
                {
                    odThread.Tag = new List <string>()
                    {
                        serverName + "\r\n", "", remoteSyncCode
                    };
                    return;
                }
            }
            //Get remote users, usergroups, associated permissions, and alertsubs
            List <Userod> listRemoteUsers = Userods.GetUsersNoCache();

            #region Detect Conflicts
            //User conflicts
            bool   nameConflict  = false;
            string nameConflicts = "";
            for (int i = 0; i < _listCEMTUsers.Count; i++)
            {
                for (int j = 0; j < listRemoteUsers.Count; j++)
                {
                    if (listRemoteUsers[j].UserName == _listCEMTUsers[i].UserName && listRemoteUsers[j].UserNumCEMT == 0)                 //User doesn't belong to CEMT
                    {
                        nameConflicts += listRemoteUsers[j].UserName + " already exists in " + serverName + "\r\n";
                        nameConflict   = true;
                        break;
                    }
                }
            }
            if (nameConflict)
            {
                odThread.Tag = new List <string>()
                {
                    serverName + "\r\n", nameConflicts, ""
                };
                return;                //Skip on to the next connection.
            }
            #endregion Detect Conflicts
            List <UserGroup> listRemoteCEMTUserGroups = UserGroups.GetCEMTGroupsNoCache();
            List <UserGroup> listCEMTUserGroups       = new List <UserGroup>();
            List <AlertSub>  listRemoteAlertSubs      = AlertSubs.GetAll();
            List <Clinic>    listRemoteClinics        = Clinics.GetClinicsNoCache();
            List <AlertSub>  listAlertSubsToInsert    = new List <AlertSub>();
            for (int i = 0; i < listCentralUserData.Count; i++)
            {
                listCEMTUserGroups.Add(listCentralUserData[i].UserGroup.Copy());
            }
            //SyncUserGroups returns the list of UserGroups for deletion so it can be used after syncing Users and GroupPermissions.
            List <UserGroup> listRemoteCEMTUserGroupsForDeletion = CentralUserGroups.Sync(listCEMTUserGroups, listRemoteCEMTUserGroups);
            listRemoteCEMTUserGroups = UserGroups.GetCEMTGroupsNoCache();
            for (int i = 0; i < listCentralUserData.Count; i++)
            {
                List <GroupPermission> listGroupPerms = new List <GroupPermission>();
                for (int j = 0; j < listRemoteCEMTUserGroups.Count; j++)
                {
                    if (listCentralUserData[i].UserGroup.UserGroupNumCEMT == listRemoteCEMTUserGroups[j].UserGroupNumCEMT)
                    {
                        for (int k = 0; k < listCentralUserData[i].ListGroupPermissions.Count; k++)
                        {
                            listCentralUserData[i].ListGroupPermissions[k].UserGroupNum = listRemoteCEMTUserGroups[j].UserGroupNum;                          //fixing primary keys to be what's in remote db
                        }
                        listGroupPerms = GroupPermissions.GetPermsNoCache(listRemoteCEMTUserGroups[j].UserGroupNum);
                    }
                }
                CentralUserods.Sync(listCentralUserData[i].ListUsers, listRemoteUsers);
                CentralGroupPermissions.Sync(listCentralUserData[i].ListGroupPermissions, listGroupPerms);
            }
            //Sync usergroup attaches
            SyncUserGroupAttaches(listCentralUserData);
            for (int j = 0; j < listRemoteCEMTUserGroupsForDeletion.Count; j++)
            {
                UserGroups.DeleteNoCache(listRemoteCEMTUserGroupsForDeletion[j]);
            }
            if (_listAlertSubs.Count > 0)
            {
                listRemoteUsers = Userods.GetUsersNoCache();              //Refresh users so we can do alertsubs.
            }
            //For each AlertSub, make a copy of that AlertSub for each Clinic.
            foreach (AlertSub alertSub in _listAlertSubs)
            {
                foreach (Clinic clinic in listRemoteClinics)
                {
                    AlertSub alert = new AlertSub();
                    alert.ClinicNum = clinic.ClinicNum;
                    alert.Type      = alertSub.Type;
                    alert.UserNum   = listRemoteUsers.Find(x => x.UserName == _listCEMTUsers.Find(y => y.UserNum == alertSub.UserNum).UserName).UserNum;
                    listAlertSubsToInsert.Add(alert);
                }
            }
            AlertSubs.DeleteAndInsertForSuperUsers(_listCEMTUsers, listAlertSubsToInsert);
            //Refresh server's cache of userods
            Signalods.SetInvalidNoCache(InvalidType.Security);
            SecurityLogs.MakeLogEntryNoCache(Permissions.SecurityAdmin, 0, "Enterprise Management Tool synced users.");
            odThread.Tag = new List <string>()
            {
                "", "", ""
            };                                                       //No errors.
        }
Ejemplo n.º 24
0
        ///<summary>Generic function that launches different thread methods depending on how isSyncUsers and isSyncLocks are set.  Set only one or the other to true.</summary>
        private static string SyncAll(List <CentralConnection> listConns, bool isSyncUsers, bool isSyncLocks)
        {
            //Get CEMT users, groups, and associated permissions
            ListSyncErrors       = new List <string>();
            _listCEMTUsers       = Userods.GetUsersForCEMT();
            _securityLockDate    = PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString();
            _securityLockDays    = PrefC.GetInt(PrefName.SecurityLockDays);
            _securityLockAdmin   = PrefC.GetBool(PrefName.SecurityLockIncludesAdmin);
            _securityCentralLock = PrefC.GetBool(PrefName.CentralManagerSecurityLock);
            _syncCode            = PrefC.GetString(PrefName.CentralManagerSyncCode);
            _listAlertSubs       = AlertSubs.GetAll();
            List <CentralUserData> listCentralUserData = new List <CentralUserData>();
            List <UserGroup>       listUserGroups      = UserGroups.GetCEMTGroups();

            foreach (UserGroup userGroup in listUserGroups)             //for each CEMT user group
            //get all usergroupattaches, userods, and grouppermissions.
            {
                List <UserGroupAttach> listUserGroupAttaches = UserGroupAttaches.GetForUserGroup(userGroup.UserGroupNum);
                List <Userod>          listUserOds           = Userods.GetForGroup(userGroup.UserGroupNum);
                List <GroupPermission> listGroupPermissions  = GroupPermissions.GetPerms(userGroup.UserGroupNum);
                //then create a new CentralUserData and add it to the list.
                listCentralUserData.Add(new CentralUserData(userGroup, listUserOds, listGroupPermissions, listUserGroupAttaches));
            }
            string failedConns     = "";
            string nameConflicts   = "";
            string failedSyncCodes = "";

            for (int i = 0; i < listConns.Count; i++)
            {
                List <CentralUserData> listCentralDataForThreads = new List <CentralUserData>();
                for (int j = 0; j < listCentralUserData.Count; j++)
                {
                    listCentralDataForThreads.Add(listCentralUserData[j].Copy());
                }
                ODThread odThread = null;
                if (isSyncUsers)
                {
                    odThread = new ODThread(ConnectAndSyncUsers, new object[] { listConns[i], listCentralDataForThreads });
                    odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper));
                }
                else if (isSyncLocks)
                {
                    odThread = new ODThread(ConnectAndSyncLocks, new object[] { listConns[i] });
                    odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper));
                }
                else
                {
                    odThread = new ODThread(ConnectAndSyncAll, new object[] { listConns[i], listCentralDataForThreads });
                    odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper));
                }
                odThread.GroupName = "Sync";
                odThread.Start(false);
            }
            ODThread.JoinThreadsByGroupName(Timeout.Infinite, "Sync");
            List <ODThread> listComplThreads = ODThread.GetThreadsByGroupName("Sync");

            for (int i = 0; i < listComplThreads.Count; i++)
            {
                if (listComplThreads[i].Tag == null)
                {
                    continue;                    //Failed due to lacking credentials
                }
                failedConns     += ((List <string>)listComplThreads[i].Tag)[0];
                nameConflicts   += ((List <string>)listComplThreads[i].Tag)[1];
                failedSyncCodes += ((List <string>)listComplThreads[i].Tag)[2];
                listComplThreads[i].QuitAsync();
            }
            string errorText = "";

            if (failedConns == "" && nameConflicts == "" && failedSyncCodes == "")
            {
                errorText += "Done";
            }
            if (failedConns != "")
            {
                errorText = "Failed Connections:\r\n" + failedConns + "Please try these connections again.\r\n";
            }
            if (nameConflicts != "")
            {
                errorText += "Name Conflicts:\r\n" + nameConflicts + "Please rename users and try again.\r\n";
            }
            if (failedSyncCodes != "")
            {
                errorText += "Incorrect Sync Codes:\r\n" + failedSyncCodes + "\r\n";
            }
            return(errorText);
        }
Ejemplo n.º 25
0
 public string GenerateLink(LinkType type, int clientId, IEnumerable <int> groupIds, GroupPermissions scope, string state)
 {
     return(GenerateLink(type, clientId, groupIds, null, DisplayOptions.Default, scope, state));
 }