-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseController.php
More file actions
54 lines (46 loc) · 1.39 KB
/
BaseController.php
File metadata and controls
54 lines (46 loc) · 1.39 KB
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
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class BaseController extends ResourceController
{
protected $format = 'json';
protected function getJWTSecret(): string
{
return getenv('app.JWT_SECRET') ?: 'dev_secret_change_me';
}
protected function getJWTExpireMinutes(): int
{
return (int)(getenv('app.JWT_EXPIRES_MIN') ?: 1440);
}
protected function makeToken(array $payload): string
{
$now = time();
$exp = $now + ($this->getJWTExpireMinutes() * 60);
$data = array_merge($payload, ['iat' => $now, 'exp' => $exp]);
return JWT::encode($data, $this->getJWTSecret(), 'HS256');
}
protected function getUserFromToken()
{
$auth = $this->request->getHeaderLine('Authorization');
if (!$auth || stripos($auth, 'Bearer ') !== 0) {
return null;
}
$token = trim(substr($auth, 7));
try {
$decoded = JWT::decode($token, new Key($this->getJWTSecret(), 'HS256'));
return (array)$decoded;
} catch (\Throwable $e) {
return null;
}
}
protected function requireAuth()
{
$user = $this->getUserFromToken();
if (!$user) {
return $this->failUnauthorized('Invalid or missing token.');
}
return $user;
}
}