<?php
declare(strict_types=1);
namespace SHServ\Controllers;
use SHServ\Integrations\GAuth\AuthControllerTrait;
use SHServ\Integrations\GAuth\AuthService;
use SHServ\Integrations\GAuth\PermissionResolver;
use SHServ\Integrations\GAuth\UserResolver;
class AuthController extends \SHServ\Middleware\Controller
{
use AuthControllerTrait;
/**
* GET /auth/login
* Redirect user to gnexus-auth authorization page.
*/
public function login()
{
$service = new AuthService();
$returnTo = $_GET['return_to'] ?? '/';
$url = $service->buildLoginUrl($returnTo);
return $this->utils()->redirect($url);
}
/**
* GET /auth/callback
* Handle OAuth callback from gnexus-auth.
*/
public function callback()
{
$code = isset($_GET['code']) ? (string) $_GET['code'] : '';
$state = isset($_GET['state']) ? (string) $_GET['state'] : '';
if ($code === '' || $state === '') {
return $this->utils()->response_error('invalid_callback');
}
$service = new AuthService();
try {
$user = $service->handleCallback($code, $state);
} catch (\GNexus\GAuth\Exception\GAuthException $e) {
return $this->utils()->response_error('auth_failed', [], ['message' => $e->getMessage()]);
}
$resolver = new UserResolver();
$localUserId = $resolver->resolve($user);
$_SESSION['shserv_user_id'] = $localUserId;
// Redirect back to app
$context = $_SESSION['gauth_state'][$state]['context'] ?? [];
$returnTo = $context['return_to'] ?? '/';
return $this->utils()->redirect($returnTo);
}
/**
* POST /auth/logout
*/
public function logout()
{
$service = new AuthService();
$service->logout();
return $this->utils()->response_success();
}
/**
* GET /auth/me
* Return current authenticated user + effective permissions.
*/
public function me()
{
$user = $this->get_current_user();
if (!$user) {
return $this->utils()->response_error('not_found_any_sessions', [], [], 401);
}
$permissions = $this->get_current_permissions();
return $this->utils()->response_success([
'user' => [
'id' => $user['id'],
'gauth_user_id' => $user['gauth_user_id'],
'email' => $user['email'],
'display_name' => $user['display_name'],
'avatar_url' => $user['avatar_url'],
'system_role' => $user['system_role'],
'status' => $user['status'],
],
'permissions' => $permissions,
]);
}
/**
* POST /auth/refresh
* Refresh access token using stored refresh token.
*/
public function refresh()
{
$sessionToken = $_SESSION['shserv_auth_token'] ?? null;
if (!$sessionToken) {
return $this->utils()->response_error('not_found_any_sessions', [], [], 401);
}
$service = new AuthService();
$tokenSet = $service->refreshAccessToken($sessionToken);
if (!$tokenSet) {
return $this->utils()->response_error('session_expired', [], [], 401);
}
return $this->utils()->response_success([
'access_token' => $tokenSet->accessToken,
'expires_in' => $tokenSet->expiresIn,
]);
}
}