class RoleHelper
{
public static function isGuest(): bool
{
guest=\Yii::app->user->isGuest ? true : false;
code
return (bool) $guest;
}
public static function userIdentity(): IdentityInterface|null
{
if (self::isGuest())
{
return null;
}
$identity = \Yii::$app->user->identity;
if ($identity instanceof IdentityInterface)
{
return $identity;
}
// Defensive fallback: If identity is not instance, treat as guest
return null;
}
public static function isAdmin(): bool
{
if (self::isGuest())
{
return false;
}
$identity = self::userIdentity();
if ($identity === null || empty($identity->email))
{
return false;
}
$userId = $identity->id;
if (self::hasRole($userId) != 'appAdmin')
{
return false;
}
$ip = self::userIp();
$email = $identity->email;
// Use both role and IP/email match for admin
return \Yii::$app->authManager->checkAccess(self::userId(), 'appAdmin')
&& RBAMHelper::isAdmin($email, $ip);
}
public static function hasRole($userId): string
{
$authManager = \Yii::$app->authManager;
if ($authManager->checkAccess($userId, 'appAdmin'))
{
return \Yii::t('app', 'appAdmin');
}
elseif ($authManager->checkAccess($userId, 'appSupport'))
{
return \Yii::t('app', 'appSupport');
}
elseif ($authManager->checkAccess($userId, 'userAssist'))
{
return \Yii::t('app', 'userAssist');
}
else
{
return \Yii::t('app', 'userOwner');
}
}
Assistant
}
class RBAMHelper
{
/**
* Checks if an IP is in the list of allowed IPs, including support for CIDR notation.
* @param string[] allowedIpsArrayofallowedIPaddressesorCIDRranges.∗@paramstringip IP address to check.
* @return bool True if IP matches any allowed IP or subnet, false otherwise.
*/
protected static function ipInRangeArray(array allowedIps,stringip): bool
{
foreach (allowedIpsasallowedIp)
{
if (self::ipMatches(ip,allowedIp))
{
return true;
}
}
code
return false;
}
/**
* Determines whether a single IP matches an allowed IP or CIDR subnet.
* @param string $ip IP address to check.
* @param string $allowedIp IP address or subnet in CIDR notation.
* @return bool True if $ip is within $allowedIp or equal to it.
*/
protected static function ipMatches(string $ip, string $allowedIp): bool
{
// If no CIDR mask given, treat as single IP
if (strpos($allowedIp, '/') === false)
{
return filter_var($ip, FILTER_VALIDATE_IP) && $ip === $allowedIp;
}
// CIDR subnet check
list($subnet, $mask) = explode('/', $allowedIp);
// Invalid IP format
if (!filter_var($ip, FILTER_VALIDATE_IP) || !filter_var($subnet, FILTER_VALIDATE_IP))
{
return false;
}
$ipLong = ip2long($ip);
$subnetLong = ip2long($subnet);
$maskLong = ~((1 << (32 - intval($mask))) - 1);
return ($ipLong & $maskLong) === ($subnetLong & $maskLong);
}
/**
* Checks if the given email belongs to an admin user and the IP is allowed.
* @param string $email User email to check.
* @param string|null $ip IP address of the user (optional but recommended).
* @return bool True if user is an admin and IP is allowed.
*/
public static function isAdmin(string $email, ?string $ip = null): bool
{
$adminUsers = ParamHelper::get('app.user.admin', []);
//$adminUsers = \Yii::$app->params['app.user.admin'] ?? [];
// If email not configured as admin user, fail fast
if (!isset($adminUsers[$email]))
{
return false;
}
// Require IP for strict checking; reject if missing
if ($ip === null)
{
return false;
}
$allowedIps = $adminUsers[$email];
// Return true if IP matches any allowed IP or subnet
return self::ipInRangeArray($allowedIps, $ip);
}
/**
* Checks if the given email belongs to a support user and the IP is allowed.
* @param string $email User email to check.
* @param string|null $ip IP address of the user (optional but recommended).
* @return bool True if user is support and IP is allowed.
*/
public static function isSupport(string $email, ?string $ip = null): bool
{
$supportUsers = ParamHelper::get('app.user.support', []);
//$supportUsers = \Yii::$app->params['app.user.support'] ?? [];
if (!isset($supportUsers[$email]))
{
return false;
}
if ($ip === null)
{
return false;
}
$allowedIps = $supportUsers[$email];
return self::ipInRangeArray($allowedIps, $ip);
}
Let's carefully review the isAdmin() method from RoleHelper alongside the related RBAMHelper and surrounding code to check correctness.
isAdmin() method analysis:
php
public static function isAdmin(): bool
{
if (self::isGuest())
{
return false;
}
$identity = self::userIdentity();
if ($identity === null || empty($identity->email))
{
return false;
}
$userId = $identity->id;
if (self::hasRole($userId) != 'appAdmin')
{
return false;
}
$ip = self::userIp();
$email = $identity->email;
// Use both role and IP/email match for admin
return \Yii::$app->authManager->checkAccess(self::userId(), 'appAdmin')
&& RBAMHelper::isAdmin($email, $ip);
}
Step-by-step evaluation:
Check guest:
Returns false if user is a guest → good.
Get user identity and check for null / email emptiness:
This ensures there's a logged-in user with an email → good.
Get user ID, verify role with hasRole($userId) != 'appAdmin':
This returns false if the user role is not appAdmin (translated string).
IMPORTANT: hasRole returns translated strings (e.g. \Yii::t('app', 'appAdmin')), so the comparison works only if the translation of appAdmin equals 'appAdmin'.
Possible issue here: direct equality check vs translation strings may cause issues.
Ideally, hasRole() should return consistent machine-readable role IDs, not translated strings, or comparison should use translated values.
Retrieve user IP with self::userIp() (not shown in code, assuming works).
Check Yii2 authManager checkAccess with self::userId() (presumably current user ID) and appAdmin permission:
This is a second role check with Yii authManager - redundant with hasRole() but good for extra safety.
Use of self::userId() assumes it's the same as $userId obtained earlier; if not, consistency might break.
Call RBAMHelper::isAdmin(email,ip) to confirm user email is configured as admin with allowed IPs:
This enforces email+IP restriction from params configuration → a nice additional check.
Additional comments / potential issues:
hasRole() returning translated string:
php
public static function hasRole($userId): string
{
$authManager = \Yii::$app->authManager;
if ($authManager->checkAccess($userId, 'appAdmin'))
{
return \Yii::t('app', 'appAdmin'); // returns a translated string, e.g. "appAdmin"
}
elseif ($authManager->checkAccess($userId, 'appSupport'))
{
return \Yii::t('app', 'appSupport');
}
elseif ($authManager->checkAccess($userId, 'userAssist'))
{
return \Yii::t('app', 'userAssist');
}
else
{
return \Yii::t('app', 'userOwner');
}
}
If the translations for these keys don't directly map to the keys themselves (e.g. 'appAdmin' translates to 'Administrator'), then the comparison:
php
if (self::hasRole($userId) != 'appAdmin')
will always fail.
Suggestion: Either compare to the translated string (get translation of 'appAdmin' key), or better - return the actual role keys ('appAdmin', 'appSupport', etc.) unmodified from hasRole() and translate only when displaying to users.
Possible inconsistency between self::userId() and $userId from $identity->id:
In isAdmin(), checkAccess is called with self::userId() but hasRole() is called with $userId.
If self::userId() is a different method or returns different data, this may generate inconsistent results.
Ensure self::userId() returns the identity ID associated with the current logged-in user.
self::userIp() is not shown:
Assuming it reliably gets the client IP, otherwise RBAMHelper::isAdmin might fail.
expects an explicit IP to function:
Conclusion
Yes, the approach in isAdmin() mostly looks correct in logic:
Checks login status → gets identity.
Confirms user has admin role.
Confirms user is allowed per RBAC and extra email + IP whitelist.
But the following improvements are needed to avoid subtle bugs:
Fix role name comparison:
Replace:
php
if (self::hasRole($userId) != 'appAdmin')
with either:
php
if (self::hasRole($userId) != \Yii::t('app', 'appAdmin'))
or ideally, modify hasRole() to return raw role keys and compare here directly with 'appAdmin'.
Validate self::userId() returns the same user id as $identity->id.
Optionally remove redundant call to hasRole(), rely only on authManager->checkAccess().
Sample fixed snippet for isAdmin() condition:
php
// Assuming hasRole() returns translated string, compare with translated string:
if (self::hasRole($userId) !== \Yii::t('app', 'appAdmin'))
{
return false;
}
Or better, modify hasRole:
php
public static function hasRole($userId): string
{
$authManager = \Yii::$app->authManager;
if ($authManager->checkAccess($userId, 'appAdmin'))
{
return 'appAdmin'; // raw role id
}
elseif ($authManager->checkAccess($userId, 'appSupport'))
{
return 'appSupport';
}
elseif ($authManager->checkAccess($userId, 'userAssist'))
{
return 'userAssist';
}
else
{
return 'userOwner';
}
}
and then in isAdmin():
php
if (self::hasRole($userId) !== 'appAdmin')
{
return false;
}
Summary:
The overall structure of isAdmin() is correct and implements protection using user role and IP/email whitelist.
The possible problem lies in role string comparison due to translation.
Make sure IP retrieval method (self::userIp()) works properly.
Make sure self::userId() aligns with $identity->id.
If you fix these issues, your isAdmin() logic will be solid.