key_auth.module in Key auth 8
Module that allows authentication via key.
File
key_auth.moduleView source
<?php
/**
* @file
* Module that allows authentication via key.
*/
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Implements hook_entity_base_field_info().
*/
function key_auth_entity_base_field_info(EntityTypeInterface $entity_type) {
// Check if this is the user entity type.
if ($entity_type
->id() === 'user') {
// Add a field to store the api key.
$fields['api_key'] = BaseFieldDefinition::create('string')
->setLabel(t('API key'))
->setDescription(t('The API key used for authentication.'))
->addConstraint('UniqueField')
->setSettings([
'max_length' => 255,
'text_processing' => 0,
]);
return $fields;
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function key_auth_user_insert(EntityInterface $entity) {
// Check if we should auto-generate a key.
if (\Drupal::config('key_auth.settings')
->get('auto_generate_keys')) {
// Load the key auth service.
$key_auth = \Drupal::service('key_auth');
// Check if this user has access to use key auth.
if ($key_auth
->access($entity)) {
// Generate a key.
$entity
->set('api_key', $key_auth
->generateKey())
->save();
}
}
}
Functions
Name | Description |
---|---|
key_auth_entity_base_field_info | Implements hook_entity_base_field_info(). |
key_auth_user_insert | Implements hook_ENTITY_TYPE_insert(). |