Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
85.71% |
12 / 14 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| BaseController | |
85.71% |
12 / 14 |
|
50.00% |
2 / 4 |
5.07 | |
0.00% |
0 / 1 |
| initController | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
2 | |||
| isAdmin | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| isCoach | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| forbidden | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Controllers; |
| 4 | |
| 5 | use CodeIgniter\Controller; |
| 6 | use CodeIgniter\HTTP\RequestInterface; |
| 7 | use CodeIgniter\HTTP\ResponseInterface; |
| 8 | use Psr\Log\LoggerInterface; |
| 9 | |
| 10 | /** |
| 11 | * BaseController provides a convenient place for loading components |
| 12 | * and performing functions that are needed by all your controllers. |
| 13 | * |
| 14 | * Extend this class in any new controllers: |
| 15 | * ``` |
| 16 | * class Home extends BaseController |
| 17 | * ``` |
| 18 | * |
| 19 | * For security, be sure to declare any new methods as protected or private. |
| 20 | */ |
| 21 | abstract class BaseController extends Controller |
| 22 | { |
| 23 | protected $helpers = ['form', 'url', 'text', 'academy', 'vite']; |
| 24 | |
| 25 | protected mixed $currentUser = null; |
| 26 | protected array $currentRoles = []; |
| 27 | protected ?string $primaryRole = null; |
| 28 | |
| 29 | /** |
| 30 | * @return void |
| 31 | */ |
| 32 | public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void |
| 33 | { |
| 34 | parent::initController($request, $response, $logger); |
| 35 | |
| 36 | if (auth()->loggedIn()) { |
| 37 | $this->currentUser = auth()->user(); |
| 38 | $authorization = service('authorization'); |
| 39 | $this->currentRoles = $authorization->getRolesForUser((int) $this->currentUser->id); |
| 40 | $this->primaryRole = $authorization->getPrimaryRole((int) $this->currentUser->id); |
| 41 | } |
| 42 | |
| 43 | service('renderer')->setVar('authUser', $this->currentUser); |
| 44 | service('renderer')->setVar('authRoles', $this->currentRoles); |
| 45 | service('renderer')->setVar('primaryRole', $this->primaryRole); |
| 46 | } |
| 47 | |
| 48 | protected function isAdmin(): bool |
| 49 | { |
| 50 | return in_array('admin', $this->currentRoles, true); |
| 51 | } |
| 52 | |
| 53 | protected function isCoach(): bool |
| 54 | { |
| 55 | return in_array('coach', $this->currentRoles, true); |
| 56 | } |
| 57 | |
| 58 | protected function forbidden(string $message = 'Nu ai permisiunea necesara pentru aceasta sectiune.'): ResponseInterface |
| 59 | { |
| 60 | return $this->response |
| 61 | ->setStatusCode(ResponseInterface::HTTP_FORBIDDEN) |
| 62 | ->setBody(view('errors/html/error_403', ['message' => $message])); |
| 63 | } |
| 64 | } |