<?php
declare(strict_types=1);
namespace SHServ\Integrations\GAuth;
use SHServ\Integrations\GAuth\AuthService;
use SHServ\Integrations\GAuth\PermissionResolver;
trait AuthControllerTrait
{
/**
* Require authenticated user. Returns error response if not auth.
*/
protected function require_auth(): ?string
{
if (!isset($_SESSION['shserv_auth_token'])) {
return $this->utils()->response_error('unauthenticated', [], [], 401);
}
return null;
}
/**
* Require specific permission. Returns error response if denied.
*/
protected function require_permission(string $permissionSlug): ?string
{
$authError = $this->require_auth();
if ($authError !== null) {
return $authError;
}
$user = $this->get_current_user();
if (!$user) {
return $this->utils()->response_error('unauthenticated', [], [], 401);
}
$resolver = new PermissionResolver();
if (!$resolver->has($user['id'], $user['system_role'], $permissionSlug)) {
return $this->utils()->response_error('permission_denied', [$permissionSlug], [], 403);
}
return null;
}
/**
* Get current user data from session.
*/
protected function get_current_user(): ?array
{
$userId = $_SESSION['shserv_user_id'] ?? null;
if (!$userId) {
return null;
}
$tb = app()->thin_builder;
$result = $tb->select('shserv_users', ['id', 'gauth_user_id', 'email', 'display_name', 'avatar_url', 'system_role', 'status'], [['id', '=', $userId]]);
return $result ? $result[0] : null;
}
/**
* Get effective permissions for current user.
*/
protected function get_current_permissions(): array
{
$user = $this->get_current_user();
if (!$user) {
return [];
}
$resolver = new PermissionResolver();
return $resolver->resolve((int) $user['id'], $user['system_role']);
}
}