Ejemplo n.º 1
0
        //[Route("update")]
        public async Task <IActionResult> Update(string id, [FromBody] EditUserBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(id);

                if (user == null)
                {
                    return(NotFound());
                }

                // Check moderators password
                var moderator = await _userManager.FindByNameAsync(User.Identity.Name);

                var passwordCorrect = await _userManager.CheckPasswordAsync(moderator, model.Password);

                if (!passwordCorrect)
                {
                    return(BadRequest());
                }

                var result = await _userService.UpdateUserAsync(user, model);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                else
                {
                    return(BadRequest(result.Error));
                }
            }

            return(BadRequest());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> EditUser(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            var findUserToEdit = await service.FindUser(id);

            var userToEdit = new EditUserBindingModel();

            //the only props of the User that can be edited will be the EmailConfirmed,IsGlobal,IsDeleted,CompanyId
            userToEdit.Id             = findUserToEdit.Id;
            userToEdit.Username       = findUserToEdit.UserName;
            userToEdit.Email          = findUserToEdit.Email;
            userToEdit.EmailConfirmed = findUserToEdit.EmailConfirmed;
            userToEdit.CompanyId      = findUserToEdit.CompanyId;
            userToEdit.IsDeleted      = findUserToEdit.IsDelete;
            userToEdit.IsGlobal       = findUserToEdit.IsGlobal;

            IEnumerable <Company> companiesIdToSelect = service.CompaniesIdToSelect();

            ViewData["CompanyId"] = new SelectList(companiesIdToSelect, "Id", "Id", userToEdit.CompanyId);

            return(View(userToEdit));
        }
Ejemplo n.º 3
0
        public async Task <ServiceResult> UpdateUserAsync(User user, EditUserBindingModel model)
        {
            var result = new ServiceResult();

            user.Email    = model.Email;
            user.UserName = model.UserName;
            user.Age      = model.Age;
            user.Gender   = model.Gender;
            user.HomeTown = model.HomeTown;

            // add functionallity to remove filed for change mark if such a field is being modified.

            try
            {
                var res = await this.db.SaveChangesAsync();

                result.Succeeded = true;
            }
            catch (System.Exception ex)
            {
                result.Error = ex.Message;
            }

            return(result);
        }
Ejemplo n.º 4
0
        public ActionResult EditUser(EditUserBindingModel model)
        {
            if (ModelState.IsValid)
            {
                EditUserResultModel editedUser = new EditUserResultModel
                {
                    UserId   = model.UserId,
                    Username = model.Username,
                    Password = model.Password
                };

                try
                {
                    // using (HttpClient client = new HttpClient())
                    // {
                    //     var postTask = client.PostAsJsonAsync("http://localhost:52680/user/edituser/", editedUser);
                    //     postTask.Wait();
                    //
                    //     var result = postTask.Result;
                    // }

                    WebRequestManager.HttpPost("http://localhost:52680/user/edituser/", editedUser);
                }
                catch (Exception ex)
                {
                    var error = ex;
                }
            }

            return(View("~/Views/Home/Index.cshtml"));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Empty Edit for user
        /// </summary>
        /// <returns>View</returns>
        public ActionResult Edit()
        {
            User user = this.GetUser();

            if (user == default(User))
            {
                return(this.RedirectToAction("BadRequest", "Error"));
            }

            EditUserBindingModel editUser = new EditUserBindingModel()
            {
                UserNames = new UserNamesBindingModel()
                {
                    Firstname = user.Firstname,
                    Lastname  = user.Lastname,
                    Email     = user.Email
                },

                UserPassword = new PasswordBindingModel(),

                UserImage = new ImageUserBindingView(),

                UserTown = new TownUserBindingModel()
                {
                    Town    = user.Town.Name,
                    Country = user.Town.Country.Name
                }
            };

            return(this.View(editUser));
        }
        public void EditUserShouldEditUser()
        {
            var editUserInfo = new EditUserBindingModel()
            {
                Name = "edited",
                Email = "*****@*****.**",
                Gender = Gender.Male
            };

            var initialName = this.unitOfWorkMock
                .Users.All()
                .Select(u => u.Name)
                .First();

            var httpResponse =
                this.controller.EditProfileInfo(editUserInfo)
                .ExecuteAsync(new CancellationToken()).Result;

            Assert.AreEqual(HttpStatusCode.OK,
                httpResponse.StatusCode);

            var newName = this.unitOfWorkMock
                .Users.All()
                .Select(u => u.Name)
                .First();

            Assert.AreEqual("edited", newName);
        }
Ejemplo n.º 7
0
        public EditUserResultModel EditUser([FromBody] EditUserBindingModel model)
        {
            var editedUser = new EditUserResultModel();

            if (ModelState.IsValid)
            {
                editedUser.Username = model.Username;
                editedUser.Password = model.Password;
                editedUser.UserId   = model.UserId;

                try
                {
                    using (SqlConnection connection = new SqlConnection(ConnectionStrings.connectionString))
                    {
                        SqlCommand command = new SqlCommand(UserQueries.EditUser, connection);
                        command.Parameters.AddWithValue("@inUserId", editedUser.UserId);
                        command.Parameters.AddWithValue("@inUsername", editedUser.Username);
                        command.Parameters.AddWithValue("@inPassword", editedUser.Password);

                        connection.Open();

                        SqlDataReader reader = command.ExecuteReader();

                        while (reader.Read())
                        {
                            int code = (int)(reader["Code"] == DBNull.Value ? -1 : int.Parse(reader["Code"].ToString()));

                            string message = (string)(reader["Msg"] == DBNull.Value ? "" : (reader["Msg"].ToString()));

                            string username = (string)(reader["User"] == DBNull.Value ? "" : (reader["User"].ToString()));

                            string pass = (string)(reader["Password"] == DBNull.Value ? "" : (reader["Password"].ToString()));

                            int userId = (int)(reader["UserId"] == DBNull.Value ? -1 : int.Parse((reader["UserId"].ToString())));

                            editedUser = new EditUserResultModel
                            {
                                Username = username,
                                Message  = message,
                                Code     = code,
                                UserId   = userId,
                                Password = pass
                            };
                        }

                        reader.Close();
                    }
                }
                catch (Exception ex)
                {
                    var error = ex;
                }
            }


            return(editedUser);
        }
Ejemplo n.º 8
0
        public void EditUserAndSave(string id, EditUserBindingModel eubm)
        {
            var user = UserByIdEdit(id);

            user.FullName = eubm.FullName;
            user.Image    = eubm.Image;
            user.Email    = eubm.Email;
            data.Users.InsertOrUpdate(user);
            data.SaveChanges();
        }
 public ActionResult Edit([Bind(Include = "Id, Name, Email, PasswordHash, PhoneNumber, DateAdded, UserName")] EditUserBindingModel bind)
 {
     if (ModelState.IsValid)
     {
         var registeredUser = Mapper.Map <EditUserBindingModel, RegisteredUser>(bind);
         db.Entry(registeredUser).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(bind));
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> EditUser(EditUserBindingModel model)
        {
            if (ModelState.IsValid)
            {
                await service.EditUser(model);

                return(RedirectToAction("DisplayAllUsers"));
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 11
0
        public bool EditUser(EditUserBindingModel model)
        {
            var userFromDb = this.db.Users.SingleOrDefault(x => x.Id == model.Id);

            userFromDb.UserName = model.Username;
            userFromDb.Name     = model.Name;
            userFromDb.Password = model.Password;

            db.Update(userFromDb);

            int result = this.db.SaveChanges();

            return(result > 0);
        }
Ejemplo n.º 12
0
        public async Task EditUser(EditUserBindingModel model)
        {
            var editUser = await FindUser(model.Id);

            if (editUser == null)
            {
                throw new NullReferenceException();
            }
            editUser.UserName  = model.Username;
            editUser.CompanyId = model.CompanyId;
            editUser.IsDelete  = model.IsDeleted;
            editUser.IsGlobal  = model.IsGlobal;

            dbContext.Update(editUser);
            await dbContext.SaveChangesAsync();
        }
Ejemplo n.º 13
0
        public async void UpdateUser(UserInfo user, EditUserBindingModel editUser)
        {
            if (editUser != null)
            {
                UserRecord userToUpdate = await FirebaseAuth.DefaultInstance
                                          .GetUserByEmailAsync(user.Email);

                UserRecordArgs newUserData = new UserRecordArgs()
                {
                    DisplayName = editUser.Username,
                    Password    = editUser.Password
                };

                await FirebaseAuth.DefaultInstance.UpdateUserAsync(newUserData);
            }
        }
Ejemplo n.º 14
0
        public async Task <IHttpActionResult> UpdateUser(EditUserBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await this.AppUserManager.FindByIdAsync(model.Id);

            user.Email    = model.Email;
            user.Name     = model.Name;
            user.UserName = model.Username;

            await this.AppUserManager.UpdateAsync(user);

            return(Ok());
        }
Ejemplo n.º 15
0
        public IHttpActionResult EditProfileInfo(EditUserBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            // Validate the current user exists in the database
            var currentUserId = this.provider.GetUserId();
            var currentUser = this.data.Users.All()
                .FirstOrDefault(u => u.Id == currentUserId);
            if (currentUser == null)
            {
                return this.BadRequest("Invalid user token.");
            }

            var emailHolder = this.data.Users.All()
                .FirstOrDefault(u => u.Email == model.Email);
            if (emailHolder != null && emailHolder.Id != currentUserId)
            {
                return this.BadRequest("Email is already taken.");
            }

            if (!this.ValidateImageSize(model.ProfileImage, ProfileImageKbLimit))
            {
                return this.BadRequest(string.Format("Profile image size should be less than {0}kb.", ProfileImageKbLimit));
            }

            currentUser.Name = model.Name;
            currentUser.Email = model.Email;
            currentUser.Gender = model.Gender;
            currentUser.ProfileImage = model.ProfileImage;

            this.data.SaveChanges();

            return this.Ok(new
            {
                message = "User profile edited successfully."
            });
        }
Ejemplo n.º 16
0
        public async Task <IHttpActionResult> PutUser(string Id, EditUserBindingModel user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Only SuperAdmin or Admin can delete users (Later when implement roles)
            var appUser = await this.AppUserManager.FindByIdAsync(Id);

            if (appUser == null)
            {
                return(NotFound());
            }

            if (appUser != null)
            {
                appUser.UserName = user.UserName;

                appUser.Email = user.Email;

                appUser.FirstName = user.FirstName;

                appUser.LastName = user.LastName;

                appUser.PhoneNumber = user.PhoneNumber;

                appUser.Latitude = user.Latitude;

                appUser.Longitude = user.Longitude;

                //appUser.Roles = user.Roles;

                //var currentRoles = await this.AppUserManager.GetRolesAsync(appUser.Id);

                //var rolesNotExists = rolesToAssign.Except(this.AppRoleManager.Roles.Select(x => x.Name)).ToArray();

                //if (rolesNotExists.Count() > 0)
                //{

                //    ModelState.AddModelError("", string.Format("Roles '{0}' does not exixts in the system", string.Join(",", rolesNotExists)));
                //    return BadRequest(ModelState);
                //}

                //IdentityResult removeResult = await this.AppUserManager.RemoveFromRolesAsync(appUser.Id, currentRoles.ToArray());

                //if (!removeResult.Succeeded)
                //{
                //    ModelState.AddModelError("", "Failed to remove user roles");
                //    return BadRequest(ModelState);
                //}

                //IdentityResult addResult = await this.AppUserManager.AddToRolesAsync(appUser.Id, rolesToAssign);

                //if (!addResult.Succeeded)
                //{
                //    ModelState.AddModelError("", "Failed to add user roles");
                //    return BadRequest(ModelState);
                //}

                IdentityResult result = await this.AppUserManager.UpdateAsync(appUser);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }

                return(Ok(appUser));
            }

            return(NotFound());
        }
Ejemplo n.º 17
0
 public ActionResult EditUserSave(string id, EditUserBindingModel eubm)
 {
     NavbarInfo();
     this.adminUserService.EditUserAndSave(id, eubm);
     return(RedirectToAction("Users", "Admin"));
 }
        public IHttpActionResult EditProfile(EditUserBindingModel model)
        {
            var loggedUserId = this.User.Identity.GetUserId();
            var loggedUser = this.TwitterData.Users.Find(loggedUserId);
            if (loggedUser == null)
            {
                return this.BadRequest("Invalid session token.");
            }

            if (model == null)
            {
                return this.BadRequest("Model is empty");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var emailHolder = this.TwitterData.Users.All()
                .FirstOrDefault(u => u.Email == model.Email);

            if (emailHolder != null && emailHolder.Id != loggedUserId)
            {
                return this.BadRequest("Email is already taken.");
            }

            if (!this.ValidateImageSize(model.ProfileImageData, ProfileImageKilobyteLimit))
            {
                return this.BadRequest(string.Format("Profile image size should be less than {0}kb.", ProfileImageKilobyteLimit));
            }

            if (!this.ValidateImageSize(model.CoverImageData, CoverImageKilobyteLimit))
            {
                return this.BadRequest(string.Format("Cover image size should be less than {0}kb.", CoverImageKilobyteLimit));
            }

            loggedUser.Fullname = model.Fullname;
            loggedUser.Email = model.Email;
            loggedUser.Gender = model.Gender;

            if (model.ProfileImageData != null && model.ProfileImageData.IndexOf(',') == -1)
            {
                model.ProfileImageData = string.Format("{0}{1}", "data:image/jpg;base64,", model.ProfileImageData);
            }

            loggedUser.ProfileImageData = model.ProfileImageData;

            try
            {
                string source = model.ProfileImageData;
                if (source != null)
                {
                    string base64 = source.Substring(source.IndexOf(',') + 1);
                    loggedUser.ProfileImageDataMinified = string.Format("{0}{1}",
                        "data:image/jpg;base64,", ImageUtility.Resize(base64, 100, 100));
                }
                else
                {
                    loggedUser.ProfileImageDataMinified = null;
                }
            }
            catch (FormatException)
            {
                return this.BadRequest("Invalid Base64 string format.");
            }

            if (model.CoverImageData != null && model.CoverImageData.IndexOf(',') == -1)
            {
                model.CoverImageData = string.Format("{0}{1}", "data:image/jpg;base64,", model.CoverImageData);
            }

            loggedUser.CoverImageData = model.CoverImageData;

            this.TwitterData.SaveChanges();

            return this.Ok(new
            {
                message = "User profile edited successfully."
            });
        }
        public IHttpActionResult EditProfile(EditUserBindingModel model)
        {
            var loggedUserId = this.User.Identity.GetUserId();
            var loggedUser   = this.TwitterData.Users.Find(loggedUserId);

            if (loggedUser == null)
            {
                return(this.BadRequest("Invalid session token."));
            }

            if (model == null)
            {
                return(this.BadRequest("Model is empty"));
            }

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var emailHolder = this.TwitterData.Users.All()
                              .FirstOrDefault(u => u.Email == model.Email);

            if (emailHolder != null && emailHolder.Id != loggedUserId)
            {
                return(this.BadRequest("Email is already taken."));
            }

            if (!this.ValidateImageSize(model.ProfileImageData, ProfileImageKilobyteLimit))
            {
                return(this.BadRequest(string.Format("Profile image size should be less than {0}kb.", ProfileImageKilobyteLimit)));
            }

            if (!this.ValidateImageSize(model.CoverImageData, CoverImageKilobyteLimit))
            {
                return(this.BadRequest(string.Format("Cover image size should be less than {0}kb.", CoverImageKilobyteLimit)));
            }

            loggedUser.Fullname = model.Fullname;
            loggedUser.Email    = model.Email;
            loggedUser.Gender   = model.Gender;

            if (model.ProfileImageData != null && model.ProfileImageData.IndexOf(',') == -1)
            {
                model.ProfileImageData = string.Format("{0}{1}", "data:image/jpg;base64,", model.ProfileImageData);
            }

            loggedUser.ProfileImageData = model.ProfileImageData;

            try
            {
                string source = model.ProfileImageData;
                if (source != null)
                {
                    string base64 = source.Substring(source.IndexOf(',') + 1);
                    loggedUser.ProfileImageDataMinified = string.Format("{0}{1}",
                                                                        "data:image/jpg;base64,", ImageUtility.Resize(base64, 100, 100));
                }
                else
                {
                    loggedUser.ProfileImageDataMinified = null;
                }
            }
            catch (FormatException)
            {
                return(this.BadRequest("Invalid Base64 string format."));
            }

            if (model.CoverImageData != null && model.CoverImageData.IndexOf(',') == -1)
            {
                model.CoverImageData = string.Format("{0}{1}", "data:image/jpg;base64,", model.CoverImageData);
            }

            loggedUser.CoverImageData = model.CoverImageData;

            this.TwitterData.SaveChanges();

            return(this.Ok(new
            {
                message = "User profile edited successfully."
            }));
        }