Edit an user account.
978587
def acp_users_edit():
    """"""
    global current_user
    if not current_user.is_admin:
        return error("Not authorized to edit users.", 401)
    if not db:
        return error('The ACP is not available in single-user mode.', 500)
    data = request.form

    form = UserEditForm()
    if not form.validate():
        return error("Bad Request", 400)
    action = data['action']

    if action == 'new':
        if not data['username']:
            return error("No username to create specified.", 400)
        uid = max(int(i) for i in db.hgetall('users').values()) + 1
        pf = [False for p in PERMISSIONS]
        pf[0] = True  # active
        pf[7] = True  # must_change_password
        user = User(uid, data['username'], '', '', '', *pf)
        write_user(user)
        db.hset('users', user.username, user.uid)
        new = True
    else:
        user = get_user(data['uid'])
        new = False

    if not user:
        return error("User does not exist.", 404)

    alert = ''
    alert_status = ''

    if action == 'save':
        if data['newpwd1']:
            if data['newpwd1'] == data['newpwd2']:
                user.password = password_hash(data['newpwd1'])
            else:
                alert = 'Passwords don’t match.'
                alert_status = 'danger'
                action = 'save_fail'
        elif new:
            alert = 'Must set a password.'
            alert_status = 'danger'
            action = 'save_fail'

        if data['username'] != user.username:
            db.hdel('users', user.username)
            user.username = data['username']
            db.hset('users', user.username, user.uid)
        user.realname = data['realname']
        user.email = data['email']
        for p in PERMISSIONS:
            setattr(user, p, p in data)
        user.active = True
        if user.uid == current_user.uid:
            user.is_admin = True
            user.must_change_password = False
            current_user = user
        write_user(user)

    return render('coil_users_edit.tmpl',
                  context={'title': 'Edit user',
                           'user': user,
                           'new': new,
                           'action': action,
                           'alert': alert,
                           'alert_status': alert_status,
                           'form': form})
1205093
private function _handle_account_edits() {
            if ( ! $this->is_user_admin() ) {
                return;
            }

            $action = fs_get_action();

            if ( empty( $action ) ) {
                return;
            }

            $plugin_id  = fs_request_get( 'plugin_id', $this->get_id() );
            $install_id = fs_request_get( 'install_id', '' );

            // Alias.
            $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';

            $is_network_action = $this->is_network_level_action();
            $blog_id           = $this->is_network_level_site_specific_action();

            if ( is_numeric( $blog_id ) ) {
                $this->switch_to_blog( $blog_id );
            } else {
                $blog_id = '';
            }

            switch ( $action ) {
                case 'opt_in':
                    check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );

                    if ( $plugin_id == $this->get_id() ) {
                        if ( $is_network_action && ! empty( $blog_id ) ) {
                            if ( ! $this->is_registered() ) {
                                $this->install_with_user(
                                    $this->get_network_user(),
                                    false,
                                    false,
                                    false,
                                    false
                                );

                                $this->_admin_notices->add(
                                    $this->get_text_inline( 'Site successfully opted in.', 'successful-opt-in' ),
                                    $this->get_text_inline( 'Awesome', 'awesome' )
                                );
                            }
                        }
                    }
                    break;

                case 'toggle_tracking':
                    check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );

                    if ( $plugin_id == $this->get_id() ) {
                        if ( $is_network_action && ! empty( $blog_id ) ) {
                            if ( $this->is_registered() ) {
                                if ( $this->is_tracking_prohibited() ) {
                                    if ( $this->allow_site_tracking() ) {
                                        $this->_admin_notices->add(
                                            sprintf( $this->get_text_inline( 'We appreciate your help in making the %s better by letting us track some usage data.', 'opt-out-message-appreciation' ), $this->_module_type ),
                                            $this->get_text_inline( 'Thank you!', 'thank-you' )
                                        );
                                    }
                                } else {
                                    if ( $this->stop_site_tracking() ) {
                                        $this->_admin_notices->add(
                                            sprintf(
                                                $this->get_text_inline( 'We will no longer be sending any usage data of %s on %s to %s.', 'opted-out-successfully' ),
                                                $this->get_plugin_title(),
                                                fs_strip_url_protocol( get_site_url( $blog_id ) ),
                                                sprintf(
                                                    '<a href="%s" target="_blank">%s</a>',
                                                    'https://freemius.com',
                                                    'freemius.com'
                                                )
                                            )
                                        );
                                    }
                                }
                            }
                        }
                    }

                    break;

                case 'delete_account':
                    check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );

                    if ( $plugin_id == $this->get_id() ) {
                        if ( $is_network_action && empty( $blog_id ) ) {
                            $this->delete_network_account_event();
                        } else {
                            $this->delete_account_event();
                        }

                        // Clear user and site.
                        $this->_site = null;
                        $this->_user = null;

                        $this->maybe_set_slug_and_network_menu_exists_flag();

                        fs_redirect( $this->get_activation_url() );
                    } else {
                        if ( $this->is_addon_activated( $plugin_id ) ) {
                            $fs_addon = self::get_instance_by_id( $plugin_id );
                            $fs_addon->delete_account_event();

                            fs_redirect( $this->_get_admin_page_url( 'account' ) );
                        }
                    }

                    return;

                case 'downgrade_account':
                    if ( is_numeric( $blog_id ) ) {
                        check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
                    } else {
                        check_admin_referer( $action );
                    }

                    $switch_to_network_install_blog_after_cancellation = (
                        is_numeric( $blog_id ) &&
                        $plugin_id == $this->get_id() &&
                        ! $this->is_trial()
                    );

                    $result = $this->cancel_subscription_or_trial( $plugin_id );
                    if ( $this->is_api_error( $result ) ) {
                        $this->_admin_notices->add(
                            $result->error->message,
                            $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
                            'error'
                        );
                    }

                    if ( $switch_to_network_install_blog_after_cancellation ) {
                        $this->switch_to_blog( $this->_storage->network_install_blog_id );
                    }

                    return;

                case 'activate_license':
                    check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );

                    $fs = $this;
                    if ( $plugin_id != $this->get_id() ) {
                        $fs = $this->is_addon_activated( $plugin_id ) ?
                            self::get_instance_by_id( $plugin_id ) :
                            null;
                    }

                    if ( is_object( $fs ) ) {
                        $fs->_activate_license();
                    }

                    return;

                case 'deactivate_license':
                    check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );

                    if ( $plugin_id == $this->get_id() ) {
                        $this->_deactivate_license();

                        if ( $this->is_only_premium() ) {
                            // Clear user and site.
                            $this->_site = null;
                            $this->_user = null;

                            if ( ! $is_network_action ) {
                                fs_redirect( $this->get_activation_url() );
                            } else if ( is_numeric( $blog_id ) ) {
                                $this->switch_to_blog( $this->_storage->network_install_blog_id );
                            }
                        }
                    } else {
                        if ( $this->is_addon_activated( $plugin_id ) ) {
                            $fs_addon = self::get_instance_by_id( $plugin_id );
                            $fs_addon->_deactivate_license();
                        }
                    }

                    return;

                case 'check_updates':
                    check_admin_referer( $action );
                    $this->check_updates();

                    return;

                case 'change_owner':
                    $state = fs_request_get( 'state', 'init' );
                    switch ( $state ) {
                        case 'init':
                            $candidate_email = fs_request_get( 'candidate_email', '' );

                            if ( $this->init_change_owner( $candidate_email ) ) {
                                $this->_admin_notices->add( sprintf( $this->get_text_inline( 'Please check your mailbox, you should receive an email via %s to confirm the ownership change. From security reasons, you must confirm the change within the next 15 min. If you cannot find the email, please check your spam folder.', 'change-owner-request-sent-x' ), '<b>' . $this->_user->email . '</b>' ) );
                            }
                            break;
                        case 'owner_confirmed':
                            $candidate_email = fs_request_get( 'candidate_email', '' );

                            $this->_admin_notices->add( sprintf( $this->get_text_inline( 'Thanks for confirming the ownership change. An email was just sent to %s for final approval.', 'change-owner-request_owner-confirmed' ), '<b>' . $candidate_email . '</b>' ) );
                            break;
                        case 'candidate_confirmed':
                            if ( $this->complete_change_owner() ) {
                                $this->_admin_notices->add_sticky(
                                    sprintf( $this->get_text_inline( '%s is the new owner of the account.', 'change-owner-request_candidate-confirmed' ), '<b>' . $this->_user->email . '</b>' ),
                                    'ownership_changed',
                                    $this->get_text_x_inline( 'Congrats', 'as congratulations', 'congrats' ) . '!'
                                );
                            } else {
                                // @todo Handle failed ownership change message.
                            }
                            break;
                    }

                    return;

                case 'update_email':
                    check_admin_referer( 'update_email' );

                    $new_email = fs_request_get( 'fs_email_' . $this->get_unique_affix(), '' );
                    $result    = $this->update_email( $new_email );

                    if ( isset( $result->error ) ) {
                        switch ( $result->error->code ) {
                            case 'user_exist':
                                $this->_admin_notices->add(
                                    $this->get_text_inline( 'Sorry, we could not complete the email update. Another user with the same email is already registered.', 'user-exist-message' ) . ' ' .
                                    sprintf( $this->get_text_inline( 'If you would like to give up the ownership of the %s\'s account to %s click the Change Ownership button.', 'user-exist-message_ownership' ), $this->_module_type, '<b>' . $new_email . '</b>' ) .
                                    sprintf(
                                        '<a style="margin-left: 10px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
                                        $this->get_account_url( 'change_owner', array(
                                            'state'           => 'init',
                                            'candidate_email' => $new_email
                                        ) ),
                                        $this->get_text_inline( 'Change Ownership', 'change-ownership' )
                                    ),
                                    $oops_text,
                                    'error'
                                );
                                break;
                        }
                    } else {
                        $this->_admin_notices->add( $this->get_text_inline( 'Your email was successfully updated. You should receive an email with confirmation instructions in few moments.', 'email-updated-message' ) );
                    }

                    return;

                case 'update_user_name':
                    check_admin_referer( 'update_user_name' );

                    $result = $this->update_user_name();

                    if ( isset( $result->error ) ) {
                        $this->_admin_notices->add(
                            $this->get_text_inline( 'Please provide your full name.', 'name-update-failed-message' ),
                            $oops_text,
                            'error'
                        );
                    } else {
                        $this->_admin_notices->add( $this->get_text_inline( 'Your name was successfully updated.', 'name-updated-message' ) );
                    }

                    return;

                #region Actions that might be called from external links (e.g. email)

                case 'cancel_trial':
                    $result = $this->cancel_subscription_or_trial( $plugin_id );
                    if ( $this->is_api_error( $result ) ) {
                        $this->_admin_notices->add(
                            $result->error->message,
                            $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
                            'error'
                        );
                    }

                    return;

                case 'verify_email':
                    $this->verify_email();

                    return;

                case 'sync_user':
                    $this->_handle_account_user_sync();

                    return;

                case $this->get_unique_affix() . '_sync_license':
                    $this->_sync_license();

                    return;

                case 'download_latest':
                    $this->download_latest_directly( $plugin_id );

                    return;

                #endregion
            }

            if ( WP_FS__IS_POST_REQUEST ) {
                $properties = array( 'site_secret_key', 'site_id', 'site_public_key' );
                foreach ( $properties as $p ) {
                    if ( 'update_' . $p === $action ) {
                        check_admin_referer( $action );

                        $this->_logger->log( $action );

                        $site_property                      = substr( $p, strlen( 'site_' ) );
                        $site_property_value                = fs_request_get( 'fs_' . $p . '_' . $this->get_unique_affix(), '' );
                        $this->get_site()->{$site_property} = $site_property_value;

                        // Store account after modification.
                        $this->_store_site();

                        $this->do_action( 'account_property_edit', 'site', $site_property, $site_property_value );

                        $this->_admin_notices->add( sprintf(
                        /* translators: %s: User's account property (e.g. email address, name) */
                            $this->get_text_inline( 'You have successfully updated your %s.', 'x-updated' ),
                            '<b>' . str_replace( '_', ' ', $p ) . '</b>'
                        ) );

                        return;
                    }
                }
            }
        }
845973
def users_update(self, user_id, **kwargs):
        """"""
        return self.__call_api_post('users.update', userId=user_id, data=kwargs)
305042
public function editAccount($user_id)
    {
        $this->setUserAccount($user_id);
        $this->controlAccessEditAccount();
        $this->setTitleEditAccount();
        $this->setBreadcrumbEditAccount();
        $this->setData('user', $this->data_user);

        $this->submitEditAccount();
        $this->outputEditAccount();
    }
1140237
def __could_edit(self, slug):
        '''
        
        '''
        page_rec = MWiki.get_by_uid(slug)
        if not page_rec:
            return False
        if self.check_post_role()['EDIT']:
            return True
        elif page_rec.user_name == self.userinfo.user_name:
            return True
        else:
            return False
918077
public function edit()
    {
        $this->defaultData();
        $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class);
        $user = $this->getUserResource();

        $types = $user->getTypes();
        $myFormContainer = new tao_actions_form_Users(reset($types), $user);
        $myForm = $myFormContainer->getForm();

        if ($myForm->isSubmited()) {
            if ($myForm->isValid()) {
                $values = $myForm->getValues();
                if (!empty($values['password2']) && !empty($values['password3'])) {
                    $plainPassword =  $values['password2'];
                    $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password2']);
                }

                unset($values['password2']);
                unset($values['password3']);

                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_UILG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_UILG]);
                }
                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_DEFLG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_DEFLG]);
                }

                $userService->checkCurrentUserAccess($values[GenerisRdf::PROPERTY_USER_ROLES]);

                // leave roles which are not in the allowed list for current user
                $oldRoles = $userService->getUserRoles($user);
                $allowedRoles = $userService->getPermittedRoles($userService->getCurrentUser(), $oldRoles, false);
                $staticRoles = array_diff($oldRoles, $allowedRoles);
                $values[GenerisRdf::PROPERTY_USER_ROLES] = array_merge($values[GenerisRdf::PROPERTY_USER_ROLES], $staticRoles);

                $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($user);

                if ($binder->bind($values)) {
                    $data = [];
                    if (isset($plainPassword)){
                        $data = ['hashForKey' => UserHashForEncryption::hash($plainPassword)];
                    }
                    $this->getEventManager()->trigger(new UserUpdatedEvent(
                        $user,
                        array_merge($values, $data))
                    );
                    $this->setData('message', __('User saved'));
                }
            }
        }

        $this->setData('formTitle', __('Edit a user'));
        $this->setData('myForm', $myForm->render());
        $this->setView('user/form.tpl');
    }
25853
public function editUserLogin()
    {
        $this->controlAccessUserLogin();
        $this->setTitleEditUserLogin();
        $this->setBreadcrumbEditUserLogin();

        $this->submitUserLogin();
        $this->outputEditUserLogin();
    }
283872
public function edit($userId = null) {

		if ( $this->request->is('post')) {
			unset ( $this->request->data[$this->modelClass]['last_login'] );

			
			$this->SiteUser->bindModel(array(
		        'hasMany' => array(
		            'RolUser' => array(
		                'classname' => 'Users.RolUser',
		            ) 
		        ) 
		    ));

			$rolUser = array();
			if (!empty($this->request->data['Rol']['Rol'])) {
			    	$rolUser[] = array(
			    		'rol_id' => $this->request->data['Rol']['Rol'],
			    		'user_id' => $userId,
			    		);
			

			$this->SiteUser->RolUser->deleteAll(array('RolUser.user_id' => $userId ));

			if ( $this->SiteUser->RolUser->saveMany( $rolUser ) ) {
				$this->Session->setFlash(__d('users', 'User saved'));
			} else {
				$this->Session->setFlash(__d('users', 'Error saving'), 'Risto.flash_error');
			}
		  } else {
		  	$this->Session->setFlash(__d('users', 'Error: no has elegido el rol del usuario, intentelo de nuevo.'), 'Risto.flash_error');
		  }
		  $this->redirect($this->referer());
		}

		if (empty($this->request->data)) {
			$this->SiteUser->recursive = 1;
			$this->request->data = $this->SiteUser->read(null, $userId);
			unset($this->request->data[$this->modelClass]['password']);
		}

		$roles = $this->SiteUser->User->Rol->find('list');
		$this->set(compact( 'roles'));
		$this->render('admin_form');
	}
410553
def upgrade():
    """"""
    op.create_table(
        'accounts_role',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(length=80), nullable=True),
        sa.Column('description', sa.String(length=255), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name')
    )
    op.create_table(
        'accounts_user',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('email', sa.String(length=255), nullable=True),
        sa.Column('password', sa.String(length=255), nullable=True),
        sa.Column('active', sa.Boolean(name='active'), nullable=True),
        sa.Column('confirmed_at', sa.DateTime(), nullable=True),
        sa.Column('last_login_at', sa.DateTime(), nullable=True),
        sa.Column('current_login_at', sa.DateTime(), nullable=True),
        sa.Column('last_login_ip',
                  sqlalchemy_utils.types.ip_address.IPAddressType(),
                  nullable=True),
        sa.Column('current_login_ip',
                  sqlalchemy_utils.types.ip_address.IPAddressType(),
                  nullable=True),
        sa.Column('login_count', sa.Integer(), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('email')
    )
    op.create_table(
        'accounts_user_session_activity',
        sa.Column('created', sa.DateTime(), nullable=False),
        sa.Column('updated', sa.DateTime(), nullable=False),
        sa.Column('sid_s', sa.String(length=255), nullable=False),
        sa.Column('user_id', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(
            ['user_id'], [u'accounts_user.id'],
            name='fk_accounts_session_activity_user_id',
        ),
        sa.PrimaryKeyConstraint('sid_s')
    )
    op.create_table(
        'accounts_userrole',
        sa.Column('user_id', sa.Integer(), nullable=True),
        sa.Column('role_id', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(
            ['role_id'], ['accounts_role.id'],
            name='fk_accounts_userrole_role_id',
        ),
        sa.ForeignKeyConstraint(
            ['user_id'], ['accounts_user.id'],
            name='fk_accounts_userrole_user_id',
        ),
    )
    with op.batch_alter_table('transaction') as batch_op:
        batch_op.add_column(sa.Column(
            'user_id',
            sa.Integer(),
            sa.ForeignKey('accounts_user.id'),
            nullable=True,
        ))
        batch_op.create_index(
            op.f('ix_transaction_user_id'), ['user_id'], unique=False
        )
124002
def can_edit(self, user):
        """"""
        return self.class_.can_edit(user) and self.status != u'locked'
899692
def modify_user(self, username, attribute, value):
        

        cmd = "userManager.cgi?action=modifyUser&name={0}".format(
            username)

        if attribute.lower() == "group":
            cmd += "&user.Group=%s" % value.lower()

        elif attribute.lower() == "sharable":
            cmd += "&user.Sharable=%s" % value.lower()

        elif attribute.lower() == "reserved":
            cmd += "&user.Reserved=%s" % value.lower()

        elif attribute == "memo":
            cmd += "&user.Memo=%s" % value.lower()

        ret = self.command(cmd)
        return ret.content.decode('utf-8')
494716
def upgrade():
    """"""
    op.create_table(
        'userprofiles_userprofile',
        sa.Column('user_id', sa.Integer(), nullable=False),
        sa.Column('username', sa.String(length=255), nullable=True),
        sa.Column('displayname', sa.String(length=255), nullable=True),
        sa.Column('full_name', sa.String(length=255), nullable=False),
        sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ),
        sa.PrimaryKeyConstraint('user_id'),
        sa.UniqueConstraint('username')
    )
1059976
def update_account(self, account_id, **params):
        """"""
        response = self._put('v2', 'accounts', account_id, data=params)
        return self._make_api_object(response, Account)
1270387
def modify_user(self, username, data):
        
        if 'password' in data:
            # generate salt
            char_set = string.ascii_letters + string.digits
            data['pwd_salt'] = ''.join(random.choice(char_set) for x in range(8))
            data['pwd_hash'] = self._gen_hash(data['password'], data['pwd_salt'])
            del(data['password'])

        sql = "UPDATE user SET "
        sql += ', '.join("%s = ?" % k for k in sorted(data))
        sql += " WHERE username = ?"

        vals = []
        for k in sorted(data):
            vals.append(data[k])
        vals.append(username)

        try:
            self._db_curs.execute(sql, vals)
            self._db_conn.commit()
        except (sqlite3.OperationalError, sqlite3.IntegrityError) as error:
            raise AuthError(error)
390808
public function edit()
    {
        $id = $this->Auth->user('id');
        $user = $this->Users->find()->where(['id' => $id])->first();
        if (!$user) {
            throw new NotFoundException('User could not be found');
        }
            
        $user->accessible('password', true);
        if ($this->request->is(['post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            $this->Users->save($user);
        }
        $this->set(compact('user'));
    }
1136335
def _create_user(ctx):
    """"""

    username, passhash = _get_credentials(ctx.obj['username'],
                                          ctx.obj['password'],
                                          ctx.obj['db'])

    if ctx.obj['db'].objectmodels['user'].count({'name': username}) > 0:
        raise KeyError()

    new_user = ctx.obj['db'].objectmodels['user']({
        'uuid': str(uuid4()),
        'created': std_now()
    })

    new_user.name = username
    new_user.passhash = passhash

    return new_user
840386
def user(ctx, username, password):
    """"""

    ctx.obj['username'] = username
    ctx.obj['password'] = password