LoginService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Service;
  3. use App\Model\Settings;
  4. use Illuminate\Support\Facades\Cache;
  5. class LoginService extends Service
  6. {
  7. const ALL = 'all';
  8. public function loginRule($data){
  9. // 获取用户的IP地址
  10. $userIP = $_SERVER['REMOTE_ADDR'];
  11. // 获取设置的IP地址
  12. $allowedIPs = $this->allowedIPs();
  13. // 校验用户IP是否在允许的范围内
  14. $isValidIP = false;
  15. if(in_array(self::ALL,$allowedIPs)) {
  16. $isValidIP = true;
  17. }else{
  18. foreach ($allowedIPs as $allowedIP) {
  19. if (strpos($allowedIP, '/') !== false) {
  20. // IP段表示法校验
  21. list($subnet, $mask) = explode('/', $allowedIP);
  22. if ((ip2long($userIP) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
  23. $isValidIP = true;
  24. break;
  25. }
  26. } else {
  27. // 单个IP地址校验
  28. if ($allowedIP === $userIP) {
  29. $isValidIP = true;
  30. break;
  31. }
  32. }
  33. }
  34. }
  35. return $isValidIP;
  36. }
  37. public function allowedIPs(){
  38. $allowedIPs = Settings::where('name','allowedIPs')->first();
  39. if(empty($allowedIPs) || empty($allowedIPs->value)) return [self::ALL];
  40. return explode(',',$allowedIPs->value);
  41. }
  42. //设置登录错误次数(超过三次)
  43. public static function errorSetLogin($cacheKey){
  44. if(Cache::has($cacheKey)){
  45. $num = Cache::get($cacheKey);
  46. $num++;
  47. Cache::put($cacheKey,$num,30);
  48. if($num >= 3){
  49. return ['账号密码输入错误3次,30分钟内限制登录!'];
  50. }else{
  51. return ['账号密码输入错误第'. $num .'次!'];
  52. }
  53. }else{
  54. Cache::add($cacheKey,1,30);
  55. return ['密码输入错误!'];
  56. }
  57. }
  58. //判断是否限制登录
  59. public static function isLoginlimitation($cacheKey){
  60. if(Cache::has($cacheKey)){
  61. $num = Cache::get($cacheKey);
  62. if($num >= 3) return true;
  63. }
  64. return false;
  65. }
  66. }