2d916037 by 周伟奇

add login limit

1 parent 14e86b52
LOGIN_TIMES_LIMIT = 100
LOGIN_TIMES_LIMIT_EXPIRES = 3600 * 24
from common.mixins import GenericView
from rest_framework import status
from rest_framework_jwt.views import ObtainJSONWebToken
from common import response
from common.redis_cache import redis_handler as rh
from .consts import LOGIN_TIMES_LIMIT_EXPIRES, LOGIN_TIMES_LIMIT
# Create your views here.
......@@ -8,17 +11,22 @@ from common import response
class LoginView(ObtainJSONWebToken, GenericView):
def post(self, request, *args, **kwargs):
user_name = request.data.get('username', '')
times = rh.get_login_times(user_name)
if isinstance(times, int) and times >= LOGIN_TIMES_LIMIT:
raise self.invalid_params(msg="重试次数限制")
res = super(LoginView, self).post(request, *args, **kwargs)
self.running_log.info('[users.login] username: %s' % request.data.get('username'))
self.running_log.info('[users.login] username: {0}'.format(user_name))
if res.status_code == 400:
if res.status_code == status.HTTP_400_BAD_REQUEST:
rh.set_login_times(user_name, LOGIN_TIMES_LIMIT_EXPIRES)
raise self.invalid_params(msg="用户名或密码错误")
serializer = self.get_serializer(data=request.data)
serializer.is_valid()
# serializer.is_valid()
user = serializer.object.get('user')
user_id = user.id
data = {
'user_id': user_id,
'user_id': user.id,
'user_name': user.username,
'token': res.data.get('token'),
}
......
......@@ -38,6 +38,7 @@ class RedisHandler:
self.session_id_key = '{0}:session_id'.format(self.prefix)
self.cms_token_key = '{0}:cms_token'.format(self.prefix)
self.ecm_token_key = '{0}:ecm_token'.format(self.prefix)
self.login_limit_key = '{0}:login_limit'.format(self.prefix)
def enqueue(self, tasks, is_priority=False):
# 1
......@@ -71,3 +72,14 @@ class RedisHandler:
def set_ecm_token(self, token, expires=None):
return self.redis.set(self.ecm_token_key, token, expires)
def get_login_times(self, user_name):
if user_name == '':
return None
return self.redis.get('{0}:{1}'.format(self.login_limit_key, user_name))
def set_login_times(self, user_name, expires=None):
key = '{0}:{1}'.format(self.login_limit_key, user_name)
self.redis.incr(key)
if isinstance(expires, int):
self.redis.expire(key, expires)
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!