Advertisement
Guest User

Untitled

a guest
Sep 11th, 2017
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.29 KB | None | 0 0
  1. <?php
  2. //
  3. //
  4. class auth {
  5.     private $db;
  6.     private $sessionId="";
  7.     public $timeout=60;
  8.     public $message;
  9.     public $data;
  10.     public $db_bill;
  11.     public $bill_dbs;
  12.     //
  13.     //
  14.     public function __construct ($db=null) {
  15.         $this->db=$db;
  16.         $this->db_bill=null;
  17.         $this->bill_dbs=array();
  18.         $this->data=array();
  19.  
  20.         if (isset($this->db->dblink)) {
  21.             $query="select * from billing_db where `show`=1 order by description";
  22.             if ($result_db=$this->db->query($query)) {
  23.                 while ($row=$this->db->fetch_assoc($result_db)) {
  24.                     $this->bill_dbs[]=$row;
  25.                 }
  26.             }
  27.         }
  28.     }
  29.     //
  30.     //
  31.     public function __destruct() {
  32.         if ($this->db_bill) $this->db_bill->close();
  33.     }
  34.  
  35.     private function check_cookie() {
  36.         $sessid=null;
  37.         if (isset($_COOKIE["session"])) {$sessid=quote_string($_COOKIE["session"]); }
  38.  
  39.         if (empty($sessid)) {
  40.             return false;
  41.         }
  42.  
  43.         if (!$result_session=$this->db->query("SELECT * FROM speedyline_sessions WHERE session='" . $sessid . "'")) {
  44.             echo $this->db->error;
  45.             return false;
  46.         }
  47.  
  48.         if (!($session=$this->db->fetch_assoc($result_session))) {
  49.             //$this->message="Previous Session time out.";
  50.             return false;
  51.         }
  52.  
  53.         if (time() > $session['ttl']) {
  54.             //$this->message= "Предыдущая сессия завершена из-за неактивности.";
  55.             return false;
  56.         }
  57.  
  58.         if (!($_SERVER['REMOTE_ADDR'] == $session['ip'])) {
  59.             //$this->message= "Wrong ip.";
  60.             return false;
  61.         }
  62.         $this->sessionId=$sessid;
  63.         $this->data['region']=$session['region'];
  64.         $this->data['id']=$session['id'];
  65.         $this->data['login']=$session['login'];
  66.         if (!$this->connect_billing()) {
  67.             $this->message='Сервис временно недоступен..';
  68.             return false;
  69.         }
  70. $this->data['is_juridical'] = $this->is_juridical();
  71.         $this->get_user_ips($this->data['id']);
  72.  
  73.         $query="UPDATE speedyline_sessions SET ttl=" . (time()+60*$this->timeout) . " WHERE session='" . $sessid . "'";
  74.         if (!$this->db->query($query)) {
  75.             //$this->message="Error in DataBase. ";
  76.             //return false;
  77.         }
  78.         return true;
  79.     }
  80.     //
  81.     //
  82.     private function check_password () {
  83.         if (!isset($_POST['submit'])) return false;
  84.         $login='';
  85.         $pass='';
  86.         $region='';
  87.         if (isset($_POST['login'])) { $login=trim(quote_string($_POST['login'])); }
  88.         if (isset($_POST['password'])) {$pass=trim(quote_string($_POST['password'])); }
  89.         if (isset($_POST['region'])) {$region=trim(quote_string($_POST['region'])); }
  90.         $ip=quote_string($_SERVER['REMOTE_ADDR']);
  91.         $net=$this->get_network_by_ip($ip);
  92.         if (empty ($login)) {
  93.             $this->message='Не введен логин.';
  94.             return false;
  95.         }
  96.         if (empty ($pass)) {
  97.             $this->message='Не введен пароль.';
  98.             return false;
  99.         }
  100.     // Биллинг пользователя определяется по его логину,
  101.     // поэтому регион может быть пустым.
  102.     // Возможность выбора региона на странице логина предоставляется только
  103.     // пользователям, подключающимся из офисов компании.
  104.         if (empty ($region)) {
  105.       // сначала подбираем регион по логину пользователя
  106.       $region = $this->getRegionByLogin($login);
  107.       if (!$region) {
  108.         // если по системному логину пользователь не нашёлся, ищем по альтернативному
  109.         $alt_login = $this->getUserByAltLogin($login);
  110.         if ($alt_login) {
  111.           $region = $alt_login['region'];
  112.         }
  113.         else {
  114.           // если и по альтернативному логину не получилось, то пытаемся использовать IP пользователя
  115.           if ($net) {
  116.             $region = $net['billing_name'];
  117.           }
  118.           else {
  119.             // если и по IP не получилось, то тогда все - без вариантов
  120.             // либо логин не существует, либо speedyline_users не обновилась,
  121.             // либо, в дополнение ко всему прочему, пользователь пытается войти
  122.             // с IP, который не принадлежит сети.
  123.             $this->message='Пользователь не найден. Повторите попытку позднее.';
  124.             return false;
  125.           }
  126.         }
  127.       }
  128.         }
  129.  
  130.         $this->data['region']=$region;
  131.         if (!$this->connect_billing()) {
  132.             $this->message='Сервис временно недоступен..';
  133.             return false;
  134.         }
  135.         $login_ok=false;
  136.     if ($alt_login) {
  137.       $query='SELECT id, login, password from users where id="'.$alt_login['user_id'].'" and is_deleted=0 limit 1';
  138.     }
  139. else {
  140.       $query='SELECT id, login, password from users where login="'.$login.'" and is_deleted=0 limit 1';
  141.     }
  142.         if ($result_user=$this->db_bill->query($query)) {
  143.             if ($user=$this->db_bill->fetch_assoc($result_user)) {
  144.                 if ($user['password']==$pass) {
  145.                     $this->data['id']=$user['id'];
  146.                     $this->data['login']=$user['login'];
  147.           $this->data['is_juridical'] = $this->is_juridical();
  148.           $login_ok=true;
  149.                 }
  150.             }
  151.         }
  152.         if (!$login_ok) {
  153.             $this->message='Логин или пароль указаны неверно.';
  154.             write_log($login.' Error login or pass ('.$pass.') from ip '.$ip);
  155.             return false;
  156.         }
  157.         $this->get_user_ips($this->data['id']);
  158.         if (!$this->is_allow_other_ips()) {
  159.             if (!$this->is_my_ip($ip)) {
  160.                 if (!$net || $net['type']!=2) {
  161.                     $this->message='Доступ разрешен только с ip адресов, принадлежащих пользователю \''.$login.'\' . Ваш ip: '.$ip;
  162.                     write_log($login.' Wrong ip for login '.$login.' from ip '.$ip);
  163.                     return false;
  164.                 }
  165.             }
  166.         }
  167.         $sessid=md5((time()*$this->data['id']).'speedyline_l_k') . $this->data['id'];
  168.         $query='INSERT INTO speedyline_sessions (session, id, ip, region, login, ttl)VALUES ("' . $sessid . '", "' . $this->data['id'] . '", "' . $ip . '", "'.$region.'", "'.$login.'", ' . (time()+60*$this->timeout) . ')';
  169.         if (!$this->db->query($query)) {
  170.             $this->message="Сервис временно недоступен!";
  171.             return false;
  172.         }
  173.         setcookie("session",$sessid,time()+60*60*24);
  174.         $this->sessionId=$sessid;
  175.         write_log($login.' Successfull login from ip '.$ip);
  176.         return true;
  177.     }
  178.     //
  179.   public function findUser($login) {
  180.         $query = "SELECT u.user_id, b.name
  181.                FROM speedyline_users u
  182.                  LEFT OUTER JOIN speedyline_users_alt_logins a
  183.                    ON u.user_id = a.user_id
  184.                  INNER JOIN billing_db b
  185.                    ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
  186.                  WHERE u.login = '$login' or a.alt_login = '$login'";
  187.     $result = $this->db->query($query);
  188.     if ($result) {
  189.       $user = $this->db->fetch_assoc($result);
  190.       if ($user) {
  191.         return $user;
  192.       }
  193.     }
  194.     return NULL;
  195.     }
  196.   //
  197.   private function getUser ($region, $user_id) {
  198.         $this->data['region']=$region;
  199.         if (!$this->connect_billing()) {
  200.             $this->message='Сервис временно недоступен..';
  201.             return false;
  202.         }
  203. $query="SELECT * from users where id = '$user_id'";
  204.     if ($result_user=$this->db_bill->query($query)) {
  205.             if ($user=$this->db_bill->fetch_assoc($result_user)) {
  206.                 return $user;
  207.             }
  208.       else {
  209.         $this->message='Данные пользователя недоступны. Обратитесь в техническую поддержку';
  210.         return false;
  211.       }
  212.         }
  213.     }
  214.   //
  215.   public function changeUserPassword($region, $user_id, $password) {
  216.         $this->data['region']=$region;
  217.         if (!$this->connect_billing()) {
  218.             $this->message='Сервис временно недоступен..';
  219.             return false;
  220.         }
  221.         $query = "UPDATE users SET password = '$password' where id = $user_id";
  222.     if (!$this->db_bill->query($query)) {
  223.             $this->message='Ошибка при изменение пароля. Обратитесь в службу технической поддержки.';
  224.       return FALSE;
  225.         }
  226.         return true;
  227.     }
  228.     //
  229.     public function login () {
  230.         //return true;
  231.         if (count($this->bill_dbs)<1) {
  232.             $this->message="Сервис временно недоступен.";
  233.             return false;
  234.         }
  235.         if ($this->check_cookie() || $this->check_password()) {
  236.                 return true;
  237.         }
  238.         return false;
  239.     }
  240.     //
  241.     //
  242.     public function logout() {
  243.         if (!empty($this->sessionId)) {
  244.             $query="DELETE FROM speedyline_sessions WHERE session='" . $this->sessionId . "'";
  245.             if (!$this->db->query($query)) {
  246.                 return false;
  247.             }
  248.             $query="DELETE FROM speedyline_sessions WHERE ttl < ".time();
  249.             $this->db->query($query);
  250.         }
  251.         return true;
  252.     }
  253.     //
  254.     //
  255.     private function connect_billing() {
  256.         foreach ($this->bill_dbs as $bill_db) {
  257.             if ($bill_db['name']==$this->data['region']) {
  258.                 $this->db_bill=new db($bill_db['ip'],$bill_db['login'],$bill_db['pass'],$bill_db['db']);
  259.                 $this->data['uniteller_shop_id']=$bill_db['uniteller_shop_id'];
  260.                 return $this->db_bill->connect_t();
  261.             }
  262.         }
  263.         return null;
  264.     }
  265.     //
  266.     //
  267.     private function get_user_ips() {
  268.         if (!$this->db_bill || !isset($this->data['id']) || $this->data['id']<1) return false;
  269. $id=$this->data['id'];
  270.         $query='select account_id, ip, mask
  271.            from service_links
  272.            left join iptraffic_service_links on service_links.id=iptraffic_service_links.id and iptraffic_service_links.is_deleted=0
  273.            left join ip_groups on iptraffic_service_links.ip_group_id=ip_groups.ip_group_id and ip_groups.is_deleted=0
  274.            where service_links.user_id='.$id.' and service_links.is_deleted=0
  275.            order by ip
  276.            ';
  277.         if ($this->db_bill->query($query)) {
  278.             while($ips=$this->db_bill->fetch_assoc()) {
  279.                 $ip=long2ip($ips['ip']);
  280.                 $mask=long2ip($ips['mask']);
  281.                 if ($ip>0) {
  282.                     $ip_ar=array('ip' => $ip, 'mask' => $mask);
  283.                     $this->data['accounts'][$ips['account_id']]['ips'][]=$ip_ar;
  284.                 }
  285.             }
  286.         }
  287.     }
  288.     //
  289.     //
  290.     public function is_my_ip($ip_str) {
  291.         $ip=ip2long($ip_str);
  292.         if (empty($ip)) return false;
  293.         if (!isset($this->data['accounts'])) return false;
  294.         foreach ($this->data['accounts'] as $account) {
  295.             if (!isset($account['ips'])) continue;
  296.             foreach ($account['ips'] as $ip_ar) {
  297.                 if ((ip2long($ip_ar['ip']) & ip2long($ip_ar['mask'])) == ($ip & ip2long($ip_ar['mask']))) {
  298.                     return true;
  299.                 }
  300.             }
  301.         }
  302.         return false;
  303.     }
  304.     public function get_network_by_ip($ip_str) {
  305.         $ip=ip2long($ip_str);
  306.         if (empty($ip)) return false;
  307.         $query='select * from billing_db_ips
  308.            where '.$ip.' & billing_db_ips.mask = billing_db_ips.ip ';
  309.         if ($result_net=$this->db->query($query)) {
  310.             if ($row=$this->db->fetch_assoc($result_net)) {
  311.                 return $row;
  312.             }
  313.         }
  314.         return null;
  315.     }
  316.     public function is_allow_other_ips() {
  317.         $query='select web_allow_other_ips as allow from speedyline_users where user_id='.$this->data['id'].'';
  318.         if ($result_opt=$this->db->query($query)) {
  319.             if ($row=$this->db->fetch_assoc($result_opt)) {
  320.                 return $row['allow'];
  321.             }
  322.         }
  323.         return 0;
  324.     }
  325.   //
  326.   private function getRegionByLogin($login) {
  327.     $query = "SELECT b.name AS region
  328.                FROM speedyline_users u
  329.                  INNER JOIN billing_db b
  330.                    ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
  331.                  WHERE u.login = '$login'";
  332.     $result_region = $this->db->query($query);
  333.     if ($result_region) {
  334.       $region_array = $this->db->fetch_assoc($result_region);
  335.       if ($region_array) {
  336. return $region_array['region'];
  337.       }
  338.     }
  339.     return NULL;
  340.   }
  341.     //
  342.   private function getUserByAltLogin($login) {
  343.     $query = "SELECT u.user_id, u.alt_login, b.name AS region
  344.                FROM speedyline_users_alt_logins u
  345.                  INNER JOIN billing_db b
  346.                    ON u.user_id BETWEEN b.user_min_id AND b.user_max_id
  347.                  WHERE u.alt_login = '$login'";
  348.     $result = $this->db->query($query);
  349.     if ($result) {
  350.       $user = $this->db->fetch_assoc($result);
  351.       if ($user) {
  352.         return $user;
  353.       }
  354.     }
  355.     return NULL;
  356.   }
  357.   //
  358.   public function getUserAltLogin() {
  359.     $query = "SELECT alt_login
  360.                FROM speedyline_users_alt_logins
  361.                  WHERE user_id = {$this->data['id']}";
  362.     $result = $this->db->query($query);
  363.     if ($result) {
  364.       $user = $this->db->fetch_assoc($result);
  365.       if ($user) {
  366.         return $user['alt_login'];
  367.       }
  368.     }
  369.     return NULL;
  370.   }
  371.   //
  372.   public function setUserAltLogin($alt_login) {
  373.     if (empty($this->data['id'])) {
  374.       return FALSE;
  375.     }
  376.     // проверяем уникальность логина среди системных
  377.     if ($this->getRegionByLogin($alt_login)) {
  378.       return FALSE;
  379.     }
  380.     //
  381.     if ($alt_login) {
  382.       $query = "REPLACE INTO speedyline_users_alt_logins (user_id, alt_login)
  383.                  VALUES({$this->data['id']}, '$alt_login')";
  384.     }
  385.     else {
  386.       $query = "DELETE FROM speedyline_users_alt_logins
  387.                  WHERE user_id = {$this->data['id']}";
  388.     }
  389.     return $this->db->query($query);
  390.   }
  391.   private function is_juridical() {
  392.         if (!$this->db_bill || !isset($this->data['id']) || $this->data['id']<1) return false;
  393.         $id=$this->data['id'];
  394.         $query="SELECT is_juridical from users where id=$id";
  395.         if ($this->db_bill->query($query)) {
  396.             while($user=$this->db_bill->fetch_assoc()) {
  397.                 return $user['is_juridical'];
  398.             }
  399.         }
  400.     return FALSE;
  401.     }
  402. }
  403. global $db;
  404. $auth=new auth($db);
  405. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement