Example #1
0
        public byte[] Execute(out CommandError error)
        {
            var client = ClientManager.GetClient(requestData.UserToken);

            if (client.Role != UserRoles.Admin)
            {
                error = CommandError.NoPermissions;
                return(null);
            }

            var    editData       = EditUserData.FromJson(SequrityUtils.DecryptString(requestData.Data, client.SecretDFKey));
            string password       = "";
            bool   changePassword = false;

            if (editData.Password != null)
            {
                password       = SequrityUtils.GetHash(editData.Password);
                changePassword = true;
            }

            UserRoles role;
            var       DBReader = DBConnection.PrepareExecProcedureCommand("GetUserRole", editData.id.ToString()).ExecuteReader();

            if (DBReader.Read())
            {
                role = (UserRoles)DBReader.GetInt32(0) - 1;
            }
            else
            {
                error = CommandError.ClientNotFound;
                return(null);
            }
            DBReader.Close();

            int  studentGroup = -1;
            bool changeGroup  = false;

            if (role == UserRoles.Student)
            {
                changeGroup = true;
                DBReader    = DBConnection.PrepareExecProcedureCommand("GetStudentGroup", editData.Group).ExecuteReader();

                if (DBReader.Read())
                {
                    studentGroup = DBReader.GetInt32(0);
                    DBReader.Close();
                }
                else
                {
                    DBReader.Close();
                    error = CommandError.BadStudentGroup;
                    return(null);
                }
            }

            DBConnection.PrepareExecProcedureCommand("EditUser", editData.id.ToString(), editData.Firstname, editData.Lastname, password, studentGroup.ToString(), Convert.ToInt32(changePassword).ToString(), Convert.ToInt32(changeGroup).ToString()).ExecuteNonQuery();

            error = CommandError.None;
            return(SequrityUtils.Encrypt("OK", client.SecretDFKey));
        }
Example #2
0
        private void Edit()
        {
            EditUserData edit = new EditUserData
                                    (ActiveUser.c_Id, txtUserNameEdit.Text, txtFirstNameEdit.Text, txtLastNameEdit.Text,
                                    txtEmailEdit.Text, ActiveUser.c_Position, txtPasswordEdit.Text, txtPasswordConfEdit.Text);

            edit.EditUser();
        }
Example #3
0
        public async Task <ActionResult> Edit(EditUserViewModel userData)
        {
            if (ModelState.IsValid)
            {
                byte[] avatar = null;
                if (Request.Files.Count > 0 &&
                    (Request.Files[0].ContentType == System.Net.Mime.MediaTypeNames.Image.Gif ||
                     Request.Files[0].ContentType == System.Net.Mime.MediaTypeNames.Image.Jpeg))
                {
                    avatar = FileUploader.UploadFile(Request.Files[0]); //Convert uploaded file to byte array
                }

                UserInfo oldUserData = await UserService.GetByIdAsync(userData.Id);

                EditUserData userDto = new EditUserData()
                {
                    Id          = userData.Id,
                    UserName    = userData.UserName,
                    Email       = userData.Email,
                    Roles       = userData.Roles.Where(r => r.Checked).Select(r => r.Name),
                    Avatar      = avatar,
                    Gender      = userData.Gender,
                    NewPassword = userData.NewPassword
                };

                var result = await UserService.EditAsync(userDto);

                if (result.Succedeed)
                {
                    UserInfo user = await UserService.GetByNameAsync(userDto.UserName);

                    if (!user.EmailConfirmed)
                    {
                        await UserService.SendVerificationEmailAsync(user.Id, Url.Action("ConfirmEmail", "Account", new { area = "" }));
                    }

                    if (!string.IsNullOrEmpty(userData.NewPassword) && User.Identity.Name == oldUserData.UserName)
                    {
                        return(RedirectToRoute(new { area = "", controller = "Account", action = "Logout" }));
                    }
                    return(RedirectToRoute(new { area = "Admin", controller = "Account", action = "List" }));
                }
                ModelState.AddModelError("", result.Message);
            }
            return(View(userData));
        }
Example #4
0
        public async Task <ActionResult> Settings(ProfileSettingsViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserInfo user = await UserService.GetByNameAsync(User.Identity.Name);

                if (user == null)
                {
                    return(HttpNotFound("User not found!"));
                }

                if (await UserService.CheckPasswordAsync(user.Id, model.OldPassword))
                {
                    if (Request.Files.Count > 0)//if avatar was uploaded
                    {
                        //TODO: check if file is image type
                        if (!Request.Files[0].ContentType.Contains("image/"))
                        {
                            ModelState.AddModelError("Avatar", "Wrong file type!");
                        }
                        else
                        {
                            model.Avatar = FileUploader.UploadFile(Request.Files[0]); //transform image to byte array
                        }
                    }

                    var userData = new EditUserData()
                    {
                        Id          = user.Id,
                        Email       = model.Email,
                        NewPassword = model.NewPassword,
                        Gender      = model.Gender,
                        Avatar      = model.Avatar
                    };
                    await UserService.EditAsync(userData);
                }
                else
                {
                    ModelState.AddModelError("OldPassword", "Wrong password");
                }
            }
            return(View(model));
        }
Example #5
0
        /// <summary>
        /// Method for edit user data in database
        /// </summary>
        /// <param name="userData">Data that must be updated in database</param>
        /// <returns></returns>
        public async Task <OperationDetails> EditAsync(EditUserData userData)
        {
            //TODO: Add transaction for this action
            IdentityResult result = null;

            UserAccount account = await repo.AccountManager.FindByIdAsync(userData.Id);       //get from database user account by id

            var profile = repo.Profiles.Get(userData.Id);                                     //get from database user profile by id

            if (account != null && profile != null)                                           //if user exists
            {
                if (account.Email != userData.Email && !string.IsNullOrEmpty(userData.Email)) //if email was changed
                {
                    if (repo.AccountManager.FindByEmail(userData.Email) != null)
                    {
                        return(new OperationDetails(false, "User with this email address is already exists"));
                    }
                    account.Email          = userData.Email; //set new email for account
                    account.EmailConfirmed = false;
                }

                if (!string.IsNullOrEmpty(userData.UserName)) //if username was changed
                {
                    account.UserName = userData.UserName;     //set new name for user
                }

                profile.Gender = (Model.Enums.Gender)userData.Gender; //set new gender for user
                if (userData.Avatar != null)
                {
                    profile.Avatar = userData.Avatar; //set new avatar
                }

                repo.Profiles.Update(profile);                           //update profile information for current user
                await repo.SaveChangesAsync();                           //apply changes to profile

                result = await repo.AccountManager.UpdateAsync(account); //apply changes to account information for current user

                if (!result.Succeeded)
                {
                    return(new OperationDetails(false, "Can`t save changes to database"));
                }

                if (!string.IsNullOrEmpty(userData.NewPassword))                                           //if password was changed
                {
                    result = await repo.AccountManager.ChangePasswordAsync(account, userData.NewPassword); //try to change password for account

                    if (!result.Succeeded)
                    {
                        return(new OperationDetails(false, $"Can`t change password"));
                    }
                }

                if (userData.Roles != null)                                                       //if roles was changed
                {
                    foreach (string role in repo.RoleManager.Roles.Select(r => r.Name).ToArray()) //remove all roles for user
                    {
                        repo.AccountManager.RemoveFromRole(userData.Id, role);
                    }

                    foreach (string role in userData.Roles)                                      //for each role added roles
                    {
                        if (await repo.RoleManager.RoleExistsAsync(role))                        //if role is exists
                        {
                            result = await repo.AccountManager.AddToRoleAsync(account.Id, role); //add current user to role

                            if (!result.Succeeded)
                            {
                                return(new OperationDetails(false, $"Can`t add role \"{role}\" to {userData.UserName}"));
                            }
                        }
                        else
                        {
                            return(new OperationDetails(false, $"Can`t add role \"{role}\" to {userData.UserName}, because this role doesn't exist in database"));
                        }
                    }
                }
                return(new OperationDetails(true, "User information was updated"));
            }
            return(new OperationDetails(false, "Can`t find user with this id!"));
        }
        /// <summary>
        /// Edit an user
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public EditUserData EditUser(UserProfile user)
        {
            // test user
            if (user == null)
            {
                return(null);
            }

            EditUserData result = new EditUserData();

            // Test insert or update
            if (user.Id == 0)
            {
                result.MailChanged        = true;
                user.EmailValidate        = false;
                user.EmailValidationToken = Guid.NewGuid();

                // Insert
                _context.Users.Add(user);
            }
            else
            {
                // Get current mail to know if it was changed
                String email = _context.Users.Where(c => c.Id == user.Id)
                               .Select(c => c.Email)
                               .FirstOrDefault();
                result.MailChanged = String.Compare(email, user.Email, StringComparison.InvariantCultureIgnoreCase) != 0;

                // Attach data for update
                _context.Users.Attach(user);
                // Get entry
                var entry = _context.Entry(user);
                entry.State = EntityState.Unchanged;
                entry.Property(c => c.Name).IsModified  = true;
                entry.Property(c => c.Email).IsModified = true;

                // Test if mail changed
                if (result.MailChanged)
                {
                    user.EmailValidate        = false;
                    user.EmailValidationToken = Guid.NewGuid();

                    entry.Property(c => c.EmailValidate).IsModified        = true;
                    entry.Property(c => c.EmailValidationToken).IsModified = true;
                }
            }


            // Save
            if (_context.SaveChanges() <= 0)
            {
                return(null);
            }
            if (String.IsNullOrWhiteSpace(user.Email))
            {
                // impossible to have to send email because this user have none email addresse
                result.MailChanged = false;
            }

            // Result is ok
            result.Result = true;
            return(result);

            // TODO : If mail changed, send validation mail
            //  SendValidationMail(user.Id, user.Name, user.Email, user.EmailValidationToken);
        }