Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function guardIp(PDO $db, int $userId, string $role = 'user'): bool
- {
- if ($role === 'admin') {
- return true;
- }
- $ip = $_SERVER['REMOTE_ADDR'];
- if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
- $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
- }
- $token = $_COOKIE['ast_dev'] ?? null;
- $st = $db->prepare('SELECT legit_ips, dev_token FROM user WHERE id=? FOR UPDATE');
- $st->execute([$userId]);
- $u = $st->fetch(PDO::FETCH_ASSOC) ?: [];
- $ips = json_decode($u['legit_ips'] ?: '[]', true);
- if (!$u['dev_token']) {
- if (!$token) {
- $token = bin2hex(random_bytes(32));
- setcookie('ast_dev', $token, [
- 'expires' => time()+86400*90,
- 'path' => '/',
- 'secure' => true,
- 'httponly' => true,
- 'samesite' => 'Lax'
- ]);
- }
- if (!in_array($ip, $ips, true) && count($ips) < 10) {
- $ips[] = $ip;
- }
- $db->prepare('UPDATE user SET legit_ips=?, dev_token=? WHERE id=?')
- ->execute([json_encode($ips), $token, $userId]);
- return true;
- }
- if (in_array($ip, $ips, true)) {
- return true;
- }
- if ($token && $token === $u['dev_token']) {
- if (!in_array($ip, $ips, true) && count($ips) < 10) {
- $ips[] = $ip;
- $db->prepare('UPDATE user SET legit_ips=? WHERE id=?')
- ->execute([json_encode($ips), $userId]);
- }
- return true;
- }
- session_unset();
- session_destroy();
- header('Location: ./?do=login&iperr=1');
- exit;
- }
Advertisement
Add Comment
Please, Sign In to add comment