Exemplo n.º 1
0
        public async Task <IActionResult> UpdateUserProfile([FromBody] UpdateUserProfileRequest userProfileRequest)
        {
            var loggedUser = User.GetUserIdFromToken();
            await _accountService.UpdateProfileAsync(loggedUser, userProfileRequest);

            return(Ok());
        }
Exemplo n.º 2
0
        public async Task <IEnumerable <Claim> > UpdateUserProfile(string userId, UpdateUserProfileRequest request)
        {
            var existedUser = await _userManager.FindByEmailAsync(userId);

            if (existedUser == null)
            {
                throw new Exception($"User with email: {userId} was not found");
            }

            var claims = await _userManager.GetClaimsAsync(existedUser);

            if (request.FirstName != claims.Single(p => p.Type == "FirstName").Value)
            {
                await _userManager.ReplaceClaimAsync(existedUser, claims.Single(p => p.Type == "FirstName"), new Claim("FirstName", request.FirstName));
            }

            if (request.FirstName != claims.Single(p => p.Type == "LastName").Value)
            {
                await _userManager.ReplaceClaimAsync(existedUser, claims.Single(p => p.Type == "LastName"), new Claim("LastName", request.LastName));
            }

            if (request.FirstName != claims.Single(p => p.Type == "Phone").Value)
            {
                await _userManager.ReplaceClaimAsync(existedUser, claims.Single(p => p.Type == "Phone"), new Claim("Phone", request.Phone));
            }

            if (request.FirstName != claims.Single(p => p.Type == "City").Value)
            {
                await _userManager.ReplaceClaimAsync(existedUser, claims.Single(p => p.Type == "City"), new Claim("City", request.City));
            }

            var updatedClaims = await _userManager.GetClaimsAsync(existedUser);

            return(updatedClaims);
        }
Exemplo n.º 3
0
        public object Put(UpdateUserProfileRequest request)
        {
            if (request.Id == default(int))
            {
                request.Id = SessionUserId;
            }

            if (SessionUserId != request.Id)
            // Only admins may change other users profile
            {
                EnsureIsAdmin();
            }

            var userAuth        = Db.SingleById <UserAuth>(request.Id);
            var userAuthUpdated = Db.SingleById <UserAuth>(request.Id).PopulateWith(request);

            userAuthUpdated.SetDivision(UserAuthMetaKeys.DivisionLuzern, request.DivisionLuzern);
            userAuthUpdated.SetDivision(UserAuthMetaKeys.DivisionStGallen, request.DivisionStGallen);
            userAuthUpdated.SetDivision(UserAuthMetaKeys.DivisionZürich, request.DivisionZuerich);
            userAuthUpdated.SetDivision(UserAuthMetaKeys.DivisionWinti, request.DivisionWinti);

            if (string.IsNullOrWhiteSpace(request.Password))
            {
                userAuthRepository.UpdateUserAuth(userAuth, userAuthUpdated);
            }
            else
            {
                userAuthRepository.UpdateUserAuth(userAuth, userAuthUpdated, request.Password);
            }


            return(Db.SingleById <UserAuth>(request.Id).ToUserProfileResponse());
        }
Exemplo n.º 4
0
        internal UpdateUserProfileResponse UpdateUserProfile(UpdateUserProfileRequest request)
        {
            var marshaller   = new UpdateUserProfileRequestMarshaller();
            var unmarshaller = UpdateUserProfileResponseUnmarshaller.Instance;

            return(Invoke <UpdateUserProfileRequest, UpdateUserProfileResponse>(request, marshaller, unmarshaller));
        }
        public async Task <CreateUserProfileResponse> UpdateProfile(UpdateUserProfileRequest user)
        {
            IsBusy = true;
            try
            {
                var res = await userProfileAPI.UpdateUserProfile(user);

                if (res != null)
                {
                    if (res.Code == 0)
                    {
                        return(res);
                    }
                    else
                    {
                        return(null);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                IsBusy = false;
            }
        }
        public IEnumerator UpdateUserProfile(string @namespace, string userAccessToken,
                                             UpdateUserProfileRequest updateRequest, ResultCallback <UserProfile> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(@namespace, "Can't update user profile! Namespace parameter is null!");
            Assert.IsNotNull(userAccessToken, "Can't update user profile! UserAccessToken parameter is null!");
            Assert.IsNotNull(updateRequest, "Can't update user profile! ProfileRequest parameter is null!");

            var request = HttpRequestBuilder
                          .CreatePut(this.baseUrl + "/v1/public/namespaces/{namespace}/users/me/profiles")
                          .WithPathParam("namespace", @namespace)
                          .WithBearerAuth(userAccessToken)
                          .WithContentType(MediaType.ApplicationJson)
                          .Accepts(MediaType.ApplicationJson)
                          .WithBody(updateRequest.ToUtf8Json())
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpClient.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <UserProfile>();

            callback.Try(result);
        }
Exemplo n.º 7
0
        public async Task UpdateUser_ResponseStatus_204(UpdateUserProfileRequest request)
        {
            // Arrange
            var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, "anuviswan"),
            }, "mock"));

            var userProfileEntity      = Mapper.Map <UserProfileEntity>(request);
            var mockUserProfileService = new Mock <IUserProfileService>();

            mockUserProfileService.Setup(x => x.UpdateUserAsync(It.IsAny <UserProfileEntity>()))
            .Returns(Task.FromResult(true));

            var userController = new UserController(Mapper, mockUserProfileService.Object, null, null);

            userController.ControllerContext.HttpContext = new DefaultHttpContext {
                User = user
            };
            MockModelState(request, userController);

            // Act
            var response = await userController.UpdateUser(request);

            // Assert
            Assert.IsType <NoContentResult>(response);
        }
Exemplo n.º 8
0
        public override async Task <Empty> UpdateUserProfile(UpdateUserProfileRequest request, ServerCallContext context)
        {
            var updateUserProfileCommand = _mapper.Map <UpdateUserProfileCommand>(request);
            var response = await _mediator.Send(updateUserProfileCommand);

            return(new Empty());
        }
        public async Task <IActionResult> UpdateProfile(int profileId, [FromBody] UpdateUserProfileRequest request)
        {
            var updateUserProfileCommand = new UpdateUserProfileCommand(profileId, request);
            var result = await mediator.Send(updateUserProfileCommand);

            return(StatusCode((int)result.Code, result.Value));
        }
        public async Task <CreateUserProfileResponse> UpdateUserProfile(UpdateUserProfileRequest user)
        {
            string url         = $"/users/update";
            var    requestBody = await Task.Run(() => JsonConvert.SerializeObject(user));

            using (HttpClient httpClient = new HttpClient())
            {
                CreateUserProfileResponse data = new CreateUserProfileResponse();
                try
                {
                    var authHeader = new AuthenticationHeaderValue("Bearer", await SecureStorage.GetAsync("auth_token"));
                    httpClient.DefaultRequestHeaders.Authorization = authHeader;
                    httpClient.BaseAddress = new Uri(Constants.BaseUrl);
                    StringContent       content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    HttpResponseMessage result  = await httpClient.PostAsync(url, content);

                    string response = await result.Content.ReadAsStringAsync();

                    data = JsonConvert.DeserializeObject <CreateUserProfileResponse>(response);

                    if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
                    {
                        return(data);
                    }

                    return(null);
                }
                catch (Exception exp)
                {
                    return(null);
                }
            }
        }
Exemplo n.º 11
0
        public async Task UpdateUserProfile(UpdateUserProfileRequest request)
        {
            CurrentUser currentUser = MemoryCache.Default["currentUser"] as CurrentUser;

            User user = await _unitOfWork.Users.All()
                        .FirstOrDefaultAsync(x => x.Id == currentUser.Id);

            if (user == null)
            {
                throw new NotFoundException();
            }

            bool userEmailExists = _unitOfWork.Users.All()
                                   .Any(x => x.Email == request.Email && x.Id != user.Id);

            if (userEmailExists)
            {
                throw new BadRequestException();
            }

            user.Name  = request.Name;
            user.Email = request.Email;
            user.City  = request.City;
            user.Phone = request.Phone;

            _unitOfWork.Users.Update(user);
            await _unitOfWork.SaveAsync();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateUserProfile operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateUserProfile operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-2017-04-19/UpdateUserProfile">REST API Reference for UpdateUserProfile Operation</seealso>
        public Task <UpdateUserProfileResponse> UpdateUserProfileAsync(UpdateUserProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new UpdateUserProfileRequestMarshaller();
            var unmarshaller = UpdateUserProfileResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateUserProfileRequest, UpdateUserProfileResponse>(request, marshaller,
                                                                                     unmarshaller, cancellationToken));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateUserProfile operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateUserProfile operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-2017-04-19/UpdateUserProfile">REST API Reference for UpdateUserProfile Operation</seealso>
        public virtual Task <UpdateUserProfileResponse> UpdateUserProfileAsync(UpdateUserProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateUserProfileRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateUserProfileResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateUserProfileResponse>(request, options, cancellationToken));
        }
Exemplo n.º 14
0
        internal virtual UpdateUserProfileResponse UpdateUserProfile(UpdateUserProfileRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateUserProfileRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateUserProfileResponseUnmarshaller.Instance;

            return(Invoke <UpdateUserProfileResponse>(request, options));
        }
Exemplo n.º 15
0
        public Domain.Result Update(Guid id, UpdateUserProfileRequest request)
        {
            var userProfile = _repository.Load(id);
            var result      = userProfile.UpdateDisplayName(request.DisplayName);

            _meetupReadModelUpdater.OnUserDisplayNameUpdated(userProfile);
            _repository.Commit();
            return(result);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> UpdateUserInfo(UpdateUserProfileRequest profileRequest)
        {
            var userId = HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.NameIdentifier)?.Value;
            var user   = await _userManager.GetById(userId);

            var toInsert = profileRequest.MergeToModel(user);

            await _userManager.UpdateProfileAsync(toInsert);

            return(Ok(UserProfileRequest.Create(toInsert)));
        }
Exemplo n.º 17
0
        public IActionResult Update(Guid id, UpdateUserProfileRequest request)
        {
            var result = _applicationService.Update(id, request);

            if (result.Success)
            {
                return(Ok());
            }
            else
            {
                return(BadRequest(new { Error = result.ErrorMessage }));
            }
        }
Exemplo n.º 18
0
        public void UpdateUserProfileWithPassword()
        {
            var client  = ClientHelper.GetClient();
            var request = new UpdateUserProfileRequest {
                Id = 1336, Email = "*****@*****.**", FirstName = "Oliver2", LastName = "Zürcher2", Password = "******"
            };

            var response = client.Put(request);

            Assert.AreEqual(request.Email, response.Email);
            Assert.AreEqual(request.FirstName, response.FirstName);
            Assert.AreEqual(request.LastName, response.LastName);
        }
        public void UpdateProfileFirstNameTest()
        {
            // Arrange
            UpdateUserProfileRequest req = new UpdateUserProfileRequest();

            req.Properties.Add("firstName", newFirstName);

            // Act
            BaseResponse res = secAuthSvc.User.UpdateUserProfile(goodUsername, req);

            // Assert
            Assert.AreEqual(Constants.ResponseStatus.Success, res.Status);
        }
        public void UpdateProfileKBTest()
        {
            // Arrange
            UpdateUserProfileRequest req = new UpdateUserProfileRequest();

            req.KnowledgeBase.Add("kbq1", new KbProperty("Which Voltron lion is your favorite?", "The black one"));

            // Act
            BaseResponse res = secAuthSvc.User.UpdateUserProfile(goodUsername, req);

            // Assert
            Assert.AreEqual(Constants.ResponseStatus.Success, res.Status);
        }
Exemplo n.º 21
0
        public async Task <ActionResult <string> > UpdateUserProfile([FromBody] UpdateUserProfileRequest request)
        {
            var userId        = Request.Headers.GetEmailFromDecodedToken();
            var updatedClaims = await _authService.UpdateUserProfile(userId, request);

            var token    = GenerateJwt(updatedClaims);
            var response = new
            {
                access_token = token
            };
            var result = JsonConvert.SerializeObject(response);

            return(Ok(result));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Update some fields of user profile for current logged in user.
        /// </summary>
        /// <param name="updateRequest">User profile details to update user profile</param>
        /// <param name="callback">Returns a Result that contains UserProfile via callback when completed</param>
        public void UpdateUserProfile(UpdateUserProfileRequest updateRequest, ResultCallback <UserProfile> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);

            if (!this.session.IsValid())
            {
                callback.TryError(ErrorCode.IsNotLoggedIn);

                return;
            }

            this.coroutineRunner.Run(
                this.api.UpdateUserProfile(this.@namespace, this.session.AuthorizationToken, updateRequest, callback));
        }
    /// <summary>
    /// Obtain user profile information from the user interface.
    /// </summary>
    /// <returns> User profile request from user interfaces.</returns>
    UpdateUserProfileRequest GetUserProfileRequestFromUI()
    {
        UpdateUserProfileRequest request = new UpdateUserProfileRequest
        {
            firstName   = _inputFields.firstName.text,
            lastName    = _inputFields.lastName.text,
            dateOfBirth = _inputFields.dateOfBirth.text,
            timeZone    = _inputFields.timeZone.text,
            language    = _inputFields.language.text,
            avatarUrl   = _inputFields.avatarUrl.text
        };

        return(request);
    }
        /// <summary>
        /// Update some fields of user profile for current logged in user.
        /// </summary>
        /// <param name="updateRequest">User profile details to update user profile</param>
        /// <param name="callback">Returns a Result that contains UserProfile via callback when completed</param>
        public void UpdateUserProfile(UpdateUserProfileRequest updateRequest, ResultCallback <UserProfile> callback)
        {
            if (!this.user.IsLoggedIn)
            {
                callback.TryError(ErrorCode.IsNotLoggedIn);
                return;
            }

            this.taskDispatcher.Start(
                Task.Retry(
                    cb => this.api.UpdateUserProfile(this.@namespace, this.user.AccessToken,
                                                     updateRequest, result => cb(result)),
                    result => this.coroutineRunner.Run(() => callback((Result <UserProfile>)result)),
                    null));
        }
Exemplo n.º 25
0
        public UpdateUserProfileResponse EditUserProfile(UpdateUserProfileRequest updateUserProfileRequest)
        {
            UpdateUserProfileResponse updateUserProfileResponse = null;

            if (updateUserProfileRequest.Id == updateUserProfileRequest.UserProfile.Id)
            {
                var userprofile = _messageMapper.MapToUserProfile(updateUserProfileRequest.UserProfile);
                _userprofileRepository.UpdateUserProfile(userprofile);
                var userprofileDto = _messageMapper.MapToUserProfileDto(userprofile);

                updateUserProfileResponse = new UpdateUserProfileResponse
                {
                };
            }
            return(updateUserProfileResponse);
        }
Exemplo n.º 26
0
        public async Task <IActionResult> UpdateUser(UpdateUserProfileRequest user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userName          = User.Identity.Name;
            var userProfileEntity = Mapper.Map <UserProfileEntity>(user) with
            {
                UserName = userName
            };

            var _ = await _userProfileService.UpdateUserAsync(userProfileEntity);

            return(NoContent());
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Update([FromRoute] string userId, [FromBody] UpdateUserProfileRequest updateUserProfile)
        {
            if (userId != User.FindFirst("Id").Value)
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            _mapper.Map(updateUserProfile, userFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            return(NotFound());
        }
        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="details">The details.</param>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task <APIResponse> UpdateUserProfile(ProfileIdDetails details, UpdateUserProfileRequest request)
        {
            try
            {
                string filename   = "";
                var    folderName = Path.Combine("UserProfiles");
                var    pathToSave = Path.Combine("D:", "HappyWedding", folderName);

                if (request.ProfilePhoto.Length > 0)
                {
                    string format = System.IO.Path.GetExtension(request.ProfilePhoto.FileName);
                    filename = request.UserId + "_UserProfiles_" + DateTime.Now + format;
                    string filenme  = filename.Replace(":", ".");
                    var    filePath = Path.Combine(pathToSave, filenme);
                    using var fileStream = new FileStream(filePath, FileMode.Create);
                    request.ProfilePhoto.CopyTo(fileStream);
                    request.Photo        = filePath;
                    request.ProfilePhoto = null;
                }

                var client = httpClientFactory.CreateClient(IdentityServiceOperation.serviceName);

                var         param       = JsonConvert.SerializeObject(request);
                HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json");

                var response = await client.PutAsync(servicesConfig.Identity + IdentityServiceOperation.UpdateUser(details.ProfileId), contentPost);

                if (response.StatusCode == HttpStatusCode.NoContent)
                {
                    var user = new User {
                        Id = details.ProfileId, FirstName = request.FirstName, LastName = request.LastName
                    };
                    usernameUpdateSender.SendUserName(user);
                }

                return(JsonConvert.DeserializeObject <APIResponse>(await response.Content.ReadAsStringAsync()));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Exception in method 'UpdateUser()'");
                var exMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                return(new APIResponse(exMessage, HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 29
0
        public async Task UpdateUser_ResponseStatus_400(UpdateUserProfileRequest request)
        {
            // Arrange
            var userProfileEntity      = Mapper.Map <UserProfileEntity>(request);
            var mockUserProfileService = new Mock <IUserProfileService>();

            mockUserProfileService.Setup(x => x.UpdateUserAsync(It.IsAny <UserProfileEntity>()))
            .Returns(Task.FromResult(true));

            var userController = new UserController(Mapper, mockUserProfileService.Object, null, null);

            MockModelState(request, userController);

            // Act
            var response = await userController.UpdateUser(request);

            // Assert
            var badObjectResult = Assert.IsType <BadRequestObjectResult>(response);
        }
Exemplo n.º 30
0
        public async Task UpdateProfileAsync(int loggedUser, UpdateUserProfileRequest userProfileRequest)
        {
            var user = await _uow.UserRepository.GetAsync(loggedUser);

            if (user == null)
            {
                throw new NotFoundException(ExceptionConstants.NOT_FOUND, "User");
            }

            var existUsername = await _uow.UserRepository.FindAsync(u => u.Username == userProfileRequest.Username && u.Id != loggedUser);

            if (existUsername != null)
            {
                throw new AlreadyExistsException("Username is already in use.");
            }

            user.Username = userProfileRequest.Username;
            user.FullName = userProfileRequest.FullName;
            user.Phone    = userProfileRequest.Phone;
            _uow.UserRepository.Update(user);
            await _uow.CommitAsync();
        }