Пример #1
0
        public void Test_UserUpdate_Validate()
        {
            var value = new UserUpdate();

            value.Validate();

            Assert.AreEqual(4, value.Errors.Count, "Errors");
        }
Пример #2
0
            public async Task FailsWhenNotAuthenticated()
            {
                var github = new GitHubClient(new ProductHeaderValue("OctokitTests"));
                var userUpdate = new UserUpdate
                {
                    Name = Helper.Credentials.Login,
                    Bio = "UPDATED BIO"
                };

                var e = await AssertEx.Throws<AuthorizationException>(async 
                    () => await github.User.Update(userUpdate));
                Assert.Equal(HttpStatusCode.Unauthorized, e.StatusCode);
            }
Пример #3
0
        public void Test_UserUpdate_ValueToModel()
        {
            var value = new UserUpdate
            {
                Name = "test",
                Title = "test2",
                EmailAddress = "*****@*****.**",
                Signature = "test3"
            };

            var user = new User();

            value.ValueToModel(user);

            Assert.AreEqual("test", user.Name, "Name");
            Assert.AreEqual("test2", user.Title, "Title");
            Assert.AreEqual("*****@*****.**", user.EmailAddress, "EmailAddress");
            Assert.AreEqual("test3", user.Signature, "Signature");
        }
Пример #4
0
        public void Test_UserUpdate()
        {
            var value = new UserUpdate(
                new User
                {
                    Name = "test",
                    Title = "test2",
                    EmailAddress = "*****@*****.**",
                    Signature = "test3"
                }
            );

            Assert.AreEqual("test", value.Name, "Name");
            Assert.AreEqual("test", value.CurrentName, "CurrentName");
            Assert.AreEqual("test2", value.Title, "Title");
            Assert.AreEqual("*****@*****.**", value.EmailAddress, "EmailAddress");
            Assert.AreEqual("*****@*****.**", value.VerifyEmailAddress, "VerifyEmailAddress");
            Assert.AreEqual("*****@*****.**", value.CurrentEmailAddress, "CurrentEmailAddress");
            Assert.AreEqual("test3", value.Signature, "Signature");
        }
Пример #5
0
        private static async Task ModifyUser(GreeterClient client)
        {
            Console.WriteLine("Inserte nombre de usuario a modificar");
            string name = Console.ReadLine();

            while (name.Trim().Equals(""))
            {
                name = Console.ReadLine();
            }
            Console.WriteLine("Inserte el nuevo nombre (deje vacio para no cambiar)");
            string newName = Console.ReadLine();

            Console.WriteLine("Inserte nueva contraseña (deje vacio para no cambiar)");
            string password = Console.ReadLine();
            var    user     = new UserUpdate
            {
                Name        = name,
                NewName     = newName,
                NewPassword = password
            };
            var response = await client.ModifyUserAsync(user);

            Console.WriteLine(response.Message);
        }
        public void Update(int id, UserUpdate user)
        {
            var userUpdate = _context.Users.Find(id);

            if (userUpdate == null)
            {
                throw new AppException("User not found");
            }
            //if user change user name
            if (!string.IsNullOrWhiteSpace(user.username) && user.username != userUpdate.username)
            {
                if (_context.Users.Any(x => x.username == user.username))
                {
                    throw new AppException("Username " + user.username + " is already taken");
                }

                userUpdate.username = user.username;
            }
            //if user change fullname
            if (!string.IsNullOrWhiteSpace(user.fullname))
            {
                userUpdate.fullname = user.fullname;
            }
            //if user change password
            if (!string.IsNullOrWhiteSpace(user.password))
            {
                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(user.password, out passwordHash, out passwordSalt);

                userUpdate.PasswordHash = passwordHash;
                userUpdate.PasswordSalt = passwordSalt;
            }

            _context.Users.Update(userUpdate);
            _context.SaveChanges();
        }
Пример #7
0
        public void GetXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <update>
        <USERINFO>
            <LOGINID>U1234</LOGINID>
        </USERINFO>
    </update>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            UserUpdate record = new UserUpdate("unittest");

            record.UserId = "U1234";

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Пример #8
0
        public async Task <IActionResult> Update(UserUpdate message)
        {
            var result = await _mediator.Send(message);

            return(Ok(result));
        }
Пример #9
0
        private void HandleDispatchEvent(GatewayPayload evnt, TaskCompletionSource <bool> readySignal)
        {
            switch (evnt.DispatchType)
            {
            case GatewayDispatchType.Ready:
                var readyEvent = evnt.Data as ReadyEvent;
                SetSession(readyEvent.SessionId);
                readySignal.TrySetResult(true);
                Ready?.Invoke(readyEvent);
                break;

            case GatewayDispatchType.Resumed:
                readySignal.TrySetResult(true);
                Resumed?.Invoke();
                break;

            case GatewayDispatchType.GuildCreate: GuildCreate?.Invoke(evnt.Data as GatewayGuild); break;

            case GatewayDispatchType.GuildUpdate: GuildUpdate?.Invoke(evnt.Data as Guild); break;

            case GatewayDispatchType.GuildDelete: GuildDelete?.Invoke(evnt.Data as UnavailableGuild); break;

            case GatewayDispatchType.ChannelCreate: ChannelCreate?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelUpdate: ChannelUpdate?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelDelete: ChannelDelete?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelPinsUpdate: ChannelPinsUpdate?.Invoke(evnt.Data as ChannelPinsUpdateEvent); break;

            case GatewayDispatchType.GuildMemberAdd: GuildMemberAdd?.Invoke(evnt.Data as GuildMemberAddEvent); break;

            case GatewayDispatchType.GuildMemberUpdate: GuildMemberUpdate?.Invoke(evnt.Data as GuildMemberUpdateEvent); break;

            case GatewayDispatchType.GuildMemberRemove: GuildMemberRemove?.Invoke(evnt.Data as GuildMemberRemoveEvent); break;

            case GatewayDispatchType.GuildMembersChunk: GuildMembersChunk?.Invoke(evnt.Data as GuildMembersChunkEvent); break;

            case GatewayDispatchType.GuildRoleCreate: GuildRoleCreate?.Invoke(evnt.Data as GuildRoleCreateEvent); break;

            case GatewayDispatchType.GuildRoleUpdate: GuildRoleUpdate?.Invoke(evnt.Data as GuildRoleUpdateEvent); break;

            case GatewayDispatchType.GuildRoleDelete: GuildRoleDelete?.Invoke(evnt.Data as GuildRoleDeleteEvent); break;

            case GatewayDispatchType.GuildBanAdd: GuildBanAdd?.Invoke(evnt.Data as GuildBanAddEvent); break;

            case GatewayDispatchType.GuildBanRemove: GuildBanRemove?.Invoke(evnt.Data as GuildBanRemoveEvent); break;

            case GatewayDispatchType.GuildEmojisUpdate: GuildEmojisUpdate?.Invoke(evnt.Data as GuildEmojiUpdateEvent); break;

            case GatewayDispatchType.GuildIntegrationsUpdate: GuildIntegrationsUpdate?.Invoke(evnt.Data as GuildIntegrationsUpdateEvent); break;

            case GatewayDispatchType.MessageCreate: MessageCreate?.Invoke(evnt.Data as Message); break;

            case GatewayDispatchType.MessageUpdate: MessageUpdate?.Invoke(evnt.Data as Message); break;

            case GatewayDispatchType.MessageDelete: MessageDelete?.Invoke(evnt.Data as MessageDeleteEvent); break;

            case GatewayDispatchType.MessageDeleteBulk: MessageDeleteBulk?.Invoke(evnt.Data as MessageDeleteBulkEvent); break;

            case GatewayDispatchType.MessageReactionAdd: MessageReactionAdd?.Invoke(evnt.Data as MessageReactionAddEvent); break;

            case GatewayDispatchType.MessageReactionRemove: MessageReactionRemove?.Invoke(evnt.Data as MessageReactionRemoveEvent); break;

            case GatewayDispatchType.MessageReactionRemoveAll: MessageReactionRemoveAll?.Invoke(evnt.Data as MessageReactionRemoveAllEvent); break;

            case GatewayDispatchType.PresenceUpdate: PresenceUpdate?.Invoke(evnt.Data as Presence); break;

            case GatewayDispatchType.UserUpdate: UserUpdate?.Invoke(evnt.Data as User); break;

            case GatewayDispatchType.TypingStart: TypingStart?.Invoke(evnt.Data as TypingStartEvent); break;

            case GatewayDispatchType.VoiceStateUpdate: VoiceStateUpdate?.Invoke(evnt.Data as VoiceState); break;

            case GatewayDispatchType.VoiceServerUpdate: VoiceServerUpdate?.Invoke(evnt.Data as VoiceServerUpdateEvent); break;

            case GatewayDispatchType.WebhooksUpdate: WebhooksUpdate?.Invoke(evnt.Data as WebhooksUpdateEvent); break;
            }
        }
Пример #10
0
        public async Task UpdateAsync(UserUpdate user)
        {
            _logger.LogInformation(LoggerEvents.UpdateItem, "Update item {User}", JsonConvert.SerializeObject(user));

            await this._userRepository.UpdateAsync(user);
        }
Пример #11
0
        public ActionResult Update(UserUpdate value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            var user = this.UserService.GetById(Identity.Id);

            if (user == null)
            {
                return base.HttpNotFound();
            }

            value.Validate();

            if (value.IsValid)
            {
                value.ValueToModel(user);

                this.UserService.Update(user);

                ApplicationSession.Destroy(Session);

                value.SuccessMessage(Messages.UserAccountUpdated);
            }
            else
            {
                value.CopyToModel(ModelState);
            }

            return base.View(Views.Update, value);
        }
Пример #12
0
        public async Task <IActionResult> UpdateAccount([FromBody] UserUpdate userUpdate)
        {
            IDbContextTransaction trans = await this._userService.BeginTransactionAsync();

            using (trans)
            {
                try
                {
                    AppUser user = await this._userManager.FindByNameAsync(userUpdate.Nik);

                    IdentityResult res_identity = null;
                    if (userUpdate.Password != null)
                    {
                        var token_change_password = await this._userManager.GeneratePasswordResetTokenAsync(user);

                        res_identity = await this._userManager.ResetPasswordAsync(user, token_change_password, userUpdate.Password);

                        // TODO send email to notify new password

                        if (!res_identity.Succeeded)
                        {
                            return(BadRequest(new CustomResponse
                            {
                                message = "Gagal Update Password User pada IdentityUser",
                                title = "Error",
                                ok = false,
                                errors = null
                            }));
                        }
                    }

                    if (user.Email != userUpdate.Email)
                    {
                        var token_change_email = await this._userManager.GenerateChangeEmailTokenAsync(user, userUpdate.Email);

                        var old_email = user.Email;
                        res_identity = await this._userManager.ChangeEmailAsync(user, userUpdate.Email, token_change_email);

                        // TODO send email to notify changing email contain old and new email

                        if (!res_identity.Succeeded)
                        {
                            return(BadRequest(new CustomResponse
                            {
                                message = "Gagal Update Email User pada IdentityUser",
                                title = "Error",
                                ok = false,
                                errors = null
                            }));
                        }
                    }
                    User userlama = this._userService.FindByKey(userUpdate.Nik);
                    userlama.Ext               = userlama.Ext == userUpdate.Ext ? userlama.Ext : userUpdate.Ext;
                    userlama.DirektoratKode    = userlama.DirektoratKode == userUpdate.KodeDirektorat ? userlama.DirektoratKode : userUpdate.KodeDirektorat;
                    userlama.DepartemenKode    = userlama.DepartemenKode == userUpdate.KodeDepartemen ? userlama.DepartemenKode : userUpdate.KodeDepartemen;
                    userlama.SubDepartemenKode = userlama.SubDepartemenKode == userUpdate.KodeSubDepartemen ? userlama.SubDepartemenKode : userUpdate.KodeSubDepartemen;
                    userlama.CabangKode        = userlama.CabangKode == userUpdate.KodeCabang ? userlama.CabangKode : userUpdate.KodeCabang;
                    userlama.UnitKode          = userlama.UnitKode == userUpdate.KodeUnit ? userlama.UnitKode : userUpdate.KodeUnit;
                    userlama.Nama              = userlama.Nama.ToLower() == userUpdate.Nama.ToLower() ? userlama.Nama : userUpdate.Nama;
                    userlama.AtasanNik         = userlama.AtasanNik == userUpdate.NikAtasan ? userlama.AtasanNik : userUpdate.NikAtasan;
                    this._userService.Update(userlama);
                    var res_save = await this._userService.SaveAsync();

                    if (res_save == 1)
                    {
                        this._userService.Commit(trans);
                        return(Ok(new CustomResponse
                        {
                            errors = null,
                            message = "Update User Berhasil",
                            title = "Success",
                            ok = true
                        }));
                    }
                    else
                    {
                        this._userService.Rollback(trans);
                        return(BadRequest(new CustomResponse
                        {
                            message = "Update User Gagal",
                            title = "Error",
                            errors = null,
                            ok = false
                        }));
                    }
                }
                catch (Exception ex)
                {
                    this._userService.Rollback(trans);
                    return(BadRequest(new CustomResponse
                    {
                        message = ex.Message,
                        title = "Error",
                        errors = new List <string>()
                        {
                            ex.InnerException.Message
                        },
                        ok = false
                    }));
                }
            }
        }
Пример #13
0
        public async Task RunPostTest(CancellationToken cancellationToken)
        {
            var instances = await instanceManagerClient.List(cancellationToken);

            var firstTest      = instances.Single(x => x.Name == TestInstanceName);
            var instanceClient = instanceManagerClient.CreateClient(firstTest);

            //can regain permissions on instance without instance user
            var ourInstanceUser = await instanceClient.Users.Read(cancellationToken).ConfigureAwait(false);

            await instanceClient.Users.Delete(ourInstanceUser, cancellationToken).ConfigureAwait(false);

            await Assert.ThrowsExceptionAsync <InsufficientPermissionsException>(() => instanceClient.Users.Read(cancellationToken)).ConfigureAwait(false);

            await instanceManagerClient.GrantPermissions(new Api.Models.Instance
            {
                Id = firstTest.Id
            }, cancellationToken).ConfigureAwait(false);

            ourInstanceUser = await instanceClient.Users.Read(cancellationToken).ConfigureAwait(false);

            Assert.AreEqual(RightsHelper.AllRights <DreamDaemonRights>(), ourInstanceUser.DreamDaemonRights.Value);

            //can't detach online instance
            await ApiAssert.ThrowsException <ConflictException>(() => instanceManagerClient.Detach(firstTest, cancellationToken), ErrorCode.InstanceDetachOnline).ConfigureAwait(false);

            firstTest.Online = false;
            firstTest        = await instanceManagerClient.Update(firstTest, cancellationToken).ConfigureAwait(false);

            await instanceManagerClient.Detach(firstTest, cancellationToken).ConfigureAwait(false);

            var attachPath = Path.Combine(firstTest.Path, InstanceController.InstanceAttachFileName);

            Assert.IsTrue(File.Exists(attachPath));

            //can recreate detached instance
            firstTest = await instanceManagerClient.CreateOrAttach(firstTest, cancellationToken).ConfigureAwait(false);

            // Test updating only with SetChatBotLimit works
            var current = await usersClient.Read(cancellationToken);

            var update = new UserUpdate
            {
                Id = current.Id,
                InstanceManagerRights = InstanceManagerRights.SetChatBotLimit
            };
            await usersClient.Update(update, cancellationToken);

            var update2 = new Api.Models.Instance
            {
                Id           = firstTest.Id,
                ChatBotLimit = 77
            };
            var newThing = await instanceManagerClient.Update(update2, cancellationToken);

            update.InstanceManagerRights |= InstanceManagerRights.Delete | InstanceManagerRights.Create | InstanceManagerRights.List;
            await usersClient.Update(update, cancellationToken);

            //but only if the attach file exists
            await instanceManagerClient.Detach(firstTest, cancellationToken).ConfigureAwait(false);

            File.Delete(attachPath);
            await ApiAssert.ThrowsException <ConflictException>(() => instanceManagerClient.CreateOrAttach(firstTest, cancellationToken), ErrorCode.InstanceAtExistingPath).ConfigureAwait(false);
        }
        public async Task <IActionResult> Create([FromBody] UserUpdate model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!(model.Password == null ^ model.SystemIdentifier == null))
            {
                return(BadRequest(new ErrorMessage {
                    Message = "User must have exactly one of either a password or system identifier!"
                }));
            }

            model.Name = model.Name?.Trim();
            if (model.Name?.Length == 0)
            {
                model.Name = null;
            }

            if (!(model.Name == null ^ model.SystemIdentifier == null))
            {
                return(BadRequest(new ErrorMessage {
                    Message = "User must have a name if and only if user has no system identifier!"
                }));
            }

            var fail = CheckValidName(model);

            if (fail != null)
            {
                return(fail);
            }

            var dbUser = new Models.User
            {
                AdministrationRights = model.AdministrationRights ?? AdministrationRights.None,
                CreatedAt            = DateTimeOffset.Now,
                CreatedBy            = AuthenticationContext.User,
                Enabled = model.Enabled ?? false,
                InstanceManagerRights = model.InstanceManagerRights ?? InstanceManagerRights.None,
                Name             = model.Name,
                SystemIdentifier = model.SystemIdentifier,
                InstanceUsers    = new List <Models.InstanceUser>()
            };

            if (model.SystemIdentifier != null)
            {
                try
                {
                    using (var sysIdentity = await systemIdentityFactory.CreateSystemIdentity(dbUser, cancellationToken).ConfigureAwait(false))
                    {
                        if (sysIdentity == null)
                        {
                            return(StatusCode((int)HttpStatusCode.Gone));
                        }
                        dbUser.Name             = sysIdentity.Username;
                        dbUser.SystemIdentifier = sysIdentity.Uid;
                    }
                }
                catch (NotImplementedException)
                {
                    return(StatusCode((int)HttpStatusCode.NotImplemented));
                }
            }
            else
            {
                var result = TrySetPassword(dbUser, model.Password);
                if (result != null)
                {
                    return(result);
                }
            }

            dbUser.CanonicalName = Models.User.CanonicalizeName(dbUser.Name);

            DatabaseContext.Users.Add(dbUser);

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            return(StatusCode((int)HttpStatusCode.Created, dbUser.ToApi(true)));
        }
Пример #15
0
 public UserUpdateCommand(string username, UserUpdate data, User user) : base(username, user)
 {
     Update = data;
 }
Пример #16
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="userUpdate"></param>
 public UserUpdateCommand(UserUpdate userUpdate)
 {
     UserUpdate = userUpdate;
 }
Пример #17
0
 public async Task <Object> Update(string id, UserUpdate model) => await _authServices.Update(id, model);
        /// <summary>
        /// Update the specified <see cref="UserUpdate"/>.
        /// </summary>
        /// <param name="user">The login for the user</param>
        /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
        /// <returns>A <see cref="User"/></returns>
        public IObservable<User> Update(UserUpdate user)
        {
            Ensure.ArgumentNotNull(user, "user");

            return _client.Update(user).ToObservable();
        }
Пример #19
0
 public User Update(UserUpdate updateUser)
 {
     return(null);
 }
Пример #20
0
 public User UpdateUser(UserUpdate user)
 {
     return(UserDAL.UpdateUser(user));
 }
        public TelegramBotDataBuilder SetUserUpdate(UserUpdate userUpdate)
        {
            _userUpdate = userUpdate;

            return(this);
        }
Пример #22
0
        public async Task <User> UpdateAsync(UserUpdate userUpdate)
        {
            var user = await GetAsync().ConfigureAwait(_halClient);

            return(await _halClient.PatchAsync <User>(user.UpdateLink, userUpdate).ConfigureAwait(_halClient));
        }
Пример #23
0
 public override Task <ActionResponse> ModifyUser(UserUpdate user, ServerCallContext context)
 {
     return(Task.FromResult(UpdateUser(user)));
 }
Пример #24
0
    private void DrawAddRemoveProperty()
    {
        DemoGuiUtils.Space();
        GUILayout.BeginVertical("Box");
        GUILayout.Label("Custom Properties", GSStyles.NormalLabelText);
        GUILayout.BeginHorizontal();
        GUILayout.Label("Public property: ", GSStyles.NormalLabelText);
        _key = GUILayout.TextField(_key, GSStyles.TextField);
        _val = GUILayout.TextField(_val, GSStyles.TextField);

        DemoGuiUtils.DrawButton("Add", () =>
        {
            if (GetSocial.GetCurrentUser().PublicProperties.ContainsKey(_key))
            {
                _console.LogW("Property already exists " + _key + "=" + GetSocial.GetCurrentUser().PublicProperties[_key] +
                              ", remove old one if you're really want to override it.");
            }
            else
            {
                var update = new UserUpdate().AddPublicProperty(_key, _val);
                GetSocial.GetCurrentUser().UpdateDetails(update,
                                                         () => _console.LogD(
                                                             "Property added for key: " + _key + "=" + GetSocial.GetCurrentUser().PublicProperties[_key]),
                                                         error => _console.LogE("Failed to add property for key: " + _key + ", error: " + error)
                                                         );
            }
        }, true, GSStyles.Button);
        DemoGuiUtils.DrawButton("Remove", () =>
        {
            var update = new UserUpdate().RemovePublicProperty(_key);
            GetSocial.GetCurrentUser().UpdateDetails(update,
                                                     () => _console.LogD("Property removed for key: " + _key),
                                                     error => _console.LogE("Failed to remove property for key: " + _key + ", error: " + error)
                                                     );
        }, true, GSStyles.Button);
        GUILayout.EndHorizontal();


        GUILayout.BeginHorizontal();
        GUILayout.Label("Private property: ", GSStyles.NormalLabelText);
        _keyPrivate = GUILayout.TextField(_keyPrivate, GSStyles.TextField);
        _valPrivate = GUILayout.TextField(_valPrivate, GSStyles.TextField);

        DemoGuiUtils.DrawButton("Add", () =>
        {
            if (GetSocial.GetCurrentUser().PrivateProperties.ContainsKey(_keyPrivate))
            {
                _console.LogW("Property already exists " + _keyPrivate + "=" +
                              GetSocial.GetCurrentUser().PrivateProperties[_keyPrivate] +
                              ", remove old one if you're really want to override it.");
            }
            else
            {
                var update = new UserUpdate().AddPrivateProperty(_key, _val);
                GetSocial.GetCurrentUser().UpdateDetails(update,
                                                         () => _console.LogD("Property added for key: " + _keyPrivate + "=" +
                                                                             GetSocial.GetCurrentUser().PrivateProperties[_keyPrivate]),
                                                         error => _console.LogE("Failed to add property for key: " + _keyPrivate + ", error: " + error)
                                                         );
            }
        }, true, GSStyles.Button);
        DemoGuiUtils.DrawButton("Remove", () =>
        {
            var update = new UserUpdate().RemovePrivateProperty(_key);
            GetSocial.GetCurrentUser().UpdateDetails(update,
                                                     () => _console.LogD("Property removed for key: " + _keyPrivate),
                                                     error => _console.LogE("Failed to remove property for key: " + _keyPrivate + ", error: " + error)
                                                     );
        }, true, GSStyles.Button);

        GUILayout.EndHorizontal();
        GUILayout.EndVertical();
    }
 public override void UserUpdated(TwilioChatClient client, Channel channel, Member member, User user, UserUpdate updated)
 {
     Logger.Info($"Channel: {channel.Sid}", $"UserUpdated: {user.Identity}, member: {member.Sid}, reason: {updated}");
 }
Пример #26
0
 public async void Update(User original, UserUpdate update)
 {
     await _users.ReplaceOneAsync(user => user.Id == original.Id, User.FromUpdate(original, update));
 }
Пример #27
0
#pragma warning disable CA1502, CA1506
        public async Task <IActionResult> Create([FromBody] UserUpdate model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.OAuthConnections?.Any(x => x == null) == true)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.ModelValidationFailure)));
            }

            if ((model.Password != null && model.SystemIdentifier != null) ||
                (model.Password == null && model.SystemIdentifier == null && model.OAuthConnections?.Any() != true))
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserMismatchPasswordSid)));
            }

            if (model.Group != null && model.PermissionSet != null)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserGroupAndPermissionSet)));
            }

            model.Name = model.Name?.Trim();
            if (model.Name?.Length == 0)
            {
                model.Name = null;
            }

            if (!(model.Name == null ^ model.SystemIdentifier == null))
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserMismatchNameSid)));
            }

            var fail = CheckValidName(model, true);

            if (fail != null)
            {
                return(fail);
            }

            var totalUsers = await DatabaseContext
                             .Users
                             .AsQueryable()
                             .CountAsync(cancellationToken)
                             .ConfigureAwait(false);

            if (totalUsers >= generalConfiguration.UserLimit)
            {
                return(Conflict(new ErrorMessage(ErrorCode.UserLimitReached)));
            }

            var dbUser = await CreateNewUserFromModel(model, cancellationToken).ConfigureAwait(false);

            if (dbUser == null)
            {
                return(Gone());
            }

            if (model.SystemIdentifier != null)
            {
                try
                {
                    using var sysIdentity = await systemIdentityFactory.CreateSystemIdentity(dbUser, cancellationToken).ConfigureAwait(false);

                    if (sysIdentity == null)
                    {
                        return(Gone());
                    }
                    dbUser.Name             = sysIdentity.Username;
                    dbUser.SystemIdentifier = sysIdentity.Uid;
                }
                catch (NotImplementedException)
                {
                    return(RequiresPosixSystemIdentity());
                }
            }
            else if (!(model.Password?.Length == 0 && model.OAuthConnections?.Any() == true))
            {
                var result = TrySetPassword(dbUser, model.Password, true);
                if (result != null)
                {
                    return(result);
                }
            }

            dbUser.CanonicalName = Models.User.CanonicalizeName(dbUser.Name);

            DatabaseContext.Users.Add(dbUser);

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            Logger.LogInformation("Created new user {0} ({1})", dbUser.Name, dbUser.Id);

            return(Created(dbUser.ToApi(true)));
        }
Пример #28
0
        public void Setup()
        {
            _context = ContextHelper.GetDatabaseContext();

            sut = new UserService(_context);

            userTeacher = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "John",
                HouseNumber  = 18,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            company = new Company
            {
                CompanyTitle = "Test inc."
            };

            dtoTeacher = new UserReadDto
            {
                FirstName = userTeacher.FirstName,
                LastName  = userTeacher.LastName,
                Id        = userTeacher.Id
            };

            userCompany = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "Johnnie",
                HouseNumber  = 19,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            dtoCompany = new UserReadDto
            {
                FirstName = userCompany.FirstName,
                LastName  = userCompany.LastName,
                Id        = userCompany.Id
            };

            userStudent = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "Henk",
                HouseNumber  = 17,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            dtoStudent = new UserReadDto
            {
                FirstName = userStudent.FirstName,
                LastName  = userStudent.LastName,
                Id        = userStudent.Id
            };

            roleCompany = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Company",
                NormalizedName = "COMPANY"
            };

            roleStudent = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Student",
                NormalizedName = "STUDENT"
            };

            roleTeacher = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Teacher",
                NormalizedName = "TEACHER"
            };

            internship = new Internship
            {
                RequiredFieldsOfStudy  = new List <string>(),
                AssignedStudents       = new List <string>(),
                Environment            = new List <string>(),
                TechnicalDescription   = "TechnicalDescription",
                ExtraRequirements      = "ExtraRequirements",
                ResearchTheme          = "ResearchTheme",
                Activities             = new List <string>(),
                RequiredStudentsAmount = 2,
                AdditionalRemarks      = "AdditionalRemarks",
                Periods         = new List <string>(),
                Description     = "Description",
                DateCreated     = DateTime.UtcNow,
                DateOfState     = DateTime.UtcNow,
                Id              = Guid.NewGuid(),
                InternshipState = 0,
                Reviewers       = new List <ReviewerInternships> {
                    new ReviewerInternships
                    {
                        ReviewedInternship = internship,
                        Reviewer           = userTeacher
                    }
                }
            };

            updateUser = new UserUpdate
            {
                FieldOfStudy = "UpdatedFOS"
            };

            userValidateDto = new UserValidateDto
            {
                Id        = userCompany.Id,
                Validated = true
            };

            pwDto = new ChangePasswordDto
            {
                OldPassword = userStudent.PasswordHash,
                NewPassword = "******"
            };

            companyUpdate = new CompanyUpdate
            {
                CompanyName = "Updated"
            };

            _context.Add(company);

            _context.Add(userCompany);
            _context.Roles.Add(roleCompany);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleCompany.Id,
                UserId = userCompany.Id
            });
            _context.Add(userTeacher);
            _context.Roles.Add(roleTeacher);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleTeacher.Id,
                UserId = userTeacher.Id
            });
            _context.Add(userStudent);
            _context.Roles.Add(roleStudent);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleStudent.Id,
                UserId = userStudent.Id
            });
            _context.Add(internship);
            _context.SaveChanges();
        }
Пример #29
0
#pragma warning disable CA1502 // TODO: Decomplexify
#pragma warning disable CA1506
        public async Task <IActionResult> Update([FromBody] UserUpdate model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!model.Id.HasValue || model.OAuthConnections?.Any(x => x == null) == true)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.ModelValidationFailure)));
            }

            if (model.Group != null && model.PermissionSet != null)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserGroupAndPermissionSet)));
            }

            var callerAdministrationRights = (AdministrationRights)AuthenticationContext.GetRight(RightsType.Administration);
            var canEditAllUsers            = callerAdministrationRights.HasFlag(AdministrationRights.WriteUsers);
            var passwordEdit = canEditAllUsers || callerAdministrationRights.HasFlag(AdministrationRights.EditOwnPassword);
            var oAuthEdit    = canEditAllUsers || callerAdministrationRights.HasFlag(AdministrationRights.EditOwnOAuthConnections);

            var originalUser = !canEditAllUsers
                                ? AuthenticationContext.User
                                : await DatabaseContext
                               .Users
                               .AsQueryable()
                               .Where(x => x.Id == model.Id)
                               .Include(x => x.CreatedBy)
                               .Include(x => x.OAuthConnections)
                               .Include(x => x.Group)
                               .ThenInclude(x => x.PermissionSet)
                               .Include(x => x.PermissionSet)
                               .FirstOrDefaultAsync(cancellationToken)
                               .ConfigureAwait(false);

            if (originalUser == default)
            {
                return(NotFound());
            }

            if (originalUser.CanonicalName == Models.User.CanonicalizeName(Models.User.TgsSystemUserName))
            {
                return(Forbid());
            }

            // Ensure they are only trying to edit things they have perms for (system identity change will trigger a bad request)
            if ((!canEditAllUsers &&
                 (model.Id != originalUser.Id ||
                  model.Enabled.HasValue ||
                  model.Group != null ||
                  model.PermissionSet != null ||
                  model.Name != null)) ||
                (!passwordEdit && model.Password != null) ||
                (!oAuthEdit && model.OAuthConnections != null))
            {
                return(Forbid());
            }

            if (model.SystemIdentifier != null && model.SystemIdentifier != originalUser.SystemIdentifier)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserSidChange)));
            }

            if (model.Password != null)
            {
                var result = TrySetPassword(originalUser, model.Password, false);
                if (result != null)
                {
                    return(result);
                }
            }

            if (model.Name != null && Models.User.CanonicalizeName(model.Name) != originalUser.CanonicalName)
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserNameChange)));
            }

            if (model.Enabled.HasValue)
            {
                if (originalUser.Enabled.Value && !model.Enabled.Value)
                {
                    originalUser.LastPasswordUpdate = DateTimeOffset.UtcNow;
                }

                originalUser.Enabled = model.Enabled.Value;
            }

            if (model.OAuthConnections != null &&
                (model.OAuthConnections.Count != originalUser.OAuthConnections.Count ||
                 !model.OAuthConnections.All(x => originalUser.OAuthConnections.Any(y => y.Provider == x.Provider && y.ExternalUserId == x.ExternalUserId))))
            {
                if (originalUser.CanonicalName == Models.User.CanonicalizeName(Api.Models.User.AdminName))
                {
                    return(BadRequest(new ErrorMessage(ErrorCode.AdminUserCannotOAuth)));
                }

                if (model.OAuthConnections.Count == 0 && originalUser.PasswordHash == null && originalUser.SystemIdentifier == null)
                {
                    return(BadRequest(new ErrorMessage(ErrorCode.CannotRemoveLastAuthenticationOption)));
                }

                originalUser.OAuthConnections.Clear();
                foreach (var updatedConnection in model.OAuthConnections)
                {
                    originalUser.OAuthConnections.Add(new Models.OAuthConnection
                    {
                        Provider       = updatedConnection.Provider,
                        ExternalUserId = updatedConnection.ExternalUserId
                    });
                }
            }

            if (model.Group != null)
            {
                originalUser.Group = await DatabaseContext
                                     .Groups
                                     .AsQueryable()
                                     .Where(x => x.Id == model.Group.Id)
                                     .Include(x => x.PermissionSet)
                                     .FirstOrDefaultAsync(cancellationToken)
                                     .ConfigureAwait(false);

                if (originalUser.Group == default)
                {
                    return(Gone());
                }

                DatabaseContext.Groups.Attach(originalUser.Group);
                if (originalUser.PermissionSet != null)
                {
                    Logger.LogInformation("Deleting permission set {0}...", originalUser.PermissionSet.Id);
                    DatabaseContext.PermissionSets.Remove(originalUser.PermissionSet);
                    originalUser.PermissionSet = null;
                }
            }
            else if (model.PermissionSet != null)
            {
                if (originalUser.PermissionSet == null)
                {
                    Logger.LogTrace("Creating new permission set...");
                    originalUser.PermissionSet = new Models.PermissionSet();
                }

                originalUser.PermissionSet.AdministrationRights  = model.PermissionSet.AdministrationRights ?? AdministrationRights.None;
                originalUser.PermissionSet.InstanceManagerRights = model.PermissionSet.InstanceManagerRights ?? InstanceManagerRights.None;

                originalUser.Group   = null;
                originalUser.GroupId = null;
            }

            var fail = CheckValidName(model, false);

            if (fail != null)
            {
                return(fail);
            }

            originalUser.Name = model.Name ?? originalUser.Name;

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            Logger.LogInformation("Updated user {0} ({1})", originalUser.Name, originalUser.Id);

            // return id only if not a self update and cannot read users
            return(Json(
                       AuthenticationContext.User.Id == originalUser.Id ||
                       callerAdministrationRights.HasFlag(AdministrationRights.ReadUsers)
                                ? originalUser.ToApi(true)
                                : new Api.Models.User
            {
                Id = originalUser.Id
            }));
        }
Пример #30
0
 /// <inheritdoc />
 public Task <User> Create(UserUpdate user, CancellationToken cancellationToken) => ApiClient.Create <UserUpdate, User>(Routes.User, user ?? throw new ArgumentNullException(nameof(user)), cancellationToken);
Пример #31
0
        public async Task <IActionResult> Create([FromBody] UserUpdate model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!(model.Password == null ^ model.SystemIdentifier == null))
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserMismatchPasswordSid)));
            }

            model.Name = model.Name?.Trim();
            if (model.Name?.Length == 0)
            {
                model.Name = null;
            }

            if (!(model.Name == null ^ model.SystemIdentifier == null))
            {
                return(BadRequest(new ErrorMessage(ErrorCode.UserMismatchNameSid)));
            }

            var fail = CheckValidName(model, true);

            if (fail != null)
            {
                return(fail);
            }

            var dbUser = new Models.User
            {
                AdministrationRights = RightsHelper.Clamp(model.AdministrationRights ?? AdministrationRights.None),
                CreatedAt            = DateTimeOffset.Now,
                CreatedBy            = AuthenticationContext.User,
                Enabled = model.Enabled ?? false,
                InstanceManagerRights = RightsHelper.Clamp(model.InstanceManagerRights ?? InstanceManagerRights.None),
                Name             = model.Name,
                SystemIdentifier = model.SystemIdentifier,
                InstanceUsers    = new List <Models.InstanceUser>()
            };

            if (model.SystemIdentifier != null)
            {
                try
                {
                    using var sysIdentity = await systemIdentityFactory.CreateSystemIdentity(dbUser, cancellationToken).ConfigureAwait(false);

                    if (sysIdentity == null)
                    {
                        return(Gone());
                    }
                    dbUser.Name             = sysIdentity.Username;
                    dbUser.SystemIdentifier = sysIdentity.Uid;
                }
                catch (NotImplementedException)
                {
                    return(RequiresPosixSystemIdentity());
                }
            }
            else
            {
                var result = TrySetPassword(dbUser, model.Password, true);
                if (result != null)
                {
                    return(result);
                }
            }

            dbUser.CanonicalName = Models.User.CanonicalizeName(dbUser.Name);

            DatabaseContext.Users.Add(dbUser);

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            return(Created(dbUser.ToApi(true)));
        }
        /// <summary>
        /// Update the specified <see cref="UserUpdate"/>.
        /// </summary>
        /// <param name="user">The login for the user</param>
        /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
        /// <returns>A <see cref="User"/></returns>
        public IObservable <User> Update(UserUpdate user)
        {
            Ensure.ArgumentNotNull(user, "user");

            return(_client.Update(user).ToObservable());
        }
Пример #33
0
 public Task <bool> UpdateProfil(UserUpdate userUpdate, string token)
 {
     return(_service.UpdateProfil(userUpdate, token));
 }
Пример #34
0
 public override void UserUpdated(TwilioChatClient client, User user, UserUpdate updated)
 {
     Logger.Info($"ChatClient: {client}", $"UserUpdated: {user.Identity}, reason: {updated}");
 }
Пример #35
0
        public async Task <PersonEntryFixed> UpdateUser([FromRoute] string userId, [FromBody] UserUpdate body)
        {
            var update = new PersonBodyUpdate
            {
                Email      = body.Email,
                FirstName  = body.FirstName,
                LastName   = body.LastName,
                Properties = new Dictionary <string, object>
                {
                    { SpisumNames.Properties.Group, body.MainGroup },
                    { SpisumNames.Properties.UserJob, body.UserJob },
                    { SpisumNames.Properties.UserOrgAddress, body.UserOrgAddress },
                    { SpisumNames.Properties.UserOrgId, body.UserOrgId },
                    { SpisumNames.Properties.UserOrgName, body.UserOrgName },
                    { SpisumNames.Properties.UserOrgUnit, body.UserOrgUnit },
                    { SpisumNames.Properties.UserName, $"{body.FirstName} {body.LastName}".Trim() },
                    { SpisumNames.Properties.UserId, body.UserId }
                }
            };

            if (!string.IsNullOrWhiteSpace(body.Password))
            {
                update.Password = body.Password;
            }

            var userInfo = await _alfrescoHttpClient.UpdatePerson(userId, update);

            var userGroupsInfo = await _alfrescoHttpClient.GetPersonGroups(userId);

            var userGroups = userGroupsInfo?.List?.Entries?.Select(x => x.Entry?.Id)?.Where(
                x => Array.IndexOf(new[] { SpisumNames.Groups.MainGroup, SpisumNames.Groups.Everyone }, x) == -1 && !x.StartsWith(SpisumNames.Prefixes.UserGroup)
                )?.ToList() ?? new List <string>();

            var allGroupsInfo = await _alfrescoHttpClient.GetGroupMembers(SpisumNames.Groups.MainGroup,
                                                                          ImmutableList <Parameter> .Empty.Add(new Parameter(AlfrescoNames.Headers.Where, AlfrescoNames.MemberType.Group, ParameterType.QueryString)));

            var allGroups  = allGroupsInfo?.List?.Entries?.Select(x => x.Entry?.Id)?.ToList() ?? new List <string>();
            var signGroups = body.SignGroups ?? new List <string>();

            var groupList = body.Groups?.ToList() ?? new List <string>();

            groupList.AddUnique(body.MainGroup);
            groupList.AddRangeUnique(signGroups);

            // remove all groups included in main groups
            for (int i = userGroups.Count - 1; i >= 0; i--)
            {
                var group = userGroups[i];
                if (allGroups.Exists(x => x.StartsWith(@group)) && !groupList.Contains(@group) ||
                    @group.EndsWith(SpisumNames.Postfixes.Sign) && !signGroups.Contains(@group))
                {
                    try
                    {
                        await _alfrescoHttpClient.DeleteGroupMember(@group, userId);

                        userGroups.RemoveAt(i);
                    }
                    catch
                    {
                    }
                }
            }

            foreach (var group in groupList.Where(x => !userGroups.Contains(x)))
            {
                try
                {
                    await _alfrescoHttpClient.CreateGroupMember(@group, new GroupMembershipBodyCreate { Id = userInfo.Entry.Id, MemberType = GroupMembershipBodyCreateMemberType.PERSON });
                }
                catch
                {
                }
            }

            foreach (var group in signGroups.Where(x => !userGroups.Contains(x + SpisumNames.Postfixes.Sign)))
            {
                try
                {
                    await _initialUser.CheckCreateGroupAndAddPerson(userInfo.Entry.Id, @group + SpisumNames.Postfixes.Sign);
                }
                catch
                {
                }
            }

            return(userInfo);
        }
        public async Task <IActionResult> Update([FromBody] UserUpdate model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var callerAdministrationRights = (AdministrationRights)AuthenticationContext.GetRight(RightsType.Administration);
            var passwordEditOnly           = !callerAdministrationRights.HasFlag(AdministrationRights.WriteUsers);

            var originalUser = passwordEditOnly
                                ? AuthenticationContext.User
                                : await DatabaseContext.Users.Where(x => x.Id == model.Id)
                               .Include(x => x.CreatedBy)
                               .FirstOrDefaultAsync(cancellationToken)
                               .ConfigureAwait(false);

            if (originalUser == default)
            {
                return(NotFound());
            }

            // Ensure they are only trying to edit password (system identity change will trigger a bad request)
            if (passwordEditOnly && (model.Id != originalUser.Id || model.InstanceManagerRights.HasValue || model.AdministrationRights.HasValue || model.Enabled.HasValue || model.Name != null))
            {
                return(Forbid());
            }

            if (model.SystemIdentifier != null && model.SystemIdentifier != originalUser.SystemIdentifier)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "Cannot change a user's system identifier!"
                }));
            }

            if (model.Password != null)
            {
                var result = TrySetPassword(originalUser, model.Password);
                if (result != null)
                {
                    return(result);
                }
            }

            if (model.Name != null && Models.User.CanonicalizeName(model.Name) != originalUser.CanonicalName)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "Can only change capitalization of a user's name!"
                }));
            }

            originalUser.InstanceManagerRights = model.InstanceManagerRights ?? originalUser.InstanceManagerRights;
            originalUser.AdministrationRights  = model.AdministrationRights ?? originalUser.AdministrationRights;
            originalUser.Enabled = model.Enabled ?? originalUser.Enabled;

            var fail = CheckValidName(model);

            if (fail != null)
            {
                return(fail);
            }

            originalUser.Name = model.Name ?? originalUser.Name;

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            // return id only if not a self update or and cannot read users
            return(Json(
                       model.Id == originalUser.Id ||
                       callerAdministrationRights.HasFlag(AdministrationRights.ReadUsers)
                                ? originalUser.ToApi(true)
                                : new Api.Models.User
            {
                Id = originalUser.Id
            }));
        }
Пример #37
0
        public void Test_HomeController_Update_Post()
        {
            var value = new UserUpdate
            {
                Name = "test",
                CurrentName = "test",
                EmailAddress = "*****@*****.**",
                VerifyEmailAddress = "*****@*****.**",
                CurrentEmailAddress = "*****@*****.**"
            };

            var viewResult = this.HomeController.Update(value) as ViewResult;

            Assert.IsNotNull(viewResult, "ViewResult");
            Assert.AreEqual(Views.Update, viewResult.ViewName, "ViewName");
            Assert.AreEqual(Messages.UserAccountUpdated, value.Message.Message);

            value.Name = null;

            var errorResult = this.HomeController.Update(value) as ViewResult;

            Assert.IsNotNull(errorResult, "ErrorResult");
            Assert.AreEqual(Views.Update, viewResult.ViewName, "ErrorViewName");
            Assert.AreEqual(2, value.Errors.Count, "Errors");
        }