public ActionResult UpdateProfile_Post(UpdateUserProfileModel model)
        {
            try
            {
                var currentIdentity = HttpContext.User.Identity as ClaimsIdentity;

                var avatarClaim = currentIdentity.FindFirst(ClaimKeys.Avatar);
                if (avatarClaim != null)
                {
                    currentIdentity.RemoveClaim(avatarClaim);
                    UserManager.RemoveClaim(model.UserId, avatarClaim);
                }

                currentIdentity.AddClaim(new Claim(ClaimKeys.Avatar, model.Avatar));
                UserManager.AddClaim(model.UserId, new Claim(ClaimKeys.Avatar, model.Avatar));

                var authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(currentIdentity), new AuthenticationProperties()
                {
                    IsPersistent = true
                });

                this.AddNotification("Update profile successfully", NotificationType.SUCCESS);
            }
            catch (Exception ex)
            {
                this.AddNotification("System is busy now. Please try again later", NotificationType.ERROR);
                var strError = string.Format("Could not UpdateProfile because: {0}", ex.ToString());
                logger.Error(strError);

                return(View(model));
            }

            return(View(model));
        }
        public ActionResult UpdateProfile()
        {
            var model = new UpdateUserProfileModel();

            try
            {
                if (Request.IsAuthenticated)
                {
                    model.UserId   = User.Identity.GetUserId();
                    model.UserName = User.Identity.GetUserName();

                    var claims = (ClaimsIdentity)User.Identity;
                    model.FullName = claims.FindFirstValue(ClaimKeys.FullName);
                    model.Avatar   = claims.FindFirstValue(ClaimKeys.Avatar);
                }
            }
            catch (Exception ex)
            {
                this.AddNotification("System is busy now. Please try again later", NotificationType.ERROR);
                var strError = string.Format("Could not open page UpdateProfile because: {0}", ex.ToString());
                logger.Error(strError);

                return(View(model));
            }

            return(View(model));
        }
Example #3
0
        public async Task <IActionResult> UpdateProfile(int id, [FromBody] UpdateUserProfileModel model)
        {
            if (id <= 0 || model is null)
            {
                return(BadRequest(new { Message = "Invalid client request" }));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(new { Message = ModelState.Values.SelectMany(x => x.Errors) }));
            }

            try
            {
                var user = await this._userService.Get(id);

                if (user == null)
                {
                    return(NotFound(new { Message = "User not found" }));
                }

                user.Culture   = model.Culture;
                user.Firstname = model.Firstname;
                user.Surname   = model.Surname;
                user.Timezone  = model.Timezone;

                if (!string.IsNullOrEmpty(model.Password) & !string.IsNullOrEmpty(model.NewPassword))
                {
                    if (!PasswordHasher.VerifyHash(model.Password, user.Salt, user.PasswordHash))
                    {
                        return(BadRequest(new { Message = "Wrong current password" }));
                    }

                    var hash = PasswordHasher.ComputeHash(model.NewPassword);
                    user.PasswordHash = hash.Hash;
                    user.Salt         = hash.Salt;
                    await _userService.Update(user);

                    return(Ok(new { Message = "User was updated" }));
                }

                await _userService.Update(user);

                var links = HypermediaHelper.PutUserHypermediaLinks(this, id);

                return(Ok(new
                {
                    Message = "User updated",
                    Links = links
                }));
            }
            catch (UserException exception)
            {
                return(BadRequest(new { exception.Message }));
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
Example #4
0
        public async Task UpdateUserProfileTest(KnownChains apiName, string followUser)
        {
            var user = Users[apiName];

            var userProfileModel = new UserProfileModel(user.Login);
            var profileResponse  = await Api[apiName].GetUserProfile(userProfileModel, CancellationToken.None);

            AssertResult(profileResponse);
            Assert.IsTrue(profileResponse.IsSuccess);
            var profile = profileResponse.Result;

            var updateUserProfileModel = new UpdateUserProfileModel()
            {
                Login        = user.Login,
                ActiveKey    = user.PostingKey,
                About        = profile.About,
                Location     = profile.Location,
                Name         = profile.Name,
                ProfileImage = profile.ProfileImage,
                Website      = profile.Website
            };
            var response = await Api[apiName].UpdateUserProfile(updateUserProfileModel, CancellationToken.None);

            AssertResult(response);
            Assert.IsTrue(response.IsSuccess);
        }
        //PUT: /api/UserProfile
        public async Task <ApiResponse> UpdateUserProfile([FromBody] UpdateUserProfileModel userProfile)
        {
            var emailChanged = false;

            string userId = User.Claims.First(c => c.Type == "UserID").Value;
            var    user   = await _userManager.FindByIdAsync(userId);

            //user.Notes = userProfile.Notes;
            if (userProfile.FirstName != null)
            {
                user.FirstName = userProfile.FirstName;
            }

            if (userProfile.LastName != null)
            {
                user.LastName = userProfile.LastName;
            }

            if (userProfile.Department != null)
            {
                user.Department = userProfile.Department;
            }

            if (userProfile.Position != null)
            {
                user.Position = userProfile.Position;
            }

            if (userProfile.UserName != null)
            {
                user.UserName = userProfile.UserName;
            }

            if (userProfile.Email != null &&
                !string.Equals(userProfile.Email.Replace(" ", ""), user.NormalizedEmail))
            {
                user.Email = userProfile.Email;

                user.EmailConfirmed = false;

                emailChanged = true;
            }

            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                return(new ApiResponse());
            }
            else
            {
                return new ApiResponse
                       {
                           ErrorMessage = result.Errors.ToString()
                       }
            };
        }
Example #6
0
        public async Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            var results = Validate(model);

            if (results.Any())
            {
                return(new OperationResult <VoidResponse>(new ValidationError(string.Join(Environment.NewLine, results.Select(i => i.ErrorMessage)))));
            }

            return(await _ditchClient.UpdateUserProfile(model, ct));
        }
Example #7
0
        public async Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            var results = Validate(model);

            if (results.Any())
            {
                return(new OperationResult <VoidResponse>(new ValidationError(results)));
            }

            return(await _ditchClient.UpdateUserProfile(model, ct));
        }
        protected string UpdateProfileJson(string jsonMetadata, UpdateUserProfileModel model)
        {
            var meta     = string.IsNullOrEmpty(jsonMetadata) ? "{}" : jsonMetadata;
            var jMeta    = JsonConvert.DeserializeObject <JObject>(meta);
            var jProfile = GetOrCreateJObject(jMeta, "profile");

            UpdateJValue(jProfile, "profile_image", model.ProfileImage);
            UpdateJValue(jProfile, "name", model.Name);
            UpdateJValue(jProfile, "location", model.Location);
            UpdateJValue(jProfile, "website", model.Website);
            UpdateJValue(jProfile, "about", model.About);
            return(JsonConvert.SerializeObject(jMeta));
        }
        public async Task <Result <LightUserModel> > UpdateProfile([FromQuery] string placeid,
                                                                   UpdateUserProfileModel model)
        {
            var placeDetail = await _placeApi.PlaceDetail(placeid);

            if (placeDetail.Success)
            {
                model.Province   = placeDetail.Data.Item1;
                model.City       = placeDetail.Data.Item2;
                model.PostalCode = placeDetail.Data.Item3;
                model.Address    = placeDetail.Data.Item4;
            }

            return(await _membershipServiceApi.AuthAuthApiService.UpdateProfile(model));
        }
Example #10
0
        public IActionResult Update(int id, [FromBody] UpdateUserProfileModel model)
        {
            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                _userService.Update(user);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
        public async Task <ErrorBase> TryUpdateUserProfile(UpdateUserProfileModel model, UserProfileResponse currentProfile)
        {
            var error = await TryRunTask(UpdateUserProfile, OnDisposeCts.Token, model);

            if (error != null)
            {
                NotifySourceChanged(nameof(TryUpdateUserProfile), false);
            }
            else
            {
                //TODO:KOA: Looks like it is work for AutoMapper
                currentProfile.About        = model.About;
                currentProfile.Name         = model.Name;
                currentProfile.Location     = model.Location;
                currentProfile.Website      = model.Website;
                currentProfile.ProfileImage = model.ProfileImage;
                NotifySourceChanged(nameof(TryUpdateUserProfile), false);
            }

            return(error);
        }
Example #12
0
        public override async Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            var isConnected = await TryReconnectChain(ct);

            if (!isConnected)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.EnableConnectToBlockchain)));
            }

            var keys = ToKeyArr(model.ActiveKey);

            if (keys == null)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivateActimeKey)));
            }

            var resp = await _operationManager.LookupAccountNames(new[] { model.Login }, CancellationToken.None);

            var result = new OperationResult <VoidResponse>();

            if (resp.IsError)
            {
                result.Exception = new RequestException(resp);
                return(result);
            }

            var profile = resp.Result.Length == 1 ? resp.Result[0] : null;

            if (profile == null)
            {
                result.Exception = new ValidationException(LocalizationKeys.UnexpectedProfileData);
                return(result);
            }

            var editedMeta = UpdateProfileJson(profile.JsonMetadata, model);

            var op    = new AccountUpdateOperation(model.Login, profile.MemoKey, editedMeta);
            var resp2 = await _operationManager.BroadcastOperationsSynchronous(keys, ct, op);

            if (resp2.IsError)
            {
                result.Exception = new RequestException(resp2);
            }
            else
            {
                result.Result = new VoidResponse();
            }
            return(result);
        }
Example #13
0
        public override async Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            return(await Task.Run(() =>
            {
                if (!TryReconnectChain(ct))
                {
                    return new OperationResult <VoidResponse>(new AppError(LocalizationKeys.EnableConnectToBlockchain));
                }

                var keys = ToKeyArr(model.ActiveKey);
                if (keys == null)
                {
                    return new OperationResult <VoidResponse>(new AppError(LocalizationKeys.WrongPrivateActimeKey));
                }

                var findAccountsArgs = new FindAccountsArgs
                {
                    Accounts = new[] { model.Login }
                };
                var resp = _operationManager.FindAccounts(findAccountsArgs, CancellationToken.None);
                var result = new OperationResult <VoidResponse>();
                if (resp.IsError)
                {
                    OnError(resp, result);
                    return result;
                }

                var profile = resp.Result.Accounts.Length == 1 ? resp.Result.Accounts[0] : null;
                if (profile == null)
                {
                    result.Error = new BlockchainError(LocalizationKeys.UnexpectedProfileData);
                    return result;
                }

                var editedMeta = UpdateProfileJson(profile.JsonMetadata, model);

                var op = new AccountUpdateOperation(model.Login, profile.MemoKey, editedMeta);
                var resp2 = _operationManager.BroadcastOperationsSynchronous(keys, ct, op);
                if (!resp2.IsError)
                {
                    result.Result = new VoidResponse();
                }
                else
                {
                    OnError(resp2, result);
                }
                return result;
            }, ct));
        }
Example #14
0
 public async Task <Result <LightUserModel> > UpdateProfile(UpdateUserProfileModel model)
 => await _userBiz.UpdateProfile(model);
Example #15
0
        public override async Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            var isConnected = await TryReconnectChain(ct);

            if (!isConnected)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.EnableConnectToBlockchain)));
            }

            var keys = ToKeyArr(model.ActiveKey);

            if (keys == null)
            {
                return(new OperationResult <VoidResponse>(new ValidationException(LocalizationKeys.WrongPrivateActimeKey)));
            }

            var args = new FindAccountsArgs
            {
                Accounts = new[] { model.Login }
            };
            var resp = await _operationManager.FindAccounts(args, CancellationToken.None);

            var result = new OperationResult <VoidResponse>();

            if (resp.IsError)
            {
                result.Exception = new RequestException(resp);
                return(result);
            }

            var profile = resp.Result.Accounts.Length == 1 ? resp.Result.Accounts[0] : null;

            if (profile == null)
            {
                result.Exception = new ValidationException(LocalizationKeys.UnexpectedProfileData);
                return(result);
            }

            var editedMeta = UpdateProfileJson(profile.JsonMetadata, model);

            var op = new AccountUpdateOperation(model.Login, profile.MemoKey, editedMeta);

            return(await Broadcast(keys, new BaseOperation[] { op }, ct));
        }
 public abstract Task <OperationResult <VoidResponse> > UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct);
        public async Task <ActionResult> UpdateProfile(UpdateUserProfileModel model)
        {
            await _userService.UpdateProfile(model.Name, model.Password, model.ProfileImgUrl);

            return(Ok("Profile updated"));
        }
        public Task <Result <LightUserModel> > UpdateProfile(UpdateUserProfileModel model)
        => Result <LightUserModel> .TryAsync(async() =>
        {
            var result =
                await _repository.FirstOrDefaultAsync <User>(u => u.Id == generalDataService.User.Id,
                                                             u => u.Receipt,
                                                             u => u.Role.RoleFeature.Select(rf =>
                                                                                            rf.Feature.FeaturePermission.Select(fp => fp.Permission)));
            if (!result.Success || result.Data == null)
            {
                return(Result <LightUserModel> .Failed(Error.WithCode(ErrorCodes.UserNotFound)));
            }
            var user = result.Data;


            var duplicateEmail =
                await _repository.FirstOrDefaultAsNoTrackingAsync <User>(u =>
                                                                         u.Id != user.Id && model.Email == u.Email);
            if (duplicateEmail.Success && duplicateEmail.Data != null)
            {
                return(Result <LightUserModel> .Failed(Error.WithData(1000, new[] { "duplicate email address" })));
            }

            var duplicateMobile =
                await _repository.FirstOrDefaultAsNoTrackingAsync <User>(u =>
                                                                         u.Id != user.Id && model.Mobile == u.Mobile);
            if (duplicateMobile.Success && duplicateMobile.Data != null)
            {
                return(Result <LightUserModel> .Failed(Error.WithData(1000, new[] { "duplicate mobile" })));
            }

            _repository.RemoveRange(user.Receipt);

            user.Address    = model.Address;
            user.City       = model.City;
            user.Province   = model.Province;
            user.Email      = model.Email;
            user.PostalCode = model.PostalCode;
            user.PoBox      = model.PoBox;
            user.Firstname  = model.Firstname;
            user.SinNumber  = model.SinNumber;
            user.UnitNumber = model.UnitNumber;
            user.UnitNumber = model.UnitNumber;
            user.Lastname   = model.Lastname;
            user.Mobile     = model.Mobile;
            user.AvatarId   = model.AvatarId;
            user.Receipt    = model.Receipts == null || !model.Receipts.Any()
                    ? null
                    : model.Receipts.Select(r => new Receipt {
                BlobId = r, Id = Guid.NewGuid()
            }).ToList();
            user.Latitude      = model.Latitude;
            user.MaritalStatus = (byte)model.MaritalStatus;
            user.Longtitude    = model.Longtitude;
            user.Gender        = model.Gender;
            user.DateOfBirth   = model.DateOfBirth ?? user.DateOfBirth;

            if (!string.IsNullOrEmpty(model.Password))
            {
                model.Password = _cryptoService.ComputeSha512Hash(model.Password);
                user.Password  = model.Password;
            }

            await _repository.CommitAsync();
            return(Result <LightUserModel> .Successful(new LightUserModel
            {
                Id = user.Id,
                Firstname = user.Firstname,
                Lastname = user.Lastname,
                Username = user.Username,
                Gender = user.Gender,
                Role = new RoleModel
                {
                    Id = user.Role.Id,
                    Name = user.Role.Name,
                    Feature = user.Role.RoleFeature.Select(rf => new FeatureModel
                    {
                        Id = rf.Feature.Id,
                        Permissions = rf.Feature.FeaturePermission.Select(fp => new PermissionModel
                        {
                            Id = (PermissionType)fp.Permission.Id, Name = fp.Permission.Name
                        }).ToList()
                    }).ToList()
                }
            }));
        });
        private async Task <ErrorBase> UpdateUserProfile(UpdateUserProfileModel model, CancellationToken ct)
        {
            var response = await Api.UpdateUserProfile(model, ct);

            return(response.Error);
        }