Skip to content

Commit cdcf3ca

Browse files
committed
5124: Refactored settings
1 parent 08dec18 commit cdcf3ca

File tree

5 files changed

+142
-36
lines changed

5 files changed

+142
-36
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
services:
2+
_defaults:
3+
autowire: true
4+
25
logger.channel.os2loop_cura_login:
36
parent: logger.channel_base
47
arguments: ["os2loop_cura_login"]
8+
9+
Drupal\os2loop_cura_login\Settings:

web/profiles/custom/os2loop/modules/os2loop_cura_login/src/Controller/Os2loopCuraLoginController.php

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
namespace Drupal\os2loop_cura_login\Controller;
66

77
use Drupal\Component\Datetime\TimeInterface;
8-
use Drupal\Core\Config\ImmutableConfig;
98
use Drupal\Core\Controller\ControllerBase;
109
use Drupal\Core\Logger\RfcLogLevel;
1110
use Drupal\Core\Routing\TrustedRedirectResponse;
1211
use Drupal\Core\Url;
12+
use Drupal\os2loop_cura_login\Settings;
1313
use Drupal\user\Entity\User;
1414
use Drupal\user\UserStorageInterface;
1515
use Firebase\JWT\JWT;
@@ -37,21 +37,16 @@ final class Os2loopCuraLoginController extends ControllerBase {
3737
*/
3838
private readonly UserStorageInterface $userStorage;
3939

40-
/**
41-
* The module config.
42-
*/
43-
private readonly ImmutableConfig $config;
44-
4540
/**
4641
* Constructor.
4742
*/
4843
public function __construct(
44+
private readonly Settings $settings,
4945
private readonly TimeInterface $time,
5046
#[Autowire(service: 'logger.channel.os2loop_cura_login')]
5147
private readonly LoggerInterface $logger,
5248
) {
5349
$this->userStorage = $this->entityTypeManager()->getStorage('user');
54-
$this->config = $this->config('os2loop_cura_login.settings');
5550
}
5651

5752
/**
@@ -75,7 +70,7 @@ public function start(Request $request, ?string $jwt): Response {
7570
]);
7671

7772
if (empty($jwt)) {
78-
$name = $this->config->get('payload_name') ?? 'payload';
73+
$name = $this->settings->getPayloadName();
7974
$jwt = Request::METHOD_POST === $request->getMethod()
8075
? $request->request->getString($name)
8176
: $request->query->getString($name);
@@ -91,16 +86,16 @@ public function start(Request $request, ?string $jwt): Response {
9186
throw new BadRequestHttpException('Missing or empty JWT');
9287
}
9388

94-
$secret = $this->config->get('signing_secret');
89+
$secret = $this->settings->getSigningSecret();
9590
// @todo Get rid of the double base64 encoding.
9691
$secret = base64_decode($secret);
9792

9893
$originalLeeway = JWT::$leeway;
99-
$leeway = (int) $this->config->get('jwt_leeway');
94+
$leeway = $this->settings->getJwtLeeway();
10095
if ($leeway > 0) {
10196
JWT::$leeway = $leeway;
10297
}
103-
$payload = (array) JWT::decode($jwt, new Key($secret, $this->config->get('signing_algorithm')));
98+
$payload = (array) JWT::decode($jwt, new Key($secret, $this->settings->getSigningAlgorithm()));
10499
JWT::$leeway = $originalLeeway;
105100

106101
$this->debug('@debug', [
@@ -253,7 +248,7 @@ public function log($level, \Stringable|string $message, array $context = []): v
253248
LogLevel::DEBUG => RfcLogLevel::DEBUG,
254249
];
255250
$rfcLogLevel = $levels[$level] ?? RfcLogLevel::ERROR;
256-
if ((int) $this->config->get('log_level') >= $rfcLogLevel) {
251+
if ((int) $this->settings->getLogLevel() >= $rfcLogLevel) {
257252
$this->logger->log($level, $message, $context);
258253
}
259254
}

web/profiles/custom/os2loop/modules/os2loop_cura_login/src/Drush/Commands/Os2loopCuraLoginCommands.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@ public function __construct(
3434
#[CLI\Argument(name: 'username', description: 'The username.')]
3535
#[CLI\Option(name: 'post', description: 'Use POST to get the login URL')]
3636
#[CLI\Usage(name: 'os2loop-cura-login:get-login-url [email protected]', description: 'Get login URL')]
37-
public function commandName(
37+
public function getLoginUrl(
3838
$username,
3939
$options = [
40+
'linkUrl' => NULL,
4041
'get' => NULL,
4142
'secret' => NULL,
4243
'algorithm' => 'HS256',
@@ -60,7 +61,7 @@ public function commandName(
6061
}
6162
else {
6263
$method = Request::METHOD_POST;
63-
$requestOptions['body'] = $jwt;
64+
$requestOptions['body'] = ['payload' => $jwt];
6465
}
6566
$url = Url::fromRoute('os2loop_cura_login.start', $routeParameters)->setAbsolute()->toString(TRUE)->getGeneratedUrl();
6667
$this->io()->writeln($method === Request::METHOD_POST

web/profiles/custom/os2loop/modules/os2loop_cura_login/src/Form/SettingsForm.php

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,26 @@
55
namespace Drupal\os2loop_cura_login\Form;
66

77
use Drupal\Component\Utility\Random;
8+
use Drupal\Core\Config\ConfigFactoryInterface;
9+
use Drupal\Core\DependencyInjection\AutowireTrait;
810
use Drupal\Core\Form\ConfigFormBase;
911
use Drupal\Core\Form\FormStateInterface;
1012
use Drupal\Core\Logger\RfcLogLevel;
1113
use Drupal\Core\Url;
14+
use Drupal\os2loop_cura_login\Settings;
1215

1316
/**
1417
* Configure OS2Loop Cura login settings for this site.
1518
*/
1619
final class SettingsForm extends ConfigFormBase {
20+
use AutowireTrait;
21+
22+
public function __construct(
23+
ConfigFactoryInterface $config_factory,
24+
private readonly Settings $settings,
25+
) {
26+
parent::__construct($config_factory);
27+
}
1728

1829
/**
1930
* {@inheritdoc}
@@ -26,34 +37,30 @@ public function getFormId(): string {
2637
* {@inheritdoc}
2738
*/
2839
protected function getEditableConfigNames(): array {
29-
return ['os2loop_cura_login.settings'];
40+
return [Settings::CONFIG_NAME];
3041
}
3142

3243
/**
3344
* {@inheritdoc}
3445
*/
3546
public function buildForm(array $form, FormStateInterface $form_state): array {
36-
$config = $this->config('os2loop_cura_login.settings');
47+
$settings = \Drupal::service(Settings::class);
3748
$form['signing_algorithm'] = [
3849
'#required' => TRUE,
3950
'#type' => 'select',
40-
'#options' => [
41-
'HS256' => 'HS256',
42-
'HS384' => 'HS384',
43-
'HS512' => 'HS512',
44-
],
51+
'#options' => Settings::SIGNING_ALGORITHMS,
4552
'#title' => $this->t('Signing algorithm'),
46-
'#default_value' => $config->get('signing_algorithm'),
53+
'#default_value' => $this->settings->getSigningAlgorithm(),
4754
];
4855

49-
$hasSigningSecret = !empty($config->get('signing_secret'));
56+
$hasSigningSecret = !empty($this->settings->getSigningSecret());
5057

5158
$form['signing_secret'] = [
5259
'#type' => 'textfield',
5360
'#size' => 128,
5461
'#required' => $hasSigningSecret,
5562
'#title' => $this->t('Signing secret'),
56-
'#default_value' => $config->get('signing_secret'),
63+
'#default_value' => $this->settings->getSigningSecret(),
5764
'#description' => !$hasSigningSecret
5865
? $this->t('Save the configuration to generate a random secret.')
5966
: '',
@@ -69,21 +76,21 @@ public function buildForm(array $form, FormStateInterface $form_state): array {
6976
$form['payload_name'] = [
7077
'#type' => 'textfield',
7178
'#title' => $this->t('Payload name'),
72-
'#default_value' => $config->get('payload_name') ?? 'payload',
79+
'#default_value' => $this->settings->getPayloadName(),
7380
'#description' => $this->t('Name of parameter used for payload'),
7481
];
7582

7683
$form['jwt_leeway'] = [
7784
'#type' => 'textfield',
7885
'#title' => $this->t('JWT leeway'),
79-
'#default_value' => $config->get('jwt_leeway') ?? 0,
86+
'#default_value' => $this->settings->getJwtLeeway(),
8087
];
8188

8289
$form['log_level'] = [
8390
'#type' => 'select',
8491
'#options' => RfcLogLevel::getLevels(),
8592
'#title' => $this->t('Log level'),
86-
'#default_value' => $config->get('log_level') ?? RfcLogLevel::ERROR,
93+
'#default_value' => $this->settings->getLogLevel(),
8794
];
8895

8996
$authenticationStartUrl = Url::fromRoute('os2loop_cura_login.start')->setAbsolute()->toString(TRUE)->getGeneratedUrl();
@@ -100,7 +107,7 @@ public function buildForm(array $form, FormStateInterface $form_state): array {
100107
'#markup' => $this->t('Use <a href=":url">:url</a> as <code>linkURL</code> for <core><code>postToGetLinkURL ≡ false</code>.', [':url' => $authenticationStartUrl]),
101108
];
102109

103-
if ($name = $config->get('payload_name')) {
110+
if ($name = $this->settings->getPayloadName()) {
104111
$authenticationStartUrl = Url::fromRoute('os2loop_cura_login.start', [$name => ''])->setAbsolute()->toString(TRUE)->getGeneratedUrl();
105112
$authenticationStartUrl = str_replace(urlencode(''), '', $authenticationStartUrl);
106113
$form['info']['#items'][] = [
@@ -117,15 +124,12 @@ public function buildForm(array $form, FormStateInterface $form_state): array {
117124
public function submitForm(array &$form, FormStateInterface $form_state): void {
118125
$secret = $form_state->getValue('signing_secret');
119126
if ($form_state->getValue('generate_new_secret')) {
120-
$secret = base64_encode((new Random())->string(64));
127+
$form_state->setValue('signing_secret', base64_encode((new Random())->string(64)));
121128
}
122-
$this->config('os2loop_cura_login.settings')
123-
->set('signing_algorithm', $form_state->getValue('signing_algorithm'))
124-
->set('signing_secret', $secret)
125-
->set('payload_name', $form_state->getValue('payload_name'))
126-
->set('jwt_leeway', $form_state->getValue('jwt_leeway'))
127-
->set('log_level', $form_state->getValue('log_level'))
128-
->save();
129+
/** @var \Drupal\os2loop_cura_login\Settings $settings */
130+
$settings = \Drupal::service(Settings::class);
131+
$settings->saveSettings($form_state);
132+
129133
parent::submitForm($form, $form_state);
130134
}
131135

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
<?php
2+
3+
namespace Drupal\os2loop_cura_login;
4+
5+
use Drupal\Core\Config\ConfigFactoryInterface;
6+
use Drupal\Core\Config\ImmutableConfig;
7+
use Drupal\Core\Form\FormStateInterface;
8+
use Drupal\Core\Logger\RfcLogLevel;
9+
10+
/**
11+
* Settings for OS2Loop Cura login.
12+
*/
13+
final class Settings {
14+
const string CONFIG_NAME = 'os2loop_cura_login.settings';
15+
16+
private const SETTING_SIGNING_SECRET = 'signing_secret';
17+
private const SETTING_SIGNING_ALGORITHM = 'signing_algorithm';
18+
private const SETTING_PAYLOAD_NAME = 'payload_name';
19+
private const SETTING_JWT_LEEWAY = 'jwt_leeway';
20+
private const SETTING_LOG_LEVEL = 'log_level';
21+
22+
const array SIGNING_ALGORITHMS = [
23+
'HS256' => 'HS256',
24+
'HS384' => 'HS384',
25+
'HS512' => 'HS512',
26+
];
27+
28+
/**
29+
* The config.
30+
*/
31+
private readonly ImmutableConfig $config;
32+
33+
/**
34+
* Constructor.
35+
*/
36+
public function __construct(
37+
private readonly ConfigFactoryInterface $configFactory,
38+
) {
39+
$this->config = $configFactory->get(self::CONFIG_NAME);
40+
}
41+
42+
/**
43+
* Get payload name.
44+
*/
45+
public function getPayloadName(): string {
46+
return $this->config->get('payload_name') ?? 'payload';
47+
}
48+
49+
/**
50+
* Get signing algorithm.
51+
*/
52+
public function getSigningAlgorithm(): string {
53+
return $this->config->get('signing_algorithm') ?? self::SIGNING_ALGORITHMS[array_key_first(self::SIGNING_ALGORITHMS)];
54+
}
55+
56+
/**
57+
* Get signing secret.
58+
*/
59+
public function getSigningSecret(): string {
60+
return $this->config->get('signing_secret') ?? '';
61+
}
62+
63+
/**
64+
* Get JWT leeway.
65+
*/
66+
public function getJwtLeeway(): int {
67+
return (int) $this->config->get('jwt_leeway');
68+
}
69+
70+
/**
71+
* Get log level.
72+
*/
73+
public function getLogLevel() {
74+
return (int) $this->config->get('log_level') ?? RfcLogLevel::ERROR;
75+
}
76+
77+
/**
78+
* Save settings.
79+
*/
80+
public function saveSettings(array|FormStateInterface $values): array {
81+
if ($values instanceof FormStateInterface) {
82+
$values = [
83+
self::SETTING_SIGNING_ALGORITHM => $values->getValue(self::SETTING_SIGNING_ALGORITHM),
84+
self::SETTING_SIGNING_SECRET => $values->getValue(self::SETTING_SIGNING_SECRET),
85+
self::SETTING_PAYLOAD_NAME => $values->getValue(self::SETTING_PAYLOAD_NAME),
86+
self::SETTING_JWT_LEEWAY => $values->getValue(self::SETTING_JWT_LEEWAY),
87+
self::SETTING_LOG_LEVEL => $values->getValue(self::SETTING_LOG_LEVEL),
88+
];
89+
}
90+
91+
// @todo validate values
92+
$config = $this->configFactory->getEditable(self::CONFIG_NAME);
93+
foreach ($values as $key => $value) {
94+
$config->set($key, $value);
95+
}
96+
$config->save();
97+
98+
return $config->get();
99+
}
100+
101+
}

0 commit comments

Comments
 (0)