eqeqwan21

iniset.php

Jul 19th, 2025 (edited)
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.65 KB | None | 0 0
  1. function guardIp(PDO $db, int $userId, string $role = 'user'): bool
  2. {
  3.     if ($role === 'admin') {
  4.         return true;
  5.     }
  6.     $ip = $_SERVER['REMOTE_ADDR'];
  7.     if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  8.         $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
  9.     }
  10.     $token = $_COOKIE['ast_dev'] ?? null;
  11.  
  12.     $st = $db->prepare('SELECT legit_ips, dev_token FROM user WHERE id=? FOR UPDATE');
  13.     $st->execute([$userId]);
  14.     $u = $st->fetch(PDO::FETCH_ASSOC) ?: [];
  15.  
  16.     $ips = json_decode($u['legit_ips'] ?: '[]', true);
  17.  
  18.     if (!$u['dev_token']) {
  19.         if (!$token) {
  20.             $token = bin2hex(random_bytes(32));
  21.             setcookie('ast_dev', $token, [
  22.                 'expires'  => time()+86400*90,
  23.                 'path'     => '/',
  24.                 'secure'   => true,
  25.                 'httponly' => true,
  26.                 'samesite' => 'Lax'
  27.             ]);
  28.         }
  29.         if (!in_array($ip, $ips, true) && count($ips) < 10) {
  30.             $ips[] = $ip;
  31.         }
  32.         $db->prepare('UPDATE user SET legit_ips=?, dev_token=? WHERE id=?')
  33.             ->execute([json_encode($ips), $token, $userId]);
  34.         return true;
  35.     }
  36.  
  37.     if (in_array($ip, $ips, true)) {
  38.         return true;
  39.     }
  40.  
  41.     if ($token && $token === $u['dev_token']) {
  42.         if (!in_array($ip, $ips, true) && count($ips) < 10) {
  43.             $ips[] = $ip;
  44.             $db->prepare('UPDATE user SET legit_ips=? WHERE id=?')
  45.                 ->execute([json_encode($ips), $userId]);
  46.         }
  47.         return true;
  48.     }
  49.  
  50.     session_unset();
  51.     session_destroy();
  52.     header('Location: ./?do=login&iperr=1');
  53.     exit;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment