Fix subuser token confusion in user auth flow

This commit is contained in:
Jeppe B
2026-06-01 22:35:24 +02:00
parent dd4c9da86c
commit fd4ec3dda2
2 changed files with 10 additions and 31 deletions
+9 -11
View File
@@ -100,9 +100,13 @@ class authentication implements authentication_i
public function validate_token(string $token): bool
{
// First: try validating as a classic user auth token
$dbToken = (new tokens_o())->getToken($token);
if ($dbToken && $dbToken->id) {
return true;
try {
$dbToken = (new tokens_o())->getToken($token);
if ($dbToken && $dbToken->id && $dbToken->type->value() === 'AUTH_TOKEN') {
return true;
}
} catch (Exception $e) {
// Ignore and continue with subuser session validation.
}
// Fallback: try validating as a subuser session token
$subuser = (new subusers_o())->getSubuserBySessionToken($token);
@@ -134,14 +138,8 @@ class authentication implements authentication_i
if (!$token->id) {
return false;
}
if ($token->type->value() === "AUTH_TOKEN_SUBUSER") {
// Get the customer number from the headers
if (!isset($headers['X-Customer-Number'])) {
return false;
}
$customer_number = (int)$headers['X-Customer-Number'];
// Get the user by the customer number
return (new users_o())->getUserByCustomerNumber($customer_number);
if ($token->type->value() !== 'AUTH_TOKEN') {
return false;
}
// Get the user from the database
return (new users_o())->getUserById($token->user_id->value());
+1 -20
View File
@@ -271,9 +271,6 @@ class subusers_o extends db
$session_token = bin2hex(random_bytes(32));
$this->cache('session_token:' . $session_token, $this->id, 'subuser_sessions');
$this->setCachedExpiration('session_token:' . $session_token, 7 * 24 * 60 * 60, 'subuser_sessions'); // Set the session to expire after 7 days
// Add the token
$tokens_o = new tokens_o();
$tokens_o->create($this->id, $session_token, 'AUTH_TOKEN_SUBUSER');
return $session_token;
}
@@ -292,22 +289,6 @@ class subusers_o extends db
$subuser->getObjectProperties();
return $subuser;
}
// Fallback: resolve via tokens table if cache is missing/expired
try {
// tokens_o::getToken() might throw Exception if not found
$tok = (new tokens_o())->getToken($token);
if ($tok && $tok->id && $tok->type->value() === 'AUTH_TOKEN_SUBUSER') {
$resolvedId = (int)$tok->user_id->value();
// Re-cache mapping for future lookups (7 days to match session lifetime)
$this->cache($cache_key, $resolvedId, $cache_object_id);
$this->setCachedExpiration($cache_key, 7 * 24 * 60 * 60, $cache_object_id);
$subuser = (new subusers_o())->select($resolvedId);
$subuser->getObjectProperties();
return $subuser;
}
} catch (Exception $e) {
// Token not found or other error; treat as missing
}
return null;
}
@@ -332,4 +313,4 @@ class subusers_o extends db
$grant = new subuser_user_grant((int)$this->id, (int)$customer_number);
return $grant->hasNode($permission_node_key);
}
}
}