public string GenerateAddUserStatements(SyncUser user)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("DECLARE @UserName nvarchar(256)");
            stringBuilder.AppendLine("DECLARE @Email nvarchar(256)");
            stringBuilder.AppendLine($"SET @UserName= '******'");
            stringBuilder.AppendLine($"SET @Email= '{user.Email}'");
            stringBuilder.AppendLine("DECLARE @Now datetime");
            stringBuilder.AppendLine("SET @Now=GETDATE()");
            stringBuilder.AppendLine("EXEC aspnet_Membership_CreateUser 'sitecore',@userName,'qOvF8m8F2IcWMvfOBjJYHmfLABc=', 'OM5gu45RQuJ76itRvkSPFw==',@Email,'','',1,@Now,@Now,0,0,null");

            stringBuilder.AppendLine("DECLARE @UserId nvarchar(256)");
            stringBuilder.AppendLine("SELECT TOP 1 @UserId = [UserId] FROM [aspnet_Users] WHERE [UserName] = @UserName");
            stringBuilder.AppendLine("UPDATE [aspnet_Membership] SET [PasswordFormat] = '1' WHERE UserId = @UserId");
            stringBuilder.AppendLine("UPDATE [aspnet_Membership] SET [Comment] = '' WHERE UserId = @UserId");

            stringBuilder.AppendLine("INSERT [dbo].[aspnet_Profile] ([UserId], [PropertyNames], [PropertyValuesString], [PropertyValuesBinary], [LastUpdatedDate])");
            stringBuilder.AppendLine(" VALUES (@UserId,");
            stringBuilder.AppendLine("  N'IsAdministrator:S:0:5:Portrait:S:5:29:ProfileItemId:S:34:38:SerializedData:B:0:3875:', ");
            stringBuilder.AppendLine("  N'Falseoffice/16x16/default_user.png{AE4C4969-5B7E-4B4E-9042-B2D8701CE214}', ");
            stringBuilder.AppendLine("  0x0001000000FFFFFFFF01000000000000000401000000E20153797374656D2E436F6C6C656374696F6E732E47656E657269632E44696374696F6E61727960325B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D2C5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D040000000756657273696F6E08436F6D7061726572084861736853697A650D4B657956616C756550616972730003000308920153797374656D2E436F6C6C656374696F6E732E47656E657269632E47656E65726963457175616C697479436F6D706172657260315B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D08E60153797374656D2E436F6C6C656374696F6E732E47656E657269632E4B657956616C75655061697260325B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D2C5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D5B5DCE00000009020000002500000009030000000402000000920153797374656D2E436F6C6C656374696F6E732E47656E657269632E47656E65726963457175616C697479436F6D706172657260315B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D00000000070300000000010000001500000003E40153797374656D2E436F6C6C656374696F6E732E47656E657269632E4B657956616C75655061697260325B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D2C5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D04FCFFFFFFE40153797374656D2E436F6C6C656374696F6E732E47656E657269632E4B657956616C75655061697260325B5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D2C5B53797374656D2E537472696E672C206D73636F726C69622C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038395D5D02000000036B65790576616C7565010106050000000957616C6C70617065720606000000312F73697465636F72652F7368656C6C2F7468656D65732F6261636B67726F756E64732F6C69676874686F7573652E6A706701F9FFFFFFFCFFFFFF06080000001357616C6C70617065724261636B67726F756E640609000000072330373333374301F6FFFFFFFCFFFFFF060B0000001157616C6C7061706572506F736974696F6E060C0000000643656E74657201F3FFFFFFFCFFFFFF060E0000001464696765737463726564656E7469616C68617368060F00000020373130373464333335653834393632396562616532383434656165333436306101F0FFFFFFFCFFFFFF06110000002164696765737463726564656E7469616C68617368776974686F7574646F6D61696E061200000020313961323764323333663534633962303930303764303533326634666464343301EDFFFFFFFCFFFFFF06140000001F2F73697465636F72655C61646D696E2F526962626F6E2F4D792053747269700615000000267B44333341303634312D394631432D343938342D383334322D3036353543334430463132337D01EAFFFFFFFCFFFFFF06170000000D5061636B616765722F46696C6506180000002F536D61727420546F6F6C7320204164642056657273696F6E20616E6420436F707920436F6E74656E7431302E7A697001E7FFFFFFFCFFFFFF061A000000372F73697465636F72655C61646D696E2F557365724F7074696F6E732E436F6E74656E74456469746F722E56697369626C65537472697073061B000000AC037B43334643454242392D463338462D344142342D383537462D4346433431354236413334327D7C7B44304643393944392D354336352D343341332D414342362D3434393544343446423045377D7C7B39324144453739322D363833462D343830442D413330412D3031433146314241414235337D7C7B46353142433531412D463541462D343144462D414431312D4630443142343846464339337D7C7B36353533363336462D453930342D344632442D423232322D3039304430413236323938437D7C7B34434636343731362D384238432D344142432D383643322D4639433546334646313132387D7C7B44363030433133392D393244372D343844452D424239462D3438313241334442394138427D7C7B34383936374331392D433338372D343534442D384544322D3536324446313430394430387D7C7B41454439354537452D383734412D344346302D393234422D3844443930464338443733307D7C7B33333645393943382D433435462D344342372D393133362D4339463846453830324538467D7C7B42423246424235352D454243382D343732342D394131462D3337424346454430333730447D01E4FFFFFFFCFFFFFF061D000000312F73697465636F72655C61646D696E2F436F6E74656E7420456469746F722F53656374696F6E732F436F6C6C6170736564061E0000000B517569636B496E666F3D3001E1FFFFFFFCFFFFFF0620000000232F73697465636F72655C61646D696E2F4D656469612F55706C6F616465644974656D730621000000E0043230313430323039543231303432342373697465636F72653A2F2F6D61737465722F7B44363441363142352D463836332D343634432D423534352D3045434639423637373141437D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B35413631433446392D363730322D343143352D424245422D3131393439453243453345467D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B31413033373138442D364338462D343732322D424332352D3635464539424245353839367D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B39464445464539452D343742332D343532392D394333332D3431394230333239314430467D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B38374530313239352D363545342D343943372D383939442D3544304441433744434534387D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B34393134424644442D303830392D344635302D413235332D3545423030353232454544337D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B42373138433944302D383636332D343746342D424635392D3245434443354633353038317D3F6C616E673D64652D4445267665723D317C73697465636F72653A2F2F6D61737465722F7B42443643364230462D304333382D344433432D393131322D3141444535443537434536347D3F6C616E673D64652D4445267665723D317C01DEFFFFFFFCFFFFFF0623000000212F73697465636F72655C61646D696E2F5075626C6973682F4C616E677561676573062400000002656E01DBFFFFFFFCFFFFFF06260000001F2F73697465636F72655C61646D696E2F5075626C6973682F546172676574730627000000267B38453038303632362D444443332D344546342D413144312D4630424534413230303235347D01D8FFFFFFFCFFFFFF06290000002A2F73697465636F72655C61646D696E2F5075626C6973682F496E6372656D656E74616C5075626C697368062A0000000566616C736501D5FFFFFFFCFFFFFF062C000000242F73697465636F72655C61646D696E2F5075626C6973682F536D6172745075626C697368092A00000001D2FFFFFFFCFFFFFF062F000000212F73697465636F72655C61646D696E2F5075626C6973682F52657075626C6973680630000000047472756501CFFFFFFFFCFFFFFF0632000000272F73697465636F72655C61646D696E2F5075626C6973682F5075626C6973684368696C6472656E093000000001CCFFFFFFFCFFFFFF0635000000282F73697465636F72655C61646D696E2F436F6E74656E7420456469746F722F4C616E67756167657306360000000B65742D45457C656E2D474201C9FFFFFFFCFFFFFF0638000000222F73697465636F72655C61646D696E2F4C69737476696577732F4974656D4C69737406390000000744657461696C7301C6FFFFFFFCFFFFFF063B0000001F2F73697465636F72655C61646D696E732F526563656E74557365724C697374063C0000001173697465636F72655C546573745573657201C3FFFFFFFCFFFFFF063E000000292F73697465636F72655C61646D696E2F486973746F72792F4164642E46726F6D2E54656D706C617465063F000000267B42463242384441322D334342412D343835442D384638352D3337383842384146424442467D01C0FFFFFFFCFFFFFF0641000000202F73697465636F72655C61646D696E2F486973746F72792F54656D706C6174650642000000267B42463242384441322D334342412D343835442D384638352D3337383842384146424442467D0B, GETUTCDATE())");
            stringBuilder.AppendLine("GO");
            return(stringBuilder.ToString());
        }
Пример #2
0
        public virtual void Save(SyncUser user)
        {
            var path = GetPathForUser(user.UserName);

            var parent = Path.GetDirectoryName(path);
            if (!Directory.Exists(parent)) Directory.CreateDirectory(parent);

            using (var writer = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                _userFormatter.WriteSerializedUser(user, writer);
            }
        }
Пример #3
0
        /// <summary>
        /// Gets the Paratext user for a comment from the specified sync user id and owner id.
        /// </summary>
        private async Task <(string SyncUserId, string ParatextUsername, bool CanWritePTNoteOnProject)> GetSyncUserAsync(
            string syncUserRef, string ownerRef)
        {
            // if the owner is a PT user, then get the PT username
            if (!_userIdToUsername.TryGetValue(ownerRef, out string paratextUsername))
            {
                if (_ptProjectUsersWhoCanWriteNotes.Contains(ownerRef))
                {
                    Attempt <UserSecret> attempt = await _userSecrets.TryGetAsync(ownerRef);

                    if (attempt.TryResult(out UserSecret userSecret))
                    {
                        paratextUsername = _paratextService.GetParatextUsername(userSecret);
                    }
                    // cache the results
                    _userIdToUsername[ownerRef] = paratextUsername;
                }
                else
                {
                    paratextUsername = null;
                }
            }

            bool canWritePTNoteOnProject = paratextUsername != null;

            SyncUser syncUser;

            // check if comment has already been synced before
            if (syncUserRef == null || !_idToSyncUser.TryGetValue(syncUserRef, out syncUser))
            {
                // the comment has never been synced before (or syncUser is missing)
                // if the owner is not a PT user on the project, then use the current user's PT username
                if (paratextUsername == null)
                {
                    paratextUsername = _currentParatextUsername;
                }
                if (!_usernameToSyncUser.TryGetValue(paratextUsername, out syncUser))
                {
                    // the PT user has never been associated with a comment, so generate a new sync user id and add it
                    // to the NewSyncUsers property
                    syncUser = new SyncUser
                    {
                        Id = ObjectId.GenerateNewId().ToString(),
                        ParatextUsername = paratextUsername
                    };
                    _idToSyncUser[syncUser.Id] = syncUser;
                    _usernameToSyncUser[syncUser.ParatextUsername] = syncUser;
                    NewSyncUsers.Add(syncUser);
                }
            }
            return(syncUser.Id, syncUser.ParatextUsername, canWritePTNoteOnProject);
        }
Пример #4
0
        public JsonResult GetClipboard(string Username, string Password, int SequenceNumber, int version)
        {
            if (WebSecurity.Login(Encrypter.base64Decode(Username), Encrypter.base64Decode(Password)) == true)
            {
                int UserId = WebSecurity.GetUserId(Encrypter.base64Decode(Username));

                // Business Logic to get the clipboard if any or hold the socket open
                SyncUser userClipboard = DatabaseClipBoard.GetClipboard(UserId, SequenceNumber);
                if (userClipboard != null)
                {
                    return(Json(userClipboard, JsonRequestBehavior.AllowGet));
                }
            }
            return(Json("", JsonRequestBehavior.AllowGet));
        }
Пример #5
0
        public static int SendClipboard(int UserId, string cleanClipboard)
        {
            // Business Logic to add the content on the database
            SyncModel sync   = new SyncModel();
            SyncUser  myUser = new SyncUser()
            {
                UserId        = UserId,
                ClipboardData = cleanClipboard
            };

            sync.SyncUsers.Add(myUser);
            sync.SaveChanges();

            return(myUser.UserId);
        }
Пример #6
0
        public virtual void Save(SyncUser user)
        {
            var path = GetPathForUser(user.UserName);

            var parent = Path.GetDirectoryName(path);

            if (!Directory.Exists(parent))
            {
                Directory.CreateDirectory(parent);
            }

            using (var writer = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                _userFormatter.WriteSerializedUser(user, writer);
            }
        }
        public virtual void WriteSerializedUser(SyncUser userData, Stream outputStream)
        {
            Assert.ArgumentNotNull(userData, nameof(userData));
            Assert.ArgumentNotNull(outputStream, "outputStream");

            using (var writer = new YamlWriter(outputStream, 4096, true))
            {
                writer.WriteMap("Username", userData.UserName);
                writer.WriteMap("Email", userData.Email);
                writer.WriteMap("Comment", userData.Comment ?? string.Empty);
                writer.WriteMap("Created", userData.CreationDate.ToString("O"));
                writer.WriteMap("IsApproved", userData.IsApproved.ToString());

                if (userData.ProfileProperties.Any())
                {
                    writer.WriteMap("Properties");
                    writer.IncreaseIndent();

                    userData.ProfileProperties.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
                    userData.ProfileProperties.ForEach(profileProperty =>
                    {
                        writer.WriteBeginListItem("Key", profileProperty.Name);
                        writer.WriteMap("Value", GetSerializedProfileContent(profileProperty));
                        writer.WriteMap("ValueType", profileProperty.Content.GetType().AssemblyQualifiedName);
                        writer.WriteMap("IsCustom", profileProperty.IsCustomProperty.ToString());
                    });

                    writer.DecreaseIndent();
                }

                if (userData.Roles.Any())
                {
                    userData.Roles.Sort();

                    writer.WriteMap("Roles");
                    writer.IncreaseIndent();

                    userData.Roles.ForEach(roleName =>
                    {
                        writer.WriteMap("MemberOf", roleName);
                    });

                    writer.DecreaseIndent();
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Validates user info against the info stored in the DB and returns a JWT token if successful or null if not.
        /// </summary>
        /// <param name="RawPassword"></param>
        /// <param name="Username"></param>
        /// <param name="Email"></param>
        /// <returns></returns>
        public static string UserLogin(string RawPassword, string Username = "", string Email = "")
        {
            if ((string.IsNullOrWhiteSpace(Username) && string.IsNullOrWhiteSpace(Email)) || (string.IsNullOrWhiteSpace(RawPassword)))
            {
                return(null);
            }

            SyncUser user = DatabaseConnector.ValidateAndGetUser(RawPassword, Username, Email);

            if (user != null)
            {
                return(GenerateToken(user.Username));
            }
            else
            {
                return(null);
            }
        }
Пример #9
0
        public static SyncUser GetClipboard(int UserId, int SequenceNumber)
        {
            SyncModel sync    = new SyncModel();
            int       timeout = 0;

            while (timeout < 100)
            {
                var checkIfAny = (from c in sync.SyncUsers
                                  where c.UserId == UserId &
                                  c.SyncID > SequenceNumber
                                  select c).ToList();

                if (checkIfAny.Count > 0)
                {
                    SyncUser userClipboard = checkIfAny[checkIfAny.Count - 1];
                    return(userClipboard);
                }

                // Hold the socket
                System.Threading.Thread.Sleep(1000 * 10);
                timeout++;
            }

            // delete old stuff from the users
            var toDelete = (from c in sync.SyncUsers
                            where c.UserId == UserId &
                            c.SyncID < SequenceNumber - 1
                            select c).ToList();

            for (int i = 0; i < toDelete.Count; i++)
            {
                sync.SyncUsers.Remove(toDelete[i]);
            }

            sync.SaveChanges();

            return(null);
        }
Пример #10
0
        protected virtual void PasteRoles(SyncUser serializedUser, User sitecoreUser, bool addedUser, List <UserUpdate> changes)
        {
            foreach (var role in serializedUser.Roles)
            {
                if (!sitecoreUser.Roles.Any(ur => ur.Name.Equals(role, StringComparison.OrdinalIgnoreCase)))
                {
                    sitecoreUser.Roles.Add(Role.FromName(role));
                    if (!addedUser)
                    {
                        changes.Add(new UserRoleUpdate(role, false));
                    }
                }
            }

            foreach (var orphanRole in sitecoreUser.Roles.Where(role => !serializedUser.Roles.Any(sr => sr.Equals(role.Name, StringComparison.OrdinalIgnoreCase))))
            {
                sitecoreUser.Roles.Remove(orphanRole);
                if (!addedUser)
                {
                    changes.Add(new UserRoleUpdate(orphanRole.Name, true));
                }
            }
        }
Пример #11
0
        /// <summary>
        /// 同步单个用户(无租户验证版本)
        /// </summary>
        /// <param name="wx_user"></param>
        /// <param name="tenant_id"></param>
        /// <returns>更新的本地Id</returns>
        public void MatchSingleUserWithoutTenant(SyncUser wx_user, int?tenant_id)
        {
            if (wx_user != null)
            {
                using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
                {
                    var ul = _userLoginRepository.FirstOrDefault(x => x.ProviderKey == wx_user.userid && x.LoginProvider == "Wechat" && x.TenantId == tenant_id);
                    //delete_user
                    switch (wx_user.changetype)
                    {
                    case "delete_user":
                        if (ul != null)
                        {
                            var user = _userRepository.FirstOrDefault(x => x.Id == ul.UserId);

                            if (user != null)
                            {
                                string user_email = user.EmailAddress;

                                _userOrganizationUnitRepository.Delete(x => x.UserId == ul.UserId);
                                _userRoleRepository.Delete(x => x.UserId == ul.UserId);

                                _userRepository.Delete(user);
                                _userLoginRepository.Delete(ul);

                                CurrentUnitOfWork.SaveChanges();

                                var mail_entity = new QYEmail.QYMailUserInfocsForUpdate
                                {
                                    userid = user_email,
                                    enable = 0,
                                    extid  = wx_user.userid
                                };
                                _emailManager.UpdateQYEmail(mail_entity, tenant_id.Value, "update");
                            }
                        }
                        break;

                    case "create_user":
                        if (ul == null)
                        {
                            var user_name = string.IsNullOrEmpty(wx_user.email) ? "" : wx_user.email.Split('@')[0];
                            //先检查用户是否有重复
                            if (_userRepository.GetAll().Any(x => x.UserName == wx_user.email || x.UserName == user_name || x.EmailAddress == wx_user.email))
                            {
                                _logger.Info(Abp.Timing.Clock.Now.ToString("yyyy-MM-dd HH:mm:ss") + wx_user.email + " : 用户已存在,无法通过企业微信回调接口Insert");
                                return;
                            }
                            var user = new User
                            {
                                TenantId               = tenant_id,
                                Name                   = wx_user.name,
                                NormalizedUserName     = wx_user.name,
                                PhoneNumber            = wx_user.mobile,
                                EmailAddress           = wx_user.email,
                                NormalizedEmailAddress = wx_user.email,
                                AccessFailedCount      = 0,
                                IsDeleted              = false,
                                IsActive               = true,
                                UserName               = user_name,
                                IsEmailConfirmed       = true,
                                IsTwoFactorEnabled     = true,
                                IsPhoneNumberConfirmed = !string.IsNullOrEmpty(wx_user.mobile),

                                IsLockoutEnabled = true,
                                Avatar           = wx_user.avatar,
                                Position         = wx_user.position,
                                Sex     = wx_user.gender == "1" ? true : false,
                                Surname = wx_user.alias ?? "",
                            };

                            user.Password = _passwordHasher.HashPassword(user, "000000");
                            var new_id = _userRepository.InsertAndGetId(user);
                            user.Id = new_id;

                            _userLoginRepository.Insert(new UserLogin {
                                LoginProvider = "Wechat", ProviderKey = wx_user.userid, TenantId = tenant_id, UserId = new_id
                            });

                            CurrentUnitOfWork.SaveChanges();


                            var base_emp = new BaseUserEmp
                            {
                                AbpUserId    = new_id,
                                EmpOrderNo   = new_id.ToString(),
                                EmpStationId = "",
                                EmpStatus    = "1",
                                EmpUserGuid  = Guid.NewGuid().ToString("N"),
                                IsLeader     = "",
                                EmpUserId    = wx_user.userid
                            };

                            var new_emp_id = _baseUserRepository.InsertAndGetId(base_emp);
                            CurrentUnitOfWork.SaveChanges();

                            if (!string.IsNullOrEmpty(wx_user.department))
                            {
                                var department_list = wx_user.department.Split(',');
                                var local_dept      = _organizationUnitRepository.GetAll().Where(x => department_list.Contains(x.WXDeptId.ToString()));
                                if (local_dept.Any())
                                {
                                    foreach (var item in local_dept)
                                    {
                                        _userOrganizationUnitRepository.Insert(new UserOrganizationUnit {
                                            TenantId = tenant_id, UserId = new_id, OrganizationUnitId = item.Id
                                        });
                                    }
                                    CurrentUnitOfWork.SaveChanges();
                                }
                                var local_emp_dept = _baseOrgRepository.GetAll().Where(x => department_list.Contains(x.WxId));
                                if (local_emp_dept.Any())
                                {
                                    int i = 0;
                                    foreach (var item in local_emp_dept)
                                    {
                                        _baseEmpOrgRepository.Insert(new BaseUserEmpOrg
                                        {
                                            AbpUserId      = new_id,
                                            BaseUserGuid   = Guid.NewGuid().ToString(),
                                            EmpUserGuid    = base_emp.EmpUserGuid,
                                            CropId         = "wx003757ee144cae06",
                                            DepartmentGuid = item.OrgGuid,
                                            EmpUserId      = wx_user.userid,
                                            DepartmentId   = item.Id.ToString(),
                                            IsMaster       = i == 0 ? "1" : "0",
                                        });
                                        i++;
                                    }

                                    CurrentUnitOfWork.SaveChanges();
                                }
                            }

                            var mail_entity = new QYEmail.QYMailUserInfocsForUpdate
                            {
                                userid     = wx_user.email,
                                extid      = wx_user.userid,
                                department = new List <long>()
                                {
                                    6786316460997750890
                                },
                                position = wx_user.position,
                                gender   = user.Sex ? "1" : "2",  //wx_user.gender,
                                mobile   = wx_user.mobile,
                                name     = wx_user.name,
                            };
                            _emailManager.UpdateQYEmail(mail_entity, tenant_id.Value, "create");

                            user.IsCreateEmail = true;
                            _userRepository.Update(user);
                        }
                        break;

                    case "update_user":
                        if (ul != null)
                        {
                            var user_id = ul.UserId;
                            var entity  = _userRepository.Get(user_id);
                            entity.TenantId     = tenant_id;
                            entity.Name         = wx_user.name ?? entity.Name;
                            entity.EmailAddress = wx_user.email ?? entity.EmailAddress;
                            entity.PhoneNumber  = wx_user.mobile ?? entity.PhoneNumber;
                            entity.Avatar       = wx_user.avatar ?? entity.Avatar;
                            entity.Position     = wx_user.position ?? entity.Position;
                            entity.Surname      = wx_user.alias ?? entity.Surname;

                            entity.Sex      = wx_user.gender == null ? entity.Sex : (wx_user.gender == "1" ? true : false);
                            entity.IsActive = wx_user.status.HasValue ? wx_user.status == 1 : entity.IsActive;

                            CurrentUnitOfWork.SaveChanges();

                            if (!string.IsNullOrEmpty(wx_user.department))
                            {
                                //先删除所有关联信息
                                //_userOrganizationUnitRepository.Delete(x => x.UserId == ul.UserId);
                                //CurrentUnitOfWork.SaveChanges();

                                //var department_list = wx_user.department.Split(',');

                                var wx_dept    = wx_user.department.Split(',').ToList();
                                var local_dept = (from o in _organizationUnitRepository.GetAll()
                                                  where o.TenantId == tenant_id && wx_dept.Contains(o.WXDeptId.ToString())
                                                  select o.Id).ToList();
                                //_organizationUnitRepository.GetAll().Where(x => x.TenantId == tenant_id && wx_dept.Contains(x.WXDeptId.ToString())).ToList();


                                //先删除 微信没有的
                                _userOrganizationUnitRepository.Delete(x => x.UserId == user_id && !local_dept.Contains(x.OrganizationUnitId));    //!local_dept.Any(d => x.OrganizationUnitId == d.Id));
                                CurrentUnitOfWork.SaveChanges();

                                var local_user_dept = _userOrganizationUnitRepository.GetAll().Where(x => x.TenantId == tenant_id && x.UserId == user_id).ToList();

                                //再添加 本地没有的
                                foreach (var item in local_dept)
                                {
                                    if (!local_user_dept.Any(x => x.OrganizationUnitId == item))
                                    {
                                        _userOrganizationUnitRepository.Insert(new UserOrganizationUnit {
                                            TenantId = tenant_id, UserId = user_id, OrganizationUnitId = item
                                        });
                                    }
                                }

                                //var local_emp_dept = _baseOrgRepository.GetAll().Where(x => wx_dept.Contains(x.WxId));
                                //var local_emp_dept_ids = local_emp_dept.Select(x => x.OrgGuid).ToList();
                                ////先删除 微信没有的
                                //_baseEmpOrgRepository.Delete(x => x.AbpUserId == user_id && !local_emp_dept_ids.Contains(x.DepartmentGuid));//!local_dept.Any(d => x.OrganizationUnitId == d.Id));
                                //CurrentUnitOfWork.SaveChanges();

                                //var local_user_emp_dept = _baseEmpOrgRepository.GetAll().Where(x => x.AbpUserId == user_id).ToList();

                                ////再添加 本地没有的
                                //foreach (var item in local_emp_dept)
                                //{
                                //    if (!local_user_emp_dept.Any(x => x.DepartmentGuid == item.OrgGuid))
                                //    {
                                //        _baseEmpOrgRepository.Insert(
                                //            new BaseUserEmpOrg
                                //            {
                                //                AbpUserId = user_id,
                                //                BaseUserGuid = Guid.NewGuid().ToString(),
                                //                EmpUserGuid = base_emp.EmpUserGuid,
                                //                CropId = "wx003757ee144cae06",
                                //                DepartmentGuid = item.OrgGuid,
                                //                EmpUserId = wx_user.userid,
                                //                DepartmentId = item.Id.ToString(),
                                //                IsMaster = i == 0 ? "1" : "0",
                                //            }
                                //            );
                                //    }
                                //}
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Пример #12
0
        protected virtual void PasteRoles(SyncUser serializedUser, User sitecoreUser, bool addedUser, List<UserUpdate> changes)
        {
            foreach (var role in serializedUser.Roles)
            {
                if (!sitecoreUser.Roles.Any(ur => ur.Name.Equals(role, StringComparison.OrdinalIgnoreCase)))
                {
                    sitecoreUser.Roles.Add(Role.FromName(role));
                    if (!addedUser)
                        changes.Add(new UserRoleUpdate(role, false));
                }
            }

            foreach (var orphanRole in sitecoreUser.Roles.Where(role => !serializedUser.Roles.Any(sr => sr.Equals(role.Name, StringComparison.OrdinalIgnoreCase))))
            {
                sitecoreUser.Roles.Remove(orphanRole);
                if (!addedUser)
                    changes.Add(new UserRoleUpdate(orphanRole.Name, true));
            }
        }
Пример #13
0
        protected virtual void PasteProfileValues(MembershipUser updatedUser, SyncUser serializedUser, List <UserUpdate> changes)
        {
            foreach (var name in SiteContextFactory.GetSiteNames())
            {
                var siteContext = SiteContextFactory.GetSiteContext(name);
                siteContext?.Caches.RegistryCache.RemoveKeysContaining(updatedUser.UserName);
            }

            var user = User.FromName(serializedUser.UserName, true);

            var propertiesAreUpdated = false;

            // load custom properties
            var knownCustomProperties = new HashSet <string>();

            foreach (var customProperty in serializedUser.ProfileProperties.Where(property => property.IsCustomProperty))
            {
                knownCustomProperties.Add(customProperty.Name);

                // check if we need to change the value
                var existingValue = user.Profile.GetCustomProperty(customProperty.Name);
                if (existingValue != null && existingValue.Equals((string)customProperty.Content, StringComparison.Ordinal))
                {
                    continue;
                }

                propertiesAreUpdated = true;
                user.Profile.SetCustomProperty(customProperty.Name, (string)customProperty.Content);
                changes.Add(new UserUpdate(customProperty.Name, existingValue, (string)customProperty.Content));
            }

            // cull orphan custom properties
            foreach (var existingCustomProperty in user.Profile.GetCustomPropertyNames())
            {
                if (!knownCustomProperties.Contains(existingCustomProperty))
                {
                    propertiesAreUpdated = true;
                    changes.Add(new UserUpdate(existingCustomProperty, user.Profile.GetCustomProperty(existingCustomProperty), "Deleted", true));
                    user.Profile.RemoveCustomProperty(existingCustomProperty);
                }
            }

            // load standard properties
            foreach (var standardProperty in serializedUser.ProfileProperties.Where(property => !property.IsCustomProperty))
            {
                // check if we need to change the value
                var existingValue = user.Profile.GetPropertyValue(standardProperty.Name);

                if (existingValue != null && (existingValue.GetType().IsPrimitive || existingValue is string))
                {
                    if (existingValue.Equals(standardProperty.Content))
                    {
                        continue;                         // no changes, skip
                    }
                    propertiesAreUpdated = true;
                    user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content);
                    changes.Add(new UserUpdate(standardProperty.Name, existingValue.ToString(), standardProperty.Content.ToString()));
                }
                else
                {
                    // a custom serialized type. No good way to compare as we don't know if it is at all comparable.
                    // we'll go with a quiet always update here
                    propertiesAreUpdated = true;
                    user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content);
                    if (existingValue == null)
                    {
                        changes.Add(new UserUpdate(standardProperty.Name, "null", standardProperty.Content.ToString()));
                    }
                }
            }

            // note: we cannot cull orphan standard properties because we cannot enumerate the keys

            if (propertiesAreUpdated)
            {
                user.Profile.Save();

                CacheManager.GetUserProfileCache().RemoveUser(updatedUser.UserName);
            }
        }
Пример #14
0
 public SyncUserFile(SyncUser user, string physicalPath)
 {
     User         = user;
     PhysicalPath = physicalPath;
 }
        public virtual SyncUser ReadSerializedUser(Stream dataStream, string serializedItemId)
        {
            Assert.ArgumentNotNull(dataStream, nameof(dataStream));

            try
            {
                using (var reader = new YamlReader(dataStream, 4096, true))
                {
                    var user = new SyncUser();

                    user.UserName     = reader.ReadExpectedMap("Username");
                    user.Email        = reader.ReadExpectedMap("Email");
                    user.Comment      = reader.ReadExpectedMap("Comment");
                    user.CreationDate = DateTime.ParseExact(reader.ReadExpectedMap("Created"), "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
                    user.IsApproved   = bool.Parse(reader.ReadExpectedMap("IsApproved"));

                    var propertiesNode = reader.PeekMap();
                    if (propertiesNode.HasValue && propertiesNode.Value.Key.Equals("Properties"))
                    {
                        reader.ReadMap();
                        while (true)
                        {
                            var propertyName = reader.PeekMap();

                            if (propertyName == null || !propertyName.Value.Key.Equals("Key"))
                            {
                                break;
                            }

                            reader.ReadMap();

                            var rawValue        = reader.ReadExpectedMap("Value");
                            var valueTypeString = reader.ReadExpectedMap("ValueType");

                            var value = ReadPropertyValueObject(propertyName.Value.Value, valueTypeString, rawValue);

                            bool propertyIsCustom = bool.Parse(reader.ReadExpectedMap("IsCustom"));

                            user.ProfileProperties.Add(new SyncProfileProperty(propertyName.Value.Value, value, propertyIsCustom));
                        }
                    }

                    var rolesNode = reader.PeekMap();

                    if (rolesNode.HasValue && rolesNode.Value.Key.Equals("Roles"))
                    {
                        reader.ReadMap();

                        while (true)
                        {
                            var roleName = reader.ReadMap();

                            if (string.IsNullOrWhiteSpace(roleName?.Value))
                            {
                                break;
                            }

                            user.Roles.Add(roleName.Value.Value);
                        }
                    }

                    return(user);
                }
            }
            catch (Exception exception)
            {
                throw new YamlFormatException("Error parsing YAML " + serializedItemId, exception);
            }
        }
Пример #16
0
        protected virtual void PasteProfileValues(MembershipUser updatedUser, SyncUser serializedUser, List<UserUpdate> changes)
        {
            foreach (var name in SiteContextFactory.GetSiteNames())
            {
                var siteContext = SiteContextFactory.GetSiteContext(name);
                siteContext?.Caches.RegistryCache.RemoveKeysContaining(updatedUser.UserName);
            }

            var user = User.FromName(serializedUser.UserName, true);

            var propertiesAreUpdated = false;

            // load custom properties
            var knownCustomProperties = new HashSet<string>();
            foreach (var customProperty in serializedUser.ProfileProperties.Where(property => property.IsCustomProperty))
            {
                knownCustomProperties.Add(customProperty.Name);

                // check if we need to change the value
                var existingValue = user.Profile.GetCustomProperty(customProperty.Name);
                if (existingValue != null && existingValue.Equals((string) customProperty.Content, StringComparison.Ordinal))
                    continue;

                propertiesAreUpdated = true;
                user.Profile.SetCustomProperty(customProperty.Name, (string) customProperty.Content);
                changes.Add(new UserUpdate(customProperty.Name, existingValue, (string) customProperty.Content));
            }

            // cull orphan custom properties
            foreach (var existingCustomProperty in user.Profile.GetCustomPropertyNames())
            {
                if (!knownCustomProperties.Contains(existingCustomProperty))
                {
                    propertiesAreUpdated = true;
                    changes.Add(new UserUpdate(existingCustomProperty, user.Profile.GetCustomProperty(existingCustomProperty), "Deleted", true));
                    user.Profile.RemoveCustomProperty(existingCustomProperty);
                }
            }

            // load standard properties
            foreach (var standardProperty in serializedUser.ProfileProperties.Where(property => !property.IsCustomProperty))
            {
                // check if we need to change the value
                var existingValue = user.Profile.GetPropertyValue(standardProperty.Name);

                if (existingValue != null && (existingValue.GetType().IsPrimitive || existingValue is string))
                {
                    if (existingValue.Equals(standardProperty.Content))
                        continue; // no changes, skip

                    propertiesAreUpdated = true;
                    user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content);
                    changes.Add(new UserUpdate(standardProperty.Name, existingValue.ToString(), standardProperty.Content.ToString()));
                }
                else
                {
                    // a custom serialized type. No good way to compare as we don't know if it is at all comparable.
                    // we'll go with a quiet always update here
                    propertiesAreUpdated = true;
                    user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content);
                    if (existingValue == null)
                        changes.Add(new UserUpdate(standardProperty.Name, "null", standardProperty.Content.ToString()));
                }
            }

            // note: we cannot cull orphan standard properties because we cannot enumerate the keys

            if (propertiesAreUpdated)
            {
                user.Profile.Save();

                CacheManager.GetUserProfileCache().RemoveUser(updatedUser.UserName);
            }
        }
Пример #17
0
 protected override IConfigurable ConvertDataObjectToPresentationObject(IConfigurable dataObject)
 {
     return(SyncUser.FromDataObject((ADUser)dataObject));
 }
        public virtual SyncUser ReadSerializedUser(Stream dataStream, string serializedItemId)
        {
            Assert.ArgumentNotNull(dataStream, nameof(dataStream));

            try
            {
                using (var reader = new YamlReader(dataStream, 4096, true))
                {
                    var user = new SyncUser();

                    user.UserName = reader.ReadExpectedMap("Username");
                    user.Email = reader.ReadExpectedMap("Email");
                    user.Comment = reader.ReadExpectedMap("Comment");
                    user.CreationDate = DateTime.ParseExact(reader.ReadExpectedMap("Created"), "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
                    user.IsApproved = bool.Parse(reader.ReadExpectedMap("IsApproved"));

                    var propertiesNode = reader.PeekMap();
                    if (propertiesNode.HasValue && propertiesNode.Value.Key.Equals("Properties"))
                    {
                        reader.ReadMap();
                        while (true)
                        {
                            var propertyName = reader.PeekMap();

                            if (propertyName == null || !propertyName.Value.Key.Equals("Key")) break;

                            reader.ReadMap();

                            var rawValue = reader.ReadExpectedMap("Value");
                            var valueTypeString = reader.ReadExpectedMap("ValueType");

                            var value = ReadPropertyValueObject(propertyName.Value.Value, valueTypeString, rawValue);

                            bool propertyIsCustom = bool.Parse(reader.ReadExpectedMap("IsCustom"));

                            user.ProfileProperties.Add(new SyncProfileProperty(propertyName.Value.Value, value, propertyIsCustom));
                        }
                    }

                    var rolesNode = reader.PeekMap();

                    if (rolesNode.HasValue && rolesNode.Value.Key.Equals("Roles"))
                    {
                        reader.ReadMap();

                        while (true)
                        {
                            var roleName = reader.ReadMap();

                            if (string.IsNullOrWhiteSpace(roleName?.Value)) break;

                            user.Roles.Add(roleName.Value.Value);
                        }
                    }

                    return user;
                }
            }
            catch (Exception exception)
            {
                throw new YamlFormatException("Error parsing YAML " + serializedItemId, exception);
            }
        }
        public virtual void WriteSerializedUser(SyncUser userData, Stream outputStream)
        {
            Assert.ArgumentNotNull(userData, nameof(userData));
            Assert.ArgumentNotNull(outputStream, "outputStream");

            using (var writer = new YamlWriter(outputStream, 4096, true))
            {
                writer.WriteMap("Username", userData.UserName);
                writer.WriteMap("Email", userData.Email ?? string.Empty);
                writer.WriteMap("Comment", userData.Comment ?? string.Empty);
                writer.WriteMap("Created", userData.CreationDate.ToString("O"));
                writer.WriteMap("IsApproved", userData.IsApproved.ToString());

                if (userData.ProfileProperties.Any())
                {
                    writer.WriteMap("Properties");
                    writer.IncreaseIndent();

                    userData.ProfileProperties.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
                    userData.ProfileProperties.ForEach(profileProperty =>
                    {
                        writer.WriteBeginListItem("Key", profileProperty.Name);
                        writer.WriteMap("Value", GetSerializedProfileContent(profileProperty));
                        writer.WriteMap("ValueType", profileProperty.Content.GetType().AssemblyQualifiedName);
                        writer.WriteMap("IsCustom", profileProperty.IsCustomProperty.ToString());
                    });

                    writer.DecreaseIndent();
                }

                if (userData.Roles.Any())
                {
                    userData.Roles.Sort();

                    writer.WriteMap("Roles");
                    writer.IncreaseIndent();

                    userData.Roles.ForEach(roleName =>
                    {
                        writer.WriteMap("MemberOf", roleName);
                    });

                    writer.DecreaseIndent();
                }
            }
        }