• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daycry / auth / 44317717916

18 Nov 2026 01:49PM UTC coverage: 82.894% (+4.4%) from 78.462%
44317717916

Pull #79

github

web-flow
Merge 7c781daeb into 55dbf61d2
Pull Request #79: feat: security fixes, extension points and auth completion

1214 of 1370 new or added lines in 67 files covered. (88.61%)

12 existing lines in 5 files now uncovered.

6663 of 8038 relevant lines covered (82.89%)

97.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.64
/src/Controllers/BaseAuthController.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of Daycry Auth.
7
 *
8
 * (c) Daycry <daycry9@proton.me>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace Daycry\Auth\Controllers;
15

16
use App\Controllers\BaseController;
17
use CodeIgniter\HTTP\RedirectResponse;
18
use CodeIgniter\HTTP\ResponseInterface;
19
use Daycry\Auth\Authentication\Authenticators\Session;
20
use Daycry\Auth\Interfaces\AuthController;
21
use Daycry\Auth\Models\LoginModel;
22
use Daycry\Auth\Result;
23
use Daycry\Auth\Traits\BaseControllerTrait;
24
use Daycry\Auth\Traits\Viewable;
25

26
/**
27
 * Base Auth Controller that provides common functionality for all auth controllers
28
 *
29
 * Uses BaseControllerTrait for core functionality and implements
30
 * common patterns used across auth controllers.
31
 */
32
abstract class BaseAuthController extends BaseController implements AuthController
33
{
34
    use BaseControllerTrait;
35
    use Viewable;
36

37
    /**
38
     * Get CSRF token array for forms
39
     */
40
    protected function getTokenArray(): array
15 ✔
41
    {
42
        return $this->getToken();
15 ✔
43
    }
44

45
    /**
46
     * Check if user is already logged in and redirect if needed
47
     */
48
    protected function redirectIfLoggedIn(?string $redirectUrl = null): ?RedirectResponse
4 ✔
49
    {
50
        if (auth()->loggedIn()) {
4 ✔
51
            $url = $redirectUrl ?? config('Auth')->loginRedirect();
×
52

53
            return redirect()->to($url);
×
54
        }
55

56
        return null;
4 ✔
57
    }
58

59
    /**
60
     * Get validation rules for the specific controller
61
     * Must be implemented by child classes
62
     */
63
    abstract protected function getValidationRules(): array;
64

65
    /**
66
     * Validate request data with given rules
67
     */
68
    protected function validateRequest(array $data, array $rules): bool
42 ✔
69
    {
70
        return $this->validateData($data, $rules, [], config('Auth')->DBGroup);
42 ✔
71
    }
72

73
    /**
74
     * Handle validation errors with redirect
75
     */
76
    protected function handleValidationError(?string $route = null): ResponseInterface
4 ✔
77
    {
78
        if ($this->expectsJsonResponse()) {
4 ✔
79
            return $this->authJsonResponse(['status' => 'error', 'errors' => $this->validator->getErrors()], 422);
2 ✔
80
        }
81
        $route ??= $this->request->getPath();
2 ✔
82

83
        return redirect()->to($route)
2 ✔
84
            ->withInput()
2 ✔
85
            ->with('errors', $this->validator->getErrors());
2 ✔
86
    }
87

88
    /**
89
     * Handle successful action with redirect
90
     */
91
    protected function handleSuccess(string $redirectUrl, ?string $message = null): ResponseInterface
14 ✔
92
    {
93
        if ($this->expectsJsonResponse()) {
14 ✔
94
            if (($pending = $this->pendingMfaResponse()) !== null) {
3 ✔
95
                return $pending;
2 ✔
96
            }
97

98
            return $this->authJsonResponse(array_filter([
1 ✔
99
                'status'        => 'success',
1 ✔
100
                'authenticated' => auth('session')->loggedIn(),
1 ✔
101
                'redirect'      => $redirectUrl,
1 ✔
102
                'message'       => $message,
1 ✔
103
            ], static fn ($value): bool => $value !== null));
1 ✔
104
        }
105
        $redirect = redirect()->to($redirectUrl);
11 ✔
106

107
        if ($message) {
11 ✔
108
            $redirect = $redirect->with('message', $message);
2 ✔
109
        }
110

111
        return $redirect;
11 ✔
112
    }
113

114
    /**
115
     * Handle error with redirect
116
     */
117
    protected function handleError(string $route, string $error, bool $withInput = true): ResponseInterface
19 ✔
118
    {
119
        if ($this->expectsJsonResponse()) {
19 ✔
NEW
120
            return $this->authJsonResponse(['status' => 'error', 'message' => $error], 400);
×
121
        }
122
        $redirect = redirect()->to($route);
19 ✔
123

124
        if ($withInput) {
19 ✔
125
            $redirect = $redirect->withInput();
19 ✔
126
        }
127

128
        return $redirect->with('error', $error);
19 ✔
129
    }
130

131
    /**
132
     * Status-aware JSON error; HTML still calls the existing override hook.
133
     */
134
    protected function handleFailure(string $route, string $error, bool $withInput = true, int $statusCode = 400): ResponseInterface
21 ✔
135
    {
136
        return $this->expectsJsonResponse()
21 ✔
137
            ? $this->authJsonResponse(['status' => 'error', 'message' => $error], $statusCode)
2 ✔
138
            : $this->handleError($route, $error, $withInput);
21 ✔
139
    }
140

141
    /**
142
     * Get current session authenticator
143
     */
144
    protected function getSessionAuthenticator(): Session
35 ✔
145
    {
146
        return auth('session')->getAuthenticator();
35 ✔
147
    }
148

149
    /**
150
     * Check if current request has post-authentication action
151
     */
152
    protected function hasPostAuthAction(): bool
7 ✔
153
    {
154
        return $this->getSessionAuthenticator()->hasAction();
7 ✔
155
    }
156

157
    /**
158
     * Redirect to auth action if one exists
159
     */
160
    protected function redirectToAuthAction(): ResponseInterface
5 ✔
161
    {
162
        if ($this->expectsJsonResponse()) {
5 ✔
163
            return $this->authJsonResponse([
5 ✔
164
                'status'        => 'action_required',
5 ✔
165
                'authenticated' => false,
5 ✔
166
                'redirect'      => url_to('auth-action-show'),
5 ✔
167
            ], 202);
5 ✔
168
        }
169

UNCOV
170
        return redirect()->route('auth-action-show')->withCookies();
×
171
    }
172

173
    /**
174
     * Extract credentials from POST data for login
175
     */
176
    protected function extractLoginCredentials(): array
25 ✔
177
    {
178
        $credentials             = $this->authInput(setting('Auth.validFields')) ?? [];
25 ✔
179
        $credentials             = array_filter($credentials);
25 ✔
180
        $credentials['password'] = $this->authInput('password');
25 ✔
181

182
        return $credentials;
25 ✔
183
    }
184

185
    /**
186
     * Check if remember me is requested
187
     */
188
    protected function shouldRememberUser(): bool
8 ✔
189
    {
190
        return filter_var($this->authInput('remember'), FILTER_VALIDATE_BOOLEAN);
8 ✔
191
    }
192

193
    /**
194
     * Handle authentication result
195
     */
196
    protected function handleAuthResult(Result $result, string $failureRoute): ResponseInterface
8 ✔
197
    {
198
        if (! $result->isOK()) {
8 ✔
199
            return $this->handleFailure($failureRoute, $result->reason(), true, 401);
1 ✔
200
        }
201

202
        // Handle post-authentication action if exists
203
        if ($this->hasPostAuthAction()) {
7 ✔
204
            return $this->redirectToAuthAction();
4 ✔
205
        }
206

207
        // Redirect to success page
208
        $response = $this->handleSuccess(
3 ✔
209
            config('Auth')->loginRedirect(),
3 ✔
210
        );
3 ✔
211

212
        return $response instanceof RedirectResponse ? $response->withCookies() : $response;
3 ✔
213
    }
214

215
    /**
216
     * Do not report first-factor sessions as fully authenticated under MFA policy.
217
     */
218
    protected function pendingMfaResponse(): ?ResponseInterface
7 ✔
219
    {
220
        if (! $this->expectsJsonResponse() || ! auth('session')->loggedIn()) {
7 ✔
NEW
221
            return null;
×
222
        }
223
        $user   = auth('session')->user();
7 ✔
224
        $policy = service('mfaPolicy');
7 ✔
225
        if ($user === null || ! $policy->requires($user)) {
7 ✔
226
            return null;
3 ✔
227
        }
228
        $enrollment = $policy->enrollmentRequired($user);
4 ✔
229
        if (! $enrollment && (! $policy->hasFactor($user) || $policy->verified($user))) {
4 ✔
NEW
230
            return null;
×
231
        }
232

233
        return $this->authJsonResponse([
4 ✔
234
            'status'        => 'action_required',
4 ✔
235
            'authenticated' => false,
4 ✔
236
            'code'          => $enrollment ? 'mfa_enrollment_required' : 'mfa_verification_required',
4 ✔
237
            'redirect'      => url_to($enrollment ? 'security' : 'password-confirm-show'),
4 ✔
238
        ], 202);
4 ✔
239
    }
240

241
    /**
242
     * Whether the client explicitly requests JSON or supplied a JSON body.
243
     */
244
    protected function expectsJsonResponse(): bool
52 ✔
245
    {
246
        return $this->request->is('json')
52 ✔
247
            || $this->request->negotiate('media', ['text/html', 'application/json']) === 'application/json';
52 ✔
248
    }
249

250
    /**
251
     * @return array<string, mixed> Validated later by each endpoint's rules.
252
     */
253
    protected function authRequestData(): array
58 ✔
254
    {
255
        return $this->request->is('json') ? (array) $this->content : $this->request->getPost();
58 ✔
256
    }
257

258
    /**
259
     * Read only the request body, never query-string or cookie credentials.
260
     */
261
    protected function authInput(array|string|null $key = null): mixed
58 ✔
262
    {
263
        $data = $this->authRequestData();
58 ✔
264
        if ($key === null) {
58 ✔
265
            return $data;
25 ✔
266
        }
267
        if (is_array($key)) {
55 ✔
268
            return array_intersect_key($data, array_flip($key));
27 ✔
269
        }
270
        $value = $data[$key] ?? null;
53 ✔
271

272
        return is_scalar($value) ? $value : null;
53 ✔
273
    }
274

275
    /**
276
     * @param array<string, mixed> $data
277
     */
278
    protected function authJsonResponse(array $data, int $statusCode = 200): ResponseInterface
15 ✔
279
    {
280
        return $this->response->setStatusCode($statusCode)
15 ✔
281
            ->setHeader('Cache-Control', 'no-store')
15 ✔
282
            ->setJSON($data + ['token' => $this->getTokenArray()]);
15 ✔
283
    }
284

285
    /**
286
     * Records a login/action attempt in the login log.
287
     *
288
     * @param string          $type       Identity type (e.g. Session::ID_TYPE_MAGIC_LINK)
289
     * @param string          $identifier The identifier used (email, token, etc.)
290
     * @param bool            $success    Whether the attempt was successful
291
     * @param int|string|null $userId     The user ID if known
292
     */
293
    protected function recordLoginAttempt(
15 ✔
294
        string $type,
295
        string $identifier,
296
        bool $success,
297
        $userId = null,
298
    ): void {
299
        /** @var LoginModel $loginModel */
300
        $loginModel = model(LoginModel::class);
15 ✔
301

302
        $loginModel->recordLoginAttempt(
15 ✔
303
            $type,
15 ✔
304
            $identifier,
15 ✔
305
            $success,
15 ✔
306
            $this->request->getIPAddress(),
15 ✔
307
            (string) $this->request->getUserAgent(),
15 ✔
308
            $userId,
15 ✔
309
        );
15 ✔
310
    }
311
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc