/
AbstractBasicAuthMiddleware.php
executable file
·60 lines (48 loc) · 1.48 KB
/
AbstractBasicAuthMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace Laravel\Foundation\Abstracts;
use Closure;
use Illuminate\Support\Str;
abstract class AbstractBasicAuthMiddleware
{
protected string $key;
protected string $header = 'authorization';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public final function handle($request, Closure $next)
{
$header = $request->header($this->header);
if (!Str::startsWith($header, 'Basic ')) {
return $this->generateError();
}
$encoded = Str::replaceFirst('Basic ', '', $header);
$decoded = base64_decode($encoded, true);
if (!$decoded) {
return $this->generateError();
}
$decoded = explode(':', $decoded);
if (count($decoded) !== 2 || empty($decoded[0]) || empty($decoded[1])) {
return $this->generateError();
}
if ($this->getUserName() !== $decoded[0] || $this->getUserPassword() !== $decoded[1]) {
return $this->generateError();
}
return $next($request);
}
protected function generateError(): mixed
{
return response('Unauthorized', 401);
}
protected function getUserName(): string
{
return config('auth.basic.' . $this->key . '.user');
}
protected function getUserPassword(): string
{
return config('auth.basic.' . $this->key . '.password');
}
}