Skip to content

Inject auth config into adapters via AuthFactory#451

Merged
armanist merged 2 commits intosoftberg:masterfrom
armanist:449-Enhancement-Inject-auth-config-into-adapters-via-AuthFactory
Apr 6, 2026
Merged

Inject auth config into adapters via AuthFactory#451
armanist merged 2 commits intosoftberg:masterfrom
armanist:449-Enhancement-Inject-auth-config-into-adapters-via-AuthFactory

Conversation

@armanist
Copy link
Copy Markdown
Member

@armanist armanist commented Apr 6, 2026

Closes #449

Summary by CodeRabbit

  • New Features

    • Remember-me cookie lifetime is now configurable via environment settings (default ~30 days).
  • Refactor

    • Authentication components now accept and use injected configuration at initialization for consistent behavior.
  • Tests

    • Test suite updated to initialize auth components with configuration and includes a test verifying configurable remember-me lifetime.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 6, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.66%. Comparing base (57f3dcd) to head (8153e60).
⚠️ Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master     #451   +/-   ##
=========================================
  Coverage     82.65%   82.66%           
  Complexity     2831     2831           
=========================================
  Files           243      243           
  Lines          7552     7556    +4     
=========================================
+ Hits           6242     6246    +4     
  Misses         1310     1310           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 6, 2026

📝 Walkthrough

Walkthrough

AuthFactory now injects the full auth config array into adapters. JwtAuthAdapter and SessionAuthAdapter accept and store array $config; AuthTrait gains a protected $config property and reads config values from it. Templates, tests, and test configs were updated to pass and use the injected config.

Changes

Cohort / File(s) Summary
Auth Adapters
src/Auth/Adapters/JwtAuthAdapter.php, src/Auth/Adapters/SessionAuthAdapter.php
Constructors extended to accept array $config and store it. SessionAuthAdapter uses $this->config['session']['remember_lifetime'] ?? default for remember-cookie lifetime (constant replaced).
Auth Factory
src/Auth/Factories/AuthFactory.php
createInstance() reads full auth config once and passes it to adapter constructors for both JWT and non-JWT flows.
Auth Trait
src/Auth/Traits/AuthTrait.php
Added protected array $config = []; and replaced config()->get('auth.*') reads with $this->config lookups using null-coalescing defaults.
Configuration Templates
src/Module/Templates/DemoApi/src/config/auth.php.tpl, src/Module/Templates/DemoWeb/src/config/auth.php.tpl
Added session.remember_lifetime entry sourced from env('REMEMBER_LIFETIME', 2592000).
Test Config
tests/_root/shared/config/auth.php
Added session.remember_lifetime with same env/default.
Tests
tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php, tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php, tests/Unit/Auth/AuthTest.php
Tests updated to pass (array) config()->get('auth') into adapter constructors via new private factory methods; added test asserting configurable remember_lifetime.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(220,230,241,0.5)
    participant Factory as AuthFactory
  end
  rect rgba(195,230,204,0.5)
    participant Config as Config Store
  end
  rect rgba(255,224,178,0.5)
    participant Adapter as Auth Adapter (JWT/Session)
  end
  rect rgba(248,202,202,0.5)
    participant Trait as AuthTrait
  end

  Config->>Factory: get('auth') (array)
  Factory->>Adapter: new Adapter(..., authConfig)
  Adapter->>Trait: set $this->config = authConfig
  Adapter->>Trait: read two_fa / otp_expires / session.remember_lifetime via $this->config
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • andrey-smaelov

Poem

🐰 A factory nibbled at the config root,
Passed crumbs to each adapter, neat and cute.
No globals munched, no surprises found,
Remember tokens now sleep on configurable ground.
Hoppity-hop — tests and templates sing! 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the primary change: injecting auth config into adapters via AuthFactory, which is the main refactoring objective.
Linked Issues check ✅ Passed All nine coding objectives from issue #449 are met: $config property added to AuthTrait, both adapters updated with config parameter, AuthFactory passes config, remember_lifetime made configurable, templates updated, tests pass config and verify configurability.
Out of Scope Changes check ✅ Passed All changes directly support the stated objectives. Configuration key renames (REMEMBER_TOKEN_LIFETIME→DEFAULT_REMEMBER_LIFETIME), null-coalescing defaults, test refactoring with factory methods, and test additions are all in scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php (1)

73-75: Consider extracting config-mutate + adapter-recreate into a helper.

The same pattern repeats in several tests. A tiny helper would reduce duplication and keep these scenarios easier to maintain.

Also applies to: 163-163, 178-178, 189-189, 198-198

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php` around lines 73 - 75, Create
a small helper on the test class to DRY the repeated pattern of mutating the
config and recreating the adapter: replace repeated config()->set('auth.two_fa',
...); $this->jwtAuth = $this->createJwtAuth(); with a single method (e.g.,
private function setTwoFaAndRecreateAdapter(bool $enabled)) that calls
config()->set('auth.two_fa', $enabled) and then assigns $this->jwtAuth =
$this->createJwtAuth(); update all test sites (around lines referencing
createJwtAuth and config()->set('auth.two_fa')) to call that helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Auth/Adapters/JwtAuthAdapter.php`:
- Around line 43-54: The public constructor JwtAuthAdapter::__construct
currently requires a fifth parameter $config which breaks backward
compatibility; make the $config parameter optional by defaulting it to an empty
array in the constructor signature and ensure the body continues to assign
$this->config = $config so existing callers with four arguments continue to work
while in-repo callers can still pass config.

In `@tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php`:
- Around line 233-241: The test testWebRememberTokenLifetimeIsConfigurable
currently only asserts cookie()->has('remember_token') and doesn't verify the
configured lifetime; update the test to retrieve the remember_token cookie
(after $this->sessionAuth->signin(...) ) and assert its expiry/Max-Age matches
the configured value (config('auth.session.remember_lifetime') or the literal
86400) so the test actually validates that SessionAuthAdapter/signin honors the
remember_lifetime setting.

---

Nitpick comments:
In `@tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php`:
- Around line 73-75: Create a small helper on the test class to DRY the repeated
pattern of mutating the config and recreating the adapter: replace repeated
config()->set('auth.two_fa', ...); $this->jwtAuth = $this->createJwtAuth(); with
a single method (e.g., private function setTwoFaAndRecreateAdapter(bool
$enabled)) that calls config()->set('auth.two_fa', $enabled) and then assigns
$this->jwtAuth = $this->createJwtAuth(); update all test sites (around lines
referencing createJwtAuth and config()->set('auth.two_fa')) to call that helper.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1cd2d67b-962e-4a6c-94b6-9bfa4b6ccd49

📥 Commits

Reviewing files that changed from the base of the PR and between 57f3dcd and 17dd974.

📒 Files selected for processing (10)
  • src/Auth/Adapters/JwtAuthAdapter.php
  • src/Auth/Adapters/SessionAuthAdapter.php
  • src/Auth/Factories/AuthFactory.php
  • src/Auth/Traits/AuthTrait.php
  • src/Module/Templates/DemoApi/src/config/auth.php.tpl
  • src/Module/Templates/DemoWeb/src/config/auth.php.tpl
  • tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php
  • tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php
  • tests/Unit/Auth/AuthTest.php
  • tests/_root/shared/config/auth.php

@armanist armanist added enhancement New feature or request help wanted Extra attention is needed labels Apr 6, 2026
@armanist armanist added this to the 3.0.0 milestone Apr 6, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/Auth/Adapters/SessionAuthAdapter.php (1)

208-213: Consider explicit type casting for the cookie lifetime parameter.

The config value retrieved from $this->config['session']['remember_lifetime'] is of type mixed (per the array<string, mixed> typing). While Cookie::set() expects int $time, PHP will implicitly coerce the value. If an invalid or non-numeric value is provided in config, it could silently become 0, causing immediate cookie expiration.

Additionally, if $this->config['session'] exists but is not an array, accessing ['remember_lifetime'] on it would cause an error.

🛡️ Suggested defensive handling
-        $rememberLifetime = $this->config['session']['remember_lifetime'] ?? self::DEFAULT_REMEMBER_LIFETIME;
+        $sessionConfig = $this->config['session'] ?? [];
+        $rememberLifetime = (int) ($sessionConfig['remember_lifetime'] ?? self::DEFAULT_REMEMBER_LIFETIME);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Auth/Adapters/SessionAuthAdapter.php` around lines 208 - 213, The
retrieved remember lifetime may be non-array or non-numeric; update the logic
around $this->config['session'] and the $rememberLifetime value used for
cookie()->set so it defensively ensures $this->config['session'] is an array,
extracts a numeric value for 'remember_lifetime', falls back to
self::DEFAULT_REMEMBER_LIFETIME when missing/invalid, and explicitly casts to
int before passing to cookie()->set (the cookie key is
$this->keyFields[AuthKeys::REMEMBER_TOKEN]); ensure the final value passed to
Cookie::set() is a validated int to avoid silent zero/expiry.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/Auth/Adapters/SessionAuthAdapter.php`:
- Around line 208-213: The retrieved remember lifetime may be non-array or
non-numeric; update the logic around $this->config['session'] and the
$rememberLifetime value used for cookie()->set so it defensively ensures
$this->config['session'] is an array, extracts a numeric value for
'remember_lifetime', falls back to self::DEFAULT_REMEMBER_LIFETIME when
missing/invalid, and explicitly casts to int before passing to cookie()->set
(the cookie key is $this->keyFields[AuthKeys::REMEMBER_TOKEN]); ensure the final
value passed to Cookie::set() is a validated int to avoid silent zero/expiry.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fc7a3dcf-1422-4e6a-89fd-9233b56c98d8

📥 Commits

Reviewing files that changed from the base of the PR and between 17dd974 and 8153e60.

📒 Files selected for processing (2)
  • src/Auth/Adapters/JwtAuthAdapter.php
  • src/Auth/Adapters/SessionAuthAdapter.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Auth/Adapters/JwtAuthAdapter.php

@armanist armanist merged commit 22e667c into softberg:master Apr 6, 2026
7 checks passed
@armanist armanist deleted the 449-Enhancement-Inject-auth-config-into-adapters-via-AuthFactory branch April 6, 2026 10:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request help wanted Extra attention is needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhancement: Inject auth config into adapters via AuthFactory

2 participants