LoginService.php 2.5 KB

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