Added logic to disable IP login after repeated login failures
This commit is contained in:
1 parent
fef2e2a1f7
commit
22fa608220
5 files changed
+71
-3
No files matched your search
@@ -6,6 +6,7 @@ from services.admin_service.services.auth_service import AuthService
|
||||
from services.admin_service.services.sys_config_service import SysConfigService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.admin_service.constants import sys_config_key
|
||||
from services.common.utils.request_utils import RequestUtils
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -19,11 +20,13 @@ def get_sys_config_service(db: Session = Depends(get_db)) -> SysConfigService:
|
||||
|
||||
@router.post("/email/sign", response_model=dict)
|
||||
def email_login(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
sys_config_service: SysConfigService = Depends(get_sys_config_service),
|
||||
):
|
||||
"""Authenticate user via email and captcha code."""
|
||||
|
||||
email_is_enabled_raw = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_ENABLE) or "false"
|
||||
# Convert to boolean
|
||||
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
|
||||
@@ -31,6 +34,13 @@ def email_login(
|
||||
return ResponseUtils.error(message="email login not enabled", code=400)
|
||||
email_mode = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_MODE) or "password"
|
||||
email = body.get("user_email")
|
||||
if not email:
|
||||
return ResponseUtils.error(message="email required", code=400)
|
||||
# Check IP ban
|
||||
ip = RequestUtils.get_client_ip(request)
|
||||
if auth_service.check_ip_ban(ip, email):
|
||||
return ResponseUtils.error(message="Login failed: IP banned due to too many failed attempts. Please try again in 5 minutes.", code=403)
|
||||
|
||||
token = None
|
||||
match email_mode:
|
||||
case "password":
|
||||
@@ -39,8 +49,10 @@ def email_login(
|
||||
return ResponseUtils.error(message="email and password required", code=400)
|
||||
token = auth_service.email_login_by_password(email=email, password=password)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, email)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
auth_service.record_login_fail(ip, email)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct account or password", code=401)
|
||||
case "captcha":
|
||||
captcha = body.get("captcha")
|
||||
@@ -48,8 +60,10 @@ def email_login(
|
||||
return ResponseUtils.error(message="email and captcha required", code=400)
|
||||
token = auth_service.email_login_by_captcha(email=email, captcha=captcha)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, email)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
auth_service.record_login_fail(ip, email)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct captcha", code=401)
|
||||
case _:
|
||||
return ResponseUtils.error(message="email login mode not supported", code=400)
|
||||
@@ -68,17 +82,27 @@ def email_login_send_captcha(body: dict = Body(...), auth_service: AuthService =
|
||||
|
||||
|
||||
@router.post("/account/sign", response_model=dict)
|
||||
def account_login(body: dict = Body(...), auth_service: AuthService = Depends(get_auth_service)):
|
||||
def account_login(request: Request, body: dict = Body(...), auth_service: AuthService = Depends(get_auth_service)):
|
||||
"""Authenticate user via username and password."""
|
||||
|
||||
name = body.get("name")
|
||||
if not name:
|
||||
return ResponseUtils.error(message="account required", code=400)
|
||||
# Check IP ban
|
||||
ip = RequestUtils.get_client_ip(request)
|
||||
if auth_service.check_ip_ban(ip, name):
|
||||
return ResponseUtils.error(message="Login failed: IP banned due to too many failed attempts. Please try again in 5 minutes.", code=403)
|
||||
|
||||
password = body.get("password")
|
||||
if not name or not password:
|
||||
return ResponseUtils.error(message="account and password required", code=400)
|
||||
token = auth_service.account_login(name, password)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, name)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
return ResponseUtils.error(message="login failed", code=401)
|
||||
auth_service.record_login_fail(ip, name)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct account or password", code=401)
|
||||
|
||||
|
||||
@router.post("/google/sign", response_model=dict)
|
||||
|
||||
@@ -50,7 +50,7 @@ async def update_user_resource_group(
|
||||
group_id = body.get("resource_group")
|
||||
if not user_id or not group_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.MISSING_PARAMETER)
|
||||
group = resource_group_service.get_info(group_id)
|
||||
group = resource_group_service.get_info(group_id, "")
|
||||
if not group:
|
||||
return ResponseUtils.error(error_msg=error_msg.RESOURCE_NOT_FOUND)
|
||||
user = user_service.get_by_id(user_id)
|
||||
|
||||
@@ -16,6 +16,7 @@ from services.admin_service.constants.sys_config_key import (
|
||||
KEY_DEFAULT_RESOURCE_GROUP,
|
||||
)
|
||||
from services.common.utils.auth import delete_token
|
||||
from services.common.redis import redis_client
|
||||
|
||||
from google.auth.transport.requests import Request as GoogleRequest
|
||||
from google.oauth2 import id_token
|
||||
@@ -32,6 +33,32 @@ class AuthService:
|
||||
self.user_access_token_repository = UserAccessTokenRepository(db)
|
||||
self.sys_config_service = SysConfigService(db)
|
||||
|
||||
def check_ip_ban(self, ip: str, user: str) -> bool:
|
||||
"""Check if IP is banned. Returns True if banned."""
|
||||
ban_key = RedisKeys.login_ban_key(ip,user)
|
||||
return redis_client.exists(ban_key) > 0
|
||||
|
||||
def record_login_fail(self, ip: str, user: str):
|
||||
"""Record login failure for IP."""
|
||||
fail_key = RedisKeys.login_fail_count_key(ip,user)
|
||||
# Increment count
|
||||
count = redis_client.incr(fail_key)
|
||||
# Set expiration if it's the first failure
|
||||
if count == 1:
|
||||
redis_client.expire(fail_key, 300) # 5 minutes window
|
||||
|
||||
if count >= 5:
|
||||
# Ban IP
|
||||
ban_key = RedisKeys.login_ban_key(ip,user)
|
||||
redis_client.set(ban_key, "1", ex=300) # Ban for 5 minutes
|
||||
# Clear fail count
|
||||
redis_client.delete(fail_key)
|
||||
|
||||
def clear_login_fail(self, ip: str, user: str):
|
||||
"""Clear login failure count for IP."""
|
||||
fail_key = RedisKeys.login_fail_count_key(ip,user)
|
||||
redis_client.delete(fail_key)
|
||||
|
||||
def send_email_login_captcha(self, email: str) -> bool:
|
||||
"""
|
||||
Sends a login captcha code to the specified email address with simple rate limiting.
|
||||
|
||||
@@ -94,6 +94,13 @@ class RedisClient:
|
||||
except redis.RedisError as e:
|
||||
raise Exception(f"Redis TTL operation failed: {e}")
|
||||
|
||||
def incr(self, key: str, amount: int = 1) -> Any:
|
||||
"""Increment key value"""
|
||||
try:
|
||||
return self.client.incr(key, amount)
|
||||
except redis.RedisError as e:
|
||||
raise Exception(f"Redis INCR operation failed: {e}")
|
||||
|
||||
def close(self):
|
||||
"""Close Redis connection"""
|
||||
try:
|
||||
|
||||
@@ -42,3 +42,13 @@ class RedisKeys:
|
||||
def user_apikey_key(apikey_hash: str) -> str:
|
||||
"""Generate user API key cache key (using hash for security)"""
|
||||
return f"xpack:user_apikey:{apikey_hash}"
|
||||
|
||||
@staticmethod
|
||||
def login_fail_count_key(ip: str, user: str) -> str:
|
||||
"""Generate login fail count cache key"""
|
||||
return f"xpack:login:fail:{user}:{ip}"
|
||||
|
||||
@staticmethod
|
||||
def login_ban_key(ip: str, user: str) -> str:
|
||||
"""Generate login ban cache key"""
|
||||
return f"xpack:login:ban:{user}:{ip}"
|
||||
Reference in new issue
Block a user