Debian Codegraph @

axes/handlers/cache.py

raw
1 from logging import getLogger
2 from typing import Optional
3
4 from axes.conf import settings
5 from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler
6 from axes.helpers import (
7 get_cache,
8 get_cache_timeout,
9 get_client_cache_key,
10 get_client_str,
11 get_client_username,
12 get_credentials,
13 get_failure_limit,
14 )
15 from axes.models import AccessAttempt
16 from axes.signals import user_locked_out
17
18 log = getLogger(__name__)
19
20
21 class AxesCacheHandler(AbstractAxesHandler, AxesBaseHandler):
22 """
23 Signal handler implementation that records user login attempts to cache and locks users out if necessary.
24 """
25
26 def __init__(self):
27 self.cache = get_cache()
28
29 def reset_attempts(
30 self,
31 *,
32 ip_address: str = None,
33 username: str = None,
34 ip_or_username: bool = False,
35 ) -> int:
36 cache_keys: list = []
37 count = 0
38
39 if ip_address is None and username is None:
40 raise NotImplementedError("Cannot clear all entries from cache")
41 if ip_or_username:
42 raise NotImplementedError(
43 "Due to the cache key ip_or_username=True is not supported"
44 )
45
46 cache_keys.extend(
47 get_client_cache_key(
48 AccessAttempt(username=username, ip_address=ip_address)
49 )
50 )
51
52 for cache_key in cache_keys:
53 deleted = self.cache.delete(cache_key)
54 count += int(deleted) if deleted is not None else 1
55
56 log.info("AXES: Reset %d access attempts from database.", count)
57
58 return count
59
60 def get_failures(self, request, credentials: Optional[dict] = None) -> int:
61 cache_keys = get_client_cache_key(request, credentials)
62 failure_count = max(
63 self.cache.get(cache_key, default=0) for cache_key in cache_keys
64 )
65 return failure_count
66
67 def user_login_failed(self, sender, credentials: dict, request=None, **kwargs):
68 """
69 When user login fails, save attempt record in cache and lock user out if necessary.
70
71 :raises AxesSignalPermissionDenied: if user should be locked out.
72 """
73
74 if request is None:
75 log.error(
76 "AXES: AxesCacheHandler.user_login_failed does not function without a request."
77 )
78 return
79
80 username = get_client_username(request, credentials)
81 if settings.AXES_ONLY_USER_FAILURES and username is None:
82 log.warning(
83 "AXES: Username is None and AXES_ONLY_USER_FAILURES is enabled, new record will NOT be created."
84 )
85 return
86
87 # If axes denied access, don't record the failed attempt as that would reset the lockout time.
88 if (
89 not settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT
90 and request.axes_locked_out
91 ):
92 request.axes_credentials = credentials
93 user_locked_out.send(
94 "axes",
95 request=request,
96 username=username,
97 ip_address=request.axes_ip_address,
98 )
99 return
100
101 client_str = get_client_str(
102 username,
103 request.axes_ip_address,
104 request.axes_user_agent,
105 request.axes_path_info,
106 request,
107 )
108
109 if self.is_whitelisted(request, credentials):
110 log.info("AXES: Login failed from whitelisted client %s.", client_str)
111 return
112
113 failures_since_start = 1 + self.get_failures(request, credentials)
114 request.axes_failures_since_start = failures_since_start
115
116 if failures_since_start > 1:
117 log.warning(
118 "AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the cache.",
119 client_str,
120 failures_since_start,
121 get_failure_limit(request, credentials),
122 )
123 else:
124 log.warning(
125 "AXES: New login failure by %s. Creating new record in the cache.",
126 client_str,
127 )
128
129 cache_keys = get_client_cache_key(request, credentials)
130 for cache_key in cache_keys:
131 failures = self.cache.get(cache_key, default=0)
132 self.cache.set(cache_key, failures + 1, get_cache_timeout())
133
134 if (
135 settings.AXES_LOCK_OUT_AT_FAILURE
136 and failures_since_start >= get_failure_limit(request, credentials)
137 ):
138 log.warning(
139 "AXES: Locking out %s after repeated login failures.", client_str
140 )
141
142 request.axes_locked_out = True
143 request.axes_credentials = credentials
144 user_locked_out.send(
145 "axes",
146 request=request,
147 username=username,
148 ip_address=request.axes_ip_address,
149 )
150
151 def user_logged_in(self, sender, request, user, **kwargs):
152 """
153 When user logs in, update the AccessLog related to the user.
154 """
155
156 username = user.get_username()
157 credentials = get_credentials(username)
158 client_str = get_client_str(
159 username,
160 request.axes_ip_address,
161 request.axes_user_agent,
162 request.axes_path_info,
163 request,
164 )
165
166 log.info("AXES: Successful login by %s.", client_str)
167
168 if settings.AXES_RESET_ON_SUCCESS:
169 cache_keys = get_client_cache_key(request, credentials)
170 for cache_key in cache_keys:
171 failures_since_start = self.cache.get(cache_key, default=0)
172 self.cache.delete(cache_key)
173 log.info(
174 "AXES: Deleted %d failed login attempts by %s from cache.",
175 failures_since_start,
176 client_str,
177 )
178
179 def user_logged_out(self, sender, request, user, **kwargs):
180 username = user.get_username() if user else None
181 client_str = get_client_str(
182 username,
183 request.axes_ip_address,
184 request.axes_user_agent,
185 request.axes_path_info,
186 request,
187 )
188
189 log.info("AXES: Successful logout by %s.", client_str)