public async Task Can_update_user_metadata() { // Add a new user with metadata var newUserRequest = new UserCreateRequest { Connection = _connection.Name, Email = $"{Guid.NewGuid():N}@nonexistingdomain.aaa", EmailVerified = true, Password = Password, AppMetadata = new { a = 1, b = 2 }, UserMetadata = new { c = 3, d = 4, Color = "red" } }; var newUserResponse = await _apiClient.Users.CreateAsync(newUserRequest); Assert.Equal(newUserResponse.UserMetadata.Color.ToString(), "red"); // Do some updating var updateUserRequest = new UserUpdateRequest { AppMetadata = new ExpandoObject(), UserMetadata = new ExpandoObject() }; updateUserRequest.AppMetadata.IsSubscribedTo = "1"; updateUserRequest.UserMetadata.Color = null; await _apiClient.Users.UpdateAsync(newUserResponse.UserId, updateUserRequest); // Get the user to ensure the metadata was set var user = await _apiClient.Users.GetAsync(newUserResponse.UserId); Assert.Equal(user.AppMetadata.IsSubscribedTo.ToString(), "1"); Assert.Null(user.UserMetadata.Color); // Delete the user await _apiClient.Users.DeleteAsync(user.UserId); }
public async Task <HttpResponseMessage> UpdateAsync(int entityId, UserUpdateRequest request) { var user = await unitOfWork.UserToReplyRepository.GetByIDAsync(entityId); if (user == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } user.Email = request.Email; user.SendEmail = request.SendEmail; user.IsActive = request.IsActive; unitOfWork.UserToReplyRepository.Update(user); await unitOfWork.SaveChangesAsync(); return(new HttpResponseMessage(HttpStatusCode.OK)); }
public async Task <IActionResult> Edit(UserUpdateRequest request) { if (!ModelState.IsValid) { return(View()); } var result = await _userApiClient.UpdateUser(request.Id, request); if (result.IsSuccessed) { //TempData["result"] = "Cập nhập tài khoản quản trị thành công"; _notyf.Success("Cập nhập tài khoản quản trị thành công"); return(RedirectToAction("Index")); } ModelState.AddModelError("", result.Message);//key and message return(View(request)); }
public async Task <IActionResult> Update([FromBody] UserUpdateRequest model) { try { var result = await _personDataService.UpdateUserAsync(model); if (result > 0) { return(Ok(result)); } } catch (Exception ex) { return(BadRequest(new { message = ex.Message })); } return(BadRequest()); }
public UserGetRequest Update(int id, UserUpdateRequest obj) { var entity = _context.User.Find(id); if (obj != null) { entity.Username = obj.Username; entity.Name = obj.Name; entity.PhoneNumber = obj.PhoneNumber; entity.Surname = obj.Surname; entity.Email = obj.Email; entity.Image = obj.Image; entity.Status = obj.Status; _context.SaveChanges(); return(_mapper.Map <UserGetRequest>(entity)); } return(null); }
public async Task <IActionResult> UpdateUserData([FromBody] UserUpdateRequest userUpdateRequest) { try { return(await customersRepository.Update(userUpdateRequest)); } catch (ArgumentException e) { return(BadRequest(new Dictionary <string, string[]> { { e.ParamName, new [] { e.Message.Split(Environment.NewLine)[0] } } })); } catch (Exception e) { return(StatusCode(500, e)); } }
public static UserUpdateDto ToUserUpdateDto(UserUpdateRequest request, CurrentUserDto currentUser) { var dto = new UserUpdateDto { Id = request.Id, Account = request.Account.Trim(), Name = request.Name.Trim(), Deptid = request.Deptid, Birthday = request.Birthday, Email = request.Email, Phone = request.Phone, Sex = request.Sex, Status = request.Status ? AccountStatus.Active : AccountStatus.InActive, ModifyBy = currentUser.Id }; return(dto); }
public async Task <IActionResult> Edit(UserUpdateRequest request) { if (!ModelState.IsValid) { return(View()); } var result = await _userApiClient.UpdateUser(request.Id, request); if (result.IsSuccessed) { TempData["result"] = "Cập nhật người dùng thành công"; return(RedirectToAction("Index")); } ModelState.AddModelError("", result.Message); return(View(request)); }
public async Task <ActionResult> UpdateAsync([FromForm] UserUpdateRequest request) { if (!ModelState.IsValid) { return(BadRequest(new ErrorResponse { Error = ModelState.GetErrorMessages(), Status = false })); } UserStatusResponse response = await usersService.UpdateAsync(request); if (response.Status) { return(Ok(mapper.Map <User, UserResponse>(response.Resource))); } return(BadRequest(new ErrorResponse { Error = response.Message, Status = response.Status })); }
public async Task <bool> SetUserLocalId(string authId, string localId) { string apiToken = ApplicationConfiguration.Configuration["auth0:managementApiToken"]; string apiEndpoint = ApplicationConfiguration.Configuration["auth0:domain"]; ManagementApiClient _client = new ManagementApiClient(apiToken, apiEndpoint); UserUpdateRequest request = new UserUpdateRequest(); request.AppMetadata = new ExpandoObject(); request.AppMetadata.neteoc_id = localId; User user = await _client.Users.UpdateAsync(authId, request); return(true); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, model.Role.ToString()); UserUpdateRequest uur = new UserUpdateRequest(); uur.emailId = model.Email; uur.firstName = model.FirstName; uur.lastName = model.LastName; uur.GTID = model.GTID; UserCommunicator uc = new UserCommunicator((GT.BuddyUp.DomainModel.IUser)UnityConfig.Container.Resolve(typeof(GT.BuddyUp.DomainModel.IUser), "User")); if (uc.UpdateUser(uur)) { //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); //return RedirectToAction("Index", "Home"); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; return(View("Info")); } } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult <int> > Put(int UserId, [FromBody] UserUpdateRequest Request) { var user = await _context .Users .Include(ur => ur.UserRoles) .AsNoTracking() .FirstOrDefaultAsync(u => u.UserId == UserId); if (user != null) { if (_claimsPrincipal.SubjectId().Equals(user.Username, StringComparison.OrdinalIgnoreCase) || _claimsPrincipal.IsInRole("admin")) { var newUser = user with { Firstname = Request.Firstname, Lastname = Request.Lastname, }; _context.Users.Update(newUser); if (Request.Roles != null && _claimsPrincipal.IsInRole("admin")) { _context.UserRoles.RemoveRange(user.UserRoles); await _context.UserRoles.AddRangeAsync( _context .Roles .Where(role => Request.Roles.Contains(role.Name)) .Select(role => new UserRole { RoleId = role.RoleId, UserId = user.UserId, }) .ToList()); } await _context.SaveChangesAsync(); return(new OkResult()); } return(new ForbidResult()); } return(new BadRequestResult()); }
public async Task <ActionResult> UpdateUser([FromBody] UserUpdateRequest request) { var user = new UserDetailed { UserName = UserName, FirstName = request.FirstName, LastName = request.LastName, Email = request.Email, Topics = request.Topics, Introduction = request.Introduction, }; var ret = await userService.UpdateUser(user); if (ret == null) { return(NotFound()); } return(Ok()); }
/** * Update an existing NPrinting user */ public void UpdateNpUser(UserResponseDataItem npUser, Model.User adUser) { var userId = npUser.Id.ToString(); //There may be changes to the user details in Active Directory UserUpdateRequest userUpdReq = new UserUpdateRequest( adUser.Email, Convert.ToBase64String(Guid.NewGuid().ToByteArray()), true, adUser.Username, adUser.Domainaccount ?? "", npUser.Timezone, npUser.Locale, npUser.Folder ?? "", npUser.Subfolder ?? ""); //Update the user details in case of any changes _usersApi.UsersIdPut(userId, userUpdReq); }
public ActionResult <SuccessResponse> UpdateUser(UserUpdateRequest model) { int code = 200; BaseResponse response = null; try { _service.UpdateUser(model); response = new SuccessResponse(); } catch (Exception ex) { code = 500; response = new ErrorResponse(ex.Message); } return(StatusCode(code, response)); }
public async Task <IActionResult> Update([FromBody] UserUpdateRequest request) { var user = await HttpContext.GetCurrentUserAsync(_userManager); var updateResponse = await _identityService.UpdateAsync(user, request); if (!updateResponse.Success) { return(BadRequest(new AuthFailedResponse { Errors = updateResponse.Errors })); } return(Ok(new { user.Email })); }
public async Task <IActionResult> Edit(Guid id) { var result = await _userApiClient.GetUser(id); if (result.IsSuccessed) { var userVm = result.ResultObj; var userUpdateRequest = new UserUpdateRequest() { FirstName = userVm.FirstName, LastName = userVm.LastName, Email = userVm.Email, PhoneNumber = userVm.PhoneNumber, Id = id }; return(View(userUpdateRequest)); } return(RedirectToAction("Error", "Home")); }
public async Task <IHttpActionResult> Update(int id, [FromBody] UserUpdateRequest data) { try { User user = await _userRepository.Update(id, data.GetObject()); if (user == null) { return(new HttpJsonApiResult <string>("Not Found", Request, HttpStatusCode.NotFound)); } return(new HttpJsonApiResult <UserModel>( new UserModel(user), Request, HttpStatusCode.OK)); } catch (Exception) { return(new HttpJsonApiResult <string>( "Internal Server Error", Request, HttpStatusCode.InternalServerError)); } }
public async Task <bool> Update(string id, UserUpdateRequest request) { var user = await userManager.FindByIdAsync(id.ToString()); user.DoB = request.DoB; user.FullName = request.FullName; user.Facebook = request.Facebook; user.PhoneNumber = request.PhoneNumber; user.Gender = request.Gender; user.ImagePath = request.ImagePath; var result = await userManager.UpdateAsync(user); if (result.Succeeded) { return(true); } return(false); }
public async Task <IActionResult> Edit(UserUpdateRequest request) { if (!ModelState.IsValid) { return(View()); } var result = await _userApiClient.UpdateUser(request.Id, request); if (result.IsSuccessed) { // khi thành công ta có thể tạo một TempData đây là đầu đi và sẽ có đầu nhận dữ liệu này nhe bên View Của nó TempData["result"] = "Sửa Thành Công"; //có key là result return(RedirectToAction("Index")); } ModelState.AddModelError("", result.Message); // đây là lỗi của Model này return(View(request)); }
public async Task <User> Update(int id, UserUpdateRequest request) { var fullUrl = _apiUrl + "/" + id; try { var result = await fullUrl.PutJsonAsync(request).ReceiveJson <User>(); return(result); } catch (FlurlHttpException ex) { var error = await GetErrorMessage(ex); await Application.Current.MainPage.DisplayAlert(Constants.Error, error, Constants.OK); return(default(User)); } }
public async Task <ActionResult <UserResponse> > Put(int id, UserUpdateRequest request) { if (!User.IsInRole(Role.Admin) && User.Claims.Single(x => x.Type == "Id").Value != id.ToString()) { return(Forbid("Only admin can change other users data.")); } var updateResponse = await _userService.Update(id, request); if (!updateResponse.Success) { if (!updateResponse.Found) { return(NotFound(updateResponse.Errors)); } return(BadRequest(updateResponse.Errors)); } return(updateResponse.Object); }
public async Task <ApiResult <bool> > Update(int id, UserUpdateRequest request) { if (await _userManager.Users.AnyAsync(x => x.Email == request.Email && x.Id != id)) { return(new ApiErrorResult <bool>("Emai đã tồn tại")); } var user = await _userManager.FindByIdAsync(id.ToString()); user.Email = request.Email; user.PhoneNumber = request.PhoneNumber; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { return(new ApiSuccessResult <bool>()); } return(new ApiErrorResult <bool>("Cập nhật không thành công")); }
public void UpdateUser(UserUpdateRequest editedUser) { if (editedUser.OldPassword != null) { if (editedUser.NewPassword != null) { UpdatePassword(editedUser.OldPassword, editedUser.NewPassword); } else { throw new BadRequestException("Invalid values"); } } else { this.FullName = editedUser.FullName ?? this.FullName; this.Email = editedUser.Email ?? this.Email; } }
public async Task<IActionResult> Edit(Guid id) { var result = await _userApiClient.GetById(id); if (result.IsSuccessed) { var user = result.ResultObj; var updateRequest = new UserUpdateRequest() { birthday = user.birthday, Email = user.Email, firstName = user.FirstName, lastName = user.LastName, PhoneNumber = user.PhoneNumber, Id = id }; return View(updateRequest); } return RedirectToAction("Error", "Home"); }
public async Task <User> UpdateUserAsync(User user, string token, CancellationToken cancellationToken = default) { var updateUserRequest = new UserUpdateRequest { User = user }; var requestBody = JsonSerializer.Serialize(updateUserRequest, _jsonSerializerOptions); var httpRequest = new HttpRequestMessage(HttpMethod.Put, new Uri($"api/user", UriKind.Relative)) { Content = new StringContent(requestBody, Encoding.UTF8, "application/json") }; httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("Authorization", $"Token {token}"); var response = await HandleRequest <UserResponse>(httpRequest, cancellationToken); return(response.User); }
public async Task <Response> Update(int userId, UserUpdateRequest request) { var response = new Response(); var user = await userRepository.SingleOrDefaultAsync(u => u.Id == userId, u => u.UserRoles, ur => ur.Role); if (user == null) { response = new Response(new[] { "User with this id does not exist " }); } if (response.Success && request.Email != user.Email) { var existing = await userManager.FindByEmailAsync(request.Email); if (existing != null) { response = new Response(new[] { "User with such an email already exists " }); } } if (response.Success) { var currRole = user.UserRoles.Select(ur => ur.Role.Name).FirstOrDefault(); if (currRole != request.Role) { await userManager.RemoveFromRoleAsync(user, currRole); await userManager.AddToRoleAsync(user, request.Role); } user.FirstName = request.FirstName; user.LastName = request.LastName; user.Email = request.Email; user.UserName = request.Email; await userManager.UpdateAsync(user); } return(response); }
internal void UpdateUser(UserUpdateRequest UserUpdateRequest) { logger.Debug("Recived update user request"); try { UserUpdateRequest.email = Decryptor.Decrypt(UserUpdateRequest.email); if (String.IsNullOrEmpty(UserUpdateRequest.email)) { logger.Error("User update required user email"); throw new CustomException("User update required user email", (int)ErrorCode.VALIDATIONFAILED); } CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (currentUser.userId >= 0) { logger.Error("User is not found on the session"); throw new CustomException("User is not found on the session", (int)ErrorCode.UNAUTHORIZED); } using (var ctx = new PetWhizzEntities()) { user User = ctx.users.Where(a => a.id == currentUser.userId).FirstOrDefault(); ctx.users.Attach(User); User.addressLine1 = UserUpdateRequest.addressLine1; User.addressLine2 = UserUpdateRequest.addressLine2; User.dateOfBirth = UserUpdateRequest.dateOfBirth; User.eMail = UserUpdateRequest.email; User.firstName = UserUpdateRequest.firstName; User.lastName = UserUpdateRequest.lastName; User.lastUpdatedDate = DateTime.Now; User.middleName = UserUpdateRequest.middleName; User.mobileNumber = UserUpdateRequest.mobileNumber; User.profilePic = UserUpdateRequest.profilePic; ctx.SaveChanges(); } logger.Debug("Successfully updated user - " + currentUser.userId); } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); throw; } }
public async Task <IActionResult> Edit(Guid id) { var result = await _userApiClient.GetById(id); if (result.IsSuccessed) { var user = result.ResultObj; var updateRequest = new UserUpdateRequest() { Dob = user.Dob, Email = user.Email, FirstName = user.FirstName, Id = user.Id, LastName = user.LastName, PhoneNumber = user.PhoneNumber }; return(View(updateRequest)); } return(RedirectToAction("Error", "Home")); }
public async Task <IActionResult> UserUpdate([FromBody] UserUpdateRequest request) { try { var result = await UserService.Update(request); if (result.Status) { return(Ok(result)); } return(BadRequest(result)); } catch (Exception ex) { Logger.LogError(ex, ex.Message); return(BadRequest(ex.Message)); } }
public void Usuario_ChangePIS() { UserUpdateRequest uur = new UserUpdateRequest(); uur.Usuario[0].PIS = 108; uur.Usuario[0].PIS2 = 223344; uur.Usuario[0].Nome = "Teste Change PIS (com template)"; StatusResult st = (StatusResult)RestJSON.SendJson(rep.IP, uur, typeof(StatusResult), rep.iDClassSession); if (!st.isOK) Assert.Inconclusive(st.Status); }
public void Update(UserUpdateRequest model, string userId) { int uid = 0; DataProvider.ExecuteNonQuery(GetConnection, "dbo.Users_Update_v2" , inputParamMapper: delegate (SqlParameterCollection paramCollection) { paramCollection.AddWithValue("@FirstName", model.FirstName); paramCollection.AddWithValue("@LastName", model.LastName); paramCollection.AddWithValue("@Email", model.Email); paramCollection.AddWithValue("@Phone", model.Phone); //paramCollection.AddWithValue("@Zip", model.Zip); paramCollection.AddWithValue("@Gender", model.Gender); paramCollection.AddWithValue("@Age", model.Age); //paramCollection.AddWithValue("@HasKids", model.HasKids); //paramCollection.AddWithValue("@CollegeStudent", model.CollegeStudent); paramCollection.AddWithValue("@MaritalStatus", model.MaritalStatus); //paramCollection.AddWithValue("@SharesFinances", model.SharesFinances); //paramCollection.AddWithValue("@EmploymentStatus", model.EmploymentStatus); paramCollection.AddWithValue("@Income", model.Income); //paramCollection.AddWithValue("@Expenses", model.Expenses); //paramCollection.AddWithValue("@CreditCardDebt", model.CreditCardDebt); //paramCollection.AddWithValue("@StudentLoanDebt", model.StudentLoanDebt); //paramCollection.AddWithValue("@Savings", model.Savings); //paramCollection.AddWithValue("@HomeStatus", model.HomeStatus); //paramCollection.AddWithValue("@FinancialConcern", model.FinancialConcern); paramCollection.AddWithValue("@UserId", userId); paramCollection.AddWithValue("@Id", model.Id); } , returnParameters: delegate (SqlParameterCollection param) { int.TryParse(param["@Id"].Value.ToString(), out uid); } ); }