3 namespace Drupal\Core\Field\Plugin\Field\FieldType;
5 use Drupal\Core\Entity\EntityMalformedException;
6 use Drupal\Core\Field\FieldStorageDefinitionInterface;
7 use Drupal\Core\StringTranslation\TranslatableMarkup;
8 use Drupal\Core\TypedData\DataDefinition;
11 * Defines the 'password' entity field type.
15 * label = @Translation("Password"),
16 * description = @Translation("An entity field containing a password value."),
20 class PasswordItem extends StringItem {
25 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
26 $properties['value'] = DataDefinition::create('string')
27 ->setLabel(new TranslatableMarkup('The hashed password'))
28 ->setSetting('case_sensitive', TRUE);
29 $properties['existing'] = DataDefinition::create('string')
30 ->setLabel(new TranslatableMarkup('Existing password'));
31 $properties['pre_hashed'] = DataDefinition::create('boolean')
32 ->setLabel(new TranslatableMarkup('Determines if a password needs hashing'));
40 public function preSave() {
43 $entity = $this->getEntity();
45 if ($this->pre_hashed) {
46 // Reset the pre_hashed value since it has now been used.
47 $this->pre_hashed = FALSE;
49 elseif ($entity->isNew() || (strlen(trim($this->value)) > 0 && $this->value != $entity->original->{$this->getFieldDefinition()->getName()}->value)) {
50 // Allow alternate password hashing schemes.
51 $this->value = \Drupal::service('password')->hash(trim($this->value));
52 // Abort if the hashing failed and returned FALSE.
54 throw new EntityMalformedException('The entity does not have a password.');
58 if (!$entity->isNew()) {
59 // If the password is empty, that means it was not changed, so use the
61 if (empty($this->value)) {
62 $this->value = $entity->original->{$this->getFieldDefinition()->getName()}->value;
65 // Ensure that the existing password is unset to minimise risks of it
66 // getting serialized and stored somewhere.
67 $this->existing = NULL;
73 public function isEmpty() {
74 // We cannot use the parent implementation from StringItem as it does not
75 // consider the additional 'existing' property that PasswordItem contains.
76 $value = $this->get('value')->getValue();
77 $existing = $this->get('existing')->getValue();
78 return $value === NULL && $existing === NULL;