$contextEntity is the currently logged in user's UserEntity

{@inheritDoc}
357228
protected function getConstraints(array $contextData, AbstractEntity $contextEntity = null)
    {
        $notBlank = new Assert\NotBlank(['message' => self::BLANK]);

        $constraints = [
            'email' => new Assert\Optional([
                $notBlank,
                new Assert\Email([
                    'checkHost' => true
                ]),
            ]),
            'password' => new Assert\Optional([$notBlank])
        ];

        if (isset($contextData['email']) or isset($contextData['password'])) {
            $constraints['current_password'] = [
                $notBlank,
                new Assert\Callback(['callback' => [$this, 'validateCurrentPassword']]),
            ];
        }

        return $constraints;
    }
796734
protected function _afterEntityInstantiate(AnCommandContext $context)
    {
        $entity = $context->entity;

        $this->getSpace()->setEntityState($entity, AnDomain::STATE_NEW);

        //set the entity default valuees
        $attributes = $this->getDescription()->getAttributes();
        foreach ($attributes as $attribute) {
            $entity->set($attribute->getName(), $attribute->getDefaultValue());
        }

        //materialize required one-to-one relationship
        $relationships = $this->getDescription()->getRelationships();
        foreach ($relationships as $relation) {
            if ($relation->isOneToOne() && $relation->isRequired()) {
                $property = $relation->getName();
                $$entity->set($property, $relation->getChildRepository()->getEntity());
            }
        }
    }
1029612
public function updateUserTypeEntityIfExists($entityId, $fieldName, $fields) {
        $item = $this->getUserTypeEntity($entityId, $fieldName);
        if (!$item) {
            return false;
        }

        return $this->updateUserTypeEntity($item['ID'], $fields);

    }
392216
protected function _beforeEntityInsert(AnCommandContext $context)
    {
        if (!empty($this->couponCode)) {
            $coupon = $this->getService('repos:subscriptions.coupon')
                           ->find(array(
                             'code' => $this->couponCode,
                           ));

            if ($coupon) {
                $coupon->used();
            }
        }
    }
233355
public function getUserEntity($user)
    {
        if (is_numeric($user)) {
            $userEntity = $this->entityTypeManager
                ->getStorage('user')
                ->load($user);
        } else {
            $userEntities = $this->entityTypeManager
                ->getStorage('user')
                ->loadByProperties(['name' => $user]);
            $userEntity = reset($userEntities);
        }

        return $userEntity;
    }
155003
protected function _beforeEntityInsert(AnCommandContext $context)
    {
        $max = $this->getScopedQuery($context->entity)->fetchValue('MAX(@col(ordering))');
        $this->ordering = $max + 1;
    }
570522
public function setUserContext($userId = null, $email = null, array $data = null)
    {
        $this->raven->set_user_data($userId, $email, $data);
    }
98571
protected function createResourceFromUser(UserEntity $user)
    {
        $resource = new Resource(
            $this->generateReadUrl($user->getUsernameCanonical()),
            array(
                 'username'   => $user->getUsernameCanonical(),
                 'email'      => $user->getEmail(),
                 'last_login' => $user->getLastLogin() ? $user->getLastLogin()->format('c') : null,
            )
        );

        return $resource;
    }
1146799
public function getUserEntityByUserCredentials(
        $username,
        $password,
        $grantType,
        ClientEntityInterface $clientEntity
    ): ?UserEntityInterface {
        $builder = $this->connection->createQueryBuilder();
        $user = $builder->select(['user.id', 'user.password'])
            ->from('user')
            ->where('username = :username')
            ->setParameter('username', $username)
            ->execute()
            ->fetch();

        if (!$user) {
            return null;
        }

        if (!password_verify($password, $user['password'])) {
            return null;
        }

        return new User(Uuid::fromBytesToHex($user['id']));
    }
705524
protected function loginFinish(Entity\Users $userEntity)
    {
        if (!$this->updateUserLogin($userEntity)) {
            return false;
        }

        $tokenEntity = $this->updateAuthToken($userEntity);
        $token = new Token($userEntity, $tokenEntity);

        $this->session->migrate(false, 0);
        $this->session->set('authentication', $token);
        $this->session->save();

        return true;
    }
861346
protected function _fetchEntity(ControllerContext $context)
    {
        if(!$context->result instanceof ModelEntityInterface)
        {
            switch($context->action)
            {
                case 'add'   :
                    $context->setEntity($this->getModel()->create($context->request->data->toArray()));
                    break;

                case 'edit'  :
                case 'delete':
                    $context->setEntity($this->getModel()->fetch());
                    break;

            }

        }
        else $context->setEntity($context->result);
    }
330870
protected function _beforeEntityUpdate(AnCommandContext $context)
    {
        if ($this->getModifiedData()->ordering) {
            $store = $this->getRepository()->getStore();
            $query = $this->getScopedQuery($context->entity);
            $change = $this->getModifiedData()->ordering;

            if ($change->new - $change->old < 0) {
                $query->update('@col(ordering) = @col(ordering) + 1');
                $query->where('ordering', '>=',  $change->new)->where('ordering', '<',   $change->old);
            } else {
                $query->update('@col(ordering) = @col(ordering) - 1');
                $query->where('ordering', '>',   $change->old)->where('ordering', '<=',  $change->new);
            }

            $store->execute($query);
        }
    }
1156274
private function validate(Entity\Users $userEntity)
    {
        $options = [
            'allow_extra_fields' => true,
            'csrf_protection'    => false,
        ];

        /** @var FormInterface $form */
        $form = $this->app['form.factory']->createBuilder(FormType\UserNewType::class, $userEntity, $options)
            ->getForm()
            ->submit($userEntity->toArray())
        ;
        $errors = $form->getErrors(true);
        if ($errors->count() === 0) {
            return null;
        }

        $messages = [];
        foreach ($errors as $error) {
            $messages[] = $error->getMessage();
        }

        return $messages;
    }
131142
protected function _getUserEntity($userId) {
		if (is_a($userId, EntityInterface::class)) {
			return $userId;
		}

		if (is_string($userId) || is_integer($userId)) {
			$entity = $this->UserTable->newEntity();

			return $this->UserTable->patchEntity(
				$entity,
				[$this->UserTable->primaryKey() => $userId],
				['guard' => false]
			);
		}

		if (is_array($userId)) {
			$entity = $this->UserTable->newEntity();

			return $this->UserTable->patchEntity(
				$entity,
				$userId,
				['guard' => false]
			);
		}
	}
769456
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        // If the user has repository_instances data, then only the User context should be present so get the first context.
        $contexts = $contextlist->get_contexts();
        if (count($contexts) == 0) {
            return;
        }
        $context = reset($contexts);

        // Sanity check that context is at the User context level, then get the userid.
        if ($context->contextlevel !== CONTEXT_USER) {
            return;
        }
        $userid = $context->instanceid;

        $sql = "SELECT DISTINCT
                       ri.id as id,
                       r.type as type,
                       ri.name as name,
                       ri.timecreated as timecreated,
                       ri.timemodified as timemodified
                  FROM {repository_instances} ri
                  JOIN {repository} r ON r.id = ri.typeid
                 WHERE ri.userid = :userid";

        $params = [
            'userid' => $userid
        ];

        $repositoryinstances = $DB->get_records_sql($sql, $params);

        foreach ($repositoryinstances as $repositoryinstance) {
            // The repository_instances data export is organised in: {User Context}/Repository plug-ins/{Plugin Name}/data.json.
            $subcontext = [
                get_string('plugin', 'core_repository'),
                get_string('pluginname', 'repository_' . $repositoryinstance->type)
            ];

            $data = (object) [
                'type' => $repositoryinstance->type,
                'name' => $repositoryinstance->name,
                'timecreated' => transform::datetime($repositoryinstance->timecreated),
                'timemodified' => transform::datetime($repositoryinstance->timemodified)
            ];

            writer::with_context($context)->export_data($subcontext, $data);
        }
    }
1362479
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        // If the user has data, then only the User context should be present so get the first context.
        $contexts = $contextlist->get_contexts();
        if (count($contexts) == 0) {
            return;
        }
        $context = reset($contexts);

        // Sanity check that context is at the User context level, then get the userid.
        if ($context->contextlevel !== CONTEXT_USER) {
            return;
        }
        $userid = $context->instanceid;

        $sql = "SELECT roa.id as id,
                       roa.itemid as itemid,
                       roa.permissionid as permissionid,
                       roa.timecreated as timecreated,
                       roa.timemodified as timemodified
                  FROM {repository_onedrive_access} roa
                 WHERE roa.usermodified = :userid";

        $params = [
            'userid' => $userid
        ];

        $onedriveaccesses = $DB->get_records_sql($sql, $params);
        $index = 0;
        foreach ($onedriveaccesses as $onedriveaccess) {
            // Data export is organised in: {User Context}/Repository plug-ins/{Plugin Name}/Access/{index}/data.json.
            $index++;
            $subcontext = [
                get_string('plugin', 'core_repository'),
                get_string('pluginname', 'repository_onedrive'),
                get_string('access', 'repository_onedrive'),
                $index
            ];

            $data = (object) [
                'itemid' => $onedriveaccess->itemid,
                'permissionid' => $onedriveaccess->permissionid,
                'timecreated' => transform::datetime($onedriveaccess->timecreated),
                'timemodified' => transform::datetime($onedriveaccess->timemodified)
            ];

            writer::with_context($context)->export_data($subcontext, $data);
        }

    }
213680
public function updateUserContext(UserContext $context): void
    {
        if ($this->session->isStarted()) {
            $context->addParameter('sessionId', $this->session->getId());
        }
    }