def login_attempts(request): """ Track number of login attempts made by a specific IP within a specified amount of time """ ip, username = check_lockout(request) attempts_key = safe_key("{}{}-{}".format(LOGIN_ATTEMPTS, ip, username)) attempts = cache.get(attempts_key) if attempts: cache.incr(attempts_key) attempts = cache.get(attempts_key) if attempts >= getattr(settings, "MAX_LOGIN_ATTEMPTS", 10): lockout_key = safe_key("{}{}-{}".format(LOCKOUT_IP, ip, username)) lockout = cache.get(lockout_key) if not lockout: send_lockout_email(username, ip) cache.set( lockout_key, datetime.now().strftime("%Y-%m-%dT%H:%M:%S"), getattr(settings, "LOCKOUT_TIME", 1800), ) check_lockout(request) return attempts return attempts cache.set(attempts_key, 1) return cache.get(attempts_key)
def user_profile_w_token_response(request, status): """ Returns authenticated user profile""" if request and not request.user.is_anonymous: session = getattr(request, "session") if not session.session_key: # login user to create session token # TODO cannot call this without calling authenticate first or # setting the backend, commented for now. # login(request, request.user) session.set_expiry(DEFAULT_SESSION_EXPIRY_TIME) try: user_profile = request.user.profile except UserProfile.DoesNotExist: user_profile = cache.get( f'{USER_PROFILE_PREFIX}{request.user.username}') if not user_profile: with use_master: user_profile, _ = UserProfile.objects.get_or_create( user=request.user) cache.set(f'{USER_PROFILE_PREFIX}{request.user.username}', user_profile) serializer = UserProfileWithTokenSerializer(instance=user_profile, context={"request": request}) return Response(serializer.data, status=status)
def change_password_attempts(request): """Track number of login attempts made by user within a specified amount of time""" username = request.user.username password_attempts = '{}{}'.format(CHANGE_PASSWORD_ATTEMPTS, username) attempts = cache.get(password_attempts) if attempts: cache.incr(password_attempts) attempts = cache.get(password_attempts) if attempts >= MAX_CHANGE_PASSWORD_ATTEMPTS: cache.set('{}{}'.format(LOCKOUT_CHANGE_PASSWORD_USER, username), datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), LOCKOUT_TIME) if check_user_lockout(request): return check_user_lockout(request) return attempts cache.set(password_attempts, 1) return 1