desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) hash = self._hash(pickled) return base64.encodestring(((hash + ':') + pickled))
'Returns session key that isn\'t being used.'
def _get_new_session_key(self):
hex_chars = '1234567890abcdef' while True: session_key = get_random_string(32, hex_chars) if (not self.exists(session_key)): break return session_key
'Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance.'
def _get_session(self, no_load=False):
self.accessed = True try: return self._session_cache except AttributeError: if ((self.session_key is None) or no_load): self._session_cache = {} else: self._session_cache = self.load() return self._session_cache
'Get the number of seconds until the session expires.'
def get_expiry_age(self):
expiry = self.get('_session_expiry') if (not expiry): return settings.SESSION_COOKIE_AGE if (not isinstance(expiry, datetime)): return expiry delta = (expiry - timezone.now()) return ((delta.days * 86400) + delta.seconds)
'Get session the expiry date (as a datetime object).'
def get_expiry_date(self):
expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if (not expiry): expiry = settings.SESSION_COOKIE_AGE return (timezone.now() + timedelta(seconds=expiry))
'Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or `...
def set_expiry(self, value):
if (value is None): try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = (timezone.now() + value) self['_session_expiry'] = value
'Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there\'s an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.'
def get_expire_at_browser_close(self):
if (self.get('_session_expiry') is None): return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return (self.get('_session_expiry') == 0)
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete() self.create()
'Creates a new session key, whilst retaining the current session data.'
def cycle_key(self):
data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key)
'Returns True if the given session_key already exists.'
def exists(self, session_key):
raise NotImplementedError
'Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.'
def create(self):
raise NotImplementedError
'Saves the session data. If \'must_create\' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key.'
def save(self, must_create=False):
raise NotImplementedError
'Deletes the session data under this key. If the key is None, the current session key value is used.'
def delete(self, session_key=None):
raise NotImplementedError
'Loads the session data and returns a dictionary.'
def load(self):
raise NotImplementedError
'Get the file associated with this session key.'
def _key_to_file(self, session_key=None):
if (session_key is None): session_key = self._get_or_create_session_key() if (not set(session_key).issubset(self.VALID_KEY_CHARS)): raise SuspiciousOperation('Invalid characters in session key') return os.path.join(self.storage_path, (self.file_prefix + session_key))
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete(self.session_key) self.create()
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
return SessionStore().encode(session_dict)
'Test we can use Session.get_decoded to retrieve data stored in normal way'
def test_session_get_decoded(self):
self.session['x'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1})
'Test SessionManager.save method'
def test_sessionmanager_save(self):
self.session['y'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) Session.objects.save(s.session_key, {'y': 2}, s.expire_date) del self.session._session_cache self.assertEqual(self.session['y'], 2)
'This test tested exists() in the other session backends, but that doesn\'t make sense for us.'
def test_save(self):
pass
'This test tested cycle_key() which would create a new session key for the same session data. But we can\'t invalidate previously signed cookies (other than letting them expire naturally) so testing for this behavior is meaningless.'
def test_cycle(self):
pass
'If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie.'
def process_response(self, request, response):
try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST): if request.session.get_e...
'Returns the current ``Site`` based on the SITE_ID in the project\'s settings. The ``Site`` object is cached the first time it\'s retrieved from the database.'
def get_current(self):
from django.conf import settings try: sid = settings.SITE_ID except AttributeError: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured('You\'re using the Django "sites framework" without having set the SITE_ID setting. ...
'Clears the ``Site`` object cache.'
def clear_cache(self):
global SITE_CACHE SITE_CACHE = {}
'Executing the changepassword management command should change joe\'s password'
def test_that_changepassword_command_changes_joes_password(self):
self.assertTrue(self.user.check_password('qwerty')) command = changepassword.Command() command._get_pass = (lambda *args: 'not qwerty') command.execute('joe', stdout=self.stdout) command_output = self.stdout.getvalue().strip() self.assertEquals(command_output, "Changing password for ...
'A CommandError should be thrown by handle() if the user enters in mismatched passwords three times. This should be caught by execute() and converted to a SystemExit'
def test_that_max_tries_exits_1(self):
command = changepassword.Command() command._get_pass = (lambda *args: (args or 'foo')) self.assertRaises(SystemExit, command.execute, 'joe', stdout=self.stdout, stderr=self.stderr)
'Regressiontest for #12462'
def test_has_no_object_perm(self):
user = User.objects.get(username='test') content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) ...
'A superuser has all permissions. Refs #14795'
def test_get_all_superuser_permissions(self):
user = User.objects.get(username='test2') self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all()))
'Backs up the AUTH_PROFILE_MODULE'
def setUp(self):
self.old_AUTH_PROFILE_MODULE = getattr(settings, 'AUTH_PROFILE_MODULE', None)
'Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted, otherwise the old value is restored'
def tearDown(self):
if ((self.old_AUTH_PROFILE_MODULE is None) and hasattr(settings, 'AUTH_PROFILE_MODULE')): del settings.AUTH_PROFILE_MODULE if (self.old_AUTH_PROFILE_MODULE is not None): settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE
'Test that \'something\' in PermWrapper doesn\'t end up in endless loop.'
def test_permwrapper_in(self):
perms = PermWrapper(MockUser()) def raises(): (self.EQLimiterObject() in perms) self.assertRaises(raises, TypeError)
'Tests that the session is not accessed simply by including the auth context processor'
@override_settings(MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES, TEMPLATE_CONTEXT_PROCESSORS=global_settings.TEMPLATE_CONTEXT_PROCESSORS) def test_session_not_accessed(self):
context._standard_context_processors = None response = self.client.get('/auth_processor_no_attr_access/') self.assertContains(response, 'Session not accessed') context._standard_context_processors = None
'Tests that the session is accessed if the auth context processor is used and relevant attributes accessed.'
@override_settings(MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES, TEMPLATE_CONTEXT_PROCESSORS=global_settings.TEMPLATE_CONTEXT_PROCESSORS) def test_session_is_accessed(self):
context._standard_context_processors = None response = self.client.get('/auth_processor_attr_access/') self.assertContains(response, 'Session accessed') context._standard_context_processors = None
'Test that the lazy objects returned behave just like the wrapped objects.'
def test_user_attrs(self):
self.client.login(username='super', password='secret') user = authenticate(username='super', password='secret') response = self.client.get('/auth_processor_user/') self.assertContains(response, 'unicode: super') self.assertContains(response, 'id: 100') self.assertContains(response, 'userna...
'Check that login_required is assignable to callable objects.'
def testCallable(self):
class CallableView(object, ): def __call__(self, *args, **kwargs): pass login_required(CallableView())
'Check that login_required is assignable to normal views.'
def testView(self):
def normal_view(request): pass login_required(normal_view)
'Check that login_required works on a simple view wrapped in a login_required decorator.'
def testLoginRequired(self, view_url='/login_required/', login_url=settings.LOGIN_URL):
response = self.client.get(view_url) self.assertEqual(response.status_code, 302) self.assertTrue((login_url in response['Location'])) self.login() response = self.client.get(view_url) self.assertEqual(response.status_code, 200)
'Check that login_required works on a simple view wrapped in a login_required decorator with a login_url set.'
def testLoginRequiredNextUrl(self):
self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/')
'creates a user and returns a tuple (user_object, username, email)'
def create_dummy_user(self):
username = 'jsmith' email = 'jsmith@example.com' user = User.objects.create_user(username, email, 'test123') return (user, username, email)
'Tests requests where no remote user is specified and insures that no users get created.'
def test_no_remote_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/') self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', REMOTE_USER=None) self.assertTrue(response.context['user'].is_anonym...
'Tests the case where the username passed in the header does not exist as a User.'
def test_unknown_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER='newuser') self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(User.objects.count(), (num_users + 1)) User.objects.get(username='newuser') response = self.client.get('/remote_user...
'Tests the case where the username passed in the header is a valid User.'
def test_known_user(self):
User.objects.create(username='knownuser') User.objects.create(username='knownuser2') num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) self.assertEqual(response.context['user'].username, 'knownuser') self.assertEqual(User.objects.count(), n...
'Tests that a user\'s last_login is set the first time they make a request but not updated in subsequent requests with the same session.'
def test_last_login(self):
user = User.objects.create(username='knownuser') default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=timezone.utc) user.last_login = default_login user.save() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) se...
'Restores settings to avoid breaking other tests.'
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.curr_middleware settings.AUTHENTICATION_BACKENDS = self.curr_auth
'Grabs username before the @ character.'
def clean_username(self, username):
return username.split('@')[0]
'Sets user\'s email address.'
def configure_user(self, user):
user.email = 'user@example.com' user.save() return user
'The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address.'
def test_known_user(self):
super(RemoteUserCustomTest, self).test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '')
'The unknown user created should be configured with an email address.'
def test_unknown_user(self):
super(RemoteUserCustomTest, self).test_unknown_user() newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, 'user@example.com')
'Ensure that we can make a token and that it is valid'
def test_make_token(self):
user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertTrue(p0.check_token(user, tk1))
'Ensure that the token generated for a user created in the same request will work correctly.'
def test_10265(self):
user = User.objects.create_user('comebackkid', 'test3@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) reload = User.objects.get(username='comebackkid') tk2 = p0.make_token(reload) self.assertEqual(tk1, tk2)
'Ensure we can use the token after n days, but no greater.'
def test_timeout(self):
class Mocked(PasswordResetTokenGenerator, ): def __init__(self, today): self._today_val = today def _today(self): return self._today_val user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.mak...
'Make sure we don\'t allow overly long dates, causing a potential DoS.'
def test_date_length(self):
user = User.objects.create_user('ima1337h4x0r', 'test4@example.com', 'p4ssw0rd') p0 = PasswordResetTokenGenerator() self.assertRaises(ValueError, p0._make_token_with_timestamp, user, 175455491841851871349L)
'Named URLs should be reversible'
def test_named_urls(self):
expected_named_urls = [('login', [], {}), ('logout', [], {}), ('password_change', [], {}), ('password_change_done', [], {}), ('password_reset', [], {}), ('password_reset_done', [], {}), ('password_reset_confirm', [], {'uidb36': 'aaaaaaa', 'token': '1111-aaaaa'}), ('password_reset_complete', [], {})] for (name, ...
'Error is raised if the provided email address isn\'t currently registered'
def test_email_not_found(self):
response = self.client.get('/password_reset/') self.assertEqual(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) self.assertContainsEscaped(response, PasswordResetForm.error_messages['unknown']) self.assertEqual(len(mail.outbox), 0)
'Email is sent if a valid email address is provided for password reset'
def test_email_found(self):
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertTrue(('http://' in mail.outbox[0].body)) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
'Email is sent if a valid email address is provided for password reset when a custom from_email is provided.'
def test_email_found_custom_from(self):
response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual('staffmember@example.com', mail.outbox[0].from_email)
'If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override.'
def test_admin_reset(self):
response = self.client.post('/admin_password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='adminsite.com') self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertTrue(('http://adminsite.com' in mail.outbox[0].body)) self.assertEqual(settings.DEFAULT_...
'Poisoned HTTP_HOST headers can\'t be used for reset emails'
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host(self):
with self.assertRaises(SuspiciousOperation): self.client.post('/password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld') self.assertEqual(len(mail.outbox), 0)
'Poisoned HTTP_HOST headers can\'t be used for reset emails on admin views'
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host_admin_site(self):
with self.assertRaises(SuspiciousOperation): self.client.post('/admin_password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld') self.assertEqual(len(mail.outbox), 0)
'Logout without next_page option renders the default template'
def test_logout_default(self):
self.login() response = self.client.get('/logout/') self.assertEqual(200, response.status_code) self.assertTrue(('Logged out' in response.content)) self.confirm_logged_out()
'Logout with next_page option given redirects to specified resource'
def test_logout_with_next_page_specified(self):
self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Logout with query string redirects to specified resource'
def test_logout_with_redirect_argument(self):
self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/login/')) self.confirm_logged_out()
'Logout with custom query string redirects to specified resource'
def test_logout_with_custom_redirect_argument(self):
self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Set up the listeners and reset the logged in/logged out counters'
def setUp(self):
self.logged_in = [] self.logged_out = [] signals.user_logged_in.connect(self.listener_login) signals.user_logged_out.connect(self.listener_logout)
'Disconnect the listeners'
def tearDown(self):
signals.user_logged_in.disconnect(self.listener_login) signals.user_logged_out.disconnect(self.listener_logout)
'Check that users can be created and can set their password'
def test_user(self):
u = User.objects.create_user('testuser', 'test@example.com', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('testpw')) u.set_unusable_password() u.save() self.assertFalse(u.check_password('testpw')) self.asser...
'Check that users can be created without an email'
def test_user_no_email(self):
u = User.objects.create_user('testuser1') self.assertEqual(u.email, '') u2 = User.objects.create_user('testuser2', email='') self.assertEqual(u2.email, '') u3 = User.objects.create_user('testuser3', email=None) self.assertEqual(u3.email, '')
'Check the properties of the anonymous user'
def test_anonymous_user(self):
a = AnonymousUser() self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) self.assertFalse(a.is_superuser) self.assertEqual(a.groups.all().count(), 0) self.assertEqual(a.user_permissions.all().count(), 0)
'Check the creation and properties of a superuser'
def test_superuser(self):
super = User.objects.create_superuser('super', 'super@example.com', 'super') self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff)
'Check the operation of the createsuperuser management command'
def test_createsuperuser_management_command(self):
new_io = StringIO() call_command('createsuperuser', interactive=False, username='joe', email='joe@somewhere.org', stdout=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username='joe') self.assertEq...
'Normalize the address by lowercasing the domain part of the email address.'
@classmethod def normalize_email(cls, email):
email = (email or '') try: (email_name, domain_part) = email.strip().rsplit('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) return email
'Creates and saves a User with the given username, email and password.'
def create_user(self, username, email=None, password=None):
now = timezone.now() if (not username): raise ValueError('The given username must be set') email = UserManager.normalize_email(email) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now) user.set...
'Generates a random password with the given length and given allowed_chars. Note that the default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion.'
def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
return get_random_string(length, allowed_chars)
'Always returns False. This is a way of comparing User objects to anonymous users.'
def is_anonymous(self):
return False
'Always return True. This is a way to tell if the user has been authenticated in templates.'
def is_authenticated(self):
return True
'Returns the first_name plus the last_name, with a space in between.'
def get_full_name(self):
full_name = (u'%s %s' % (self.first_name, self.last_name)) return full_name.strip()
'Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes.'
def check_password(self, raw_password):
def setter(raw_password): self.set_password(raw_password) self.save() return check_password(raw_password, self.password, setter)
'Returns a list of permission strings that this user has through his/her groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned.'
def get_group_permissions(self, obj=None):
permissions = set() for backend in auth.get_backends(): if hasattr(backend, 'get_group_permissions'): if (obj is not None): permissions.update(backend.get_group_permissions(self, obj)) else: permissions.update(backend.get_group_permissions(self)) ...
'Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific objec...
def has_perm(self, perm, obj=None):
if (self.is_active and self.is_superuser): return True return _user_has_perm(self, perm, obj)
'Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object.'
def has_perms(self, perm_list, obj=None):
for perm in perm_list: if (not self.has_perm(perm, obj)): return False return True
'Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above.'
def has_module_perms(self, app_label):
if (self.is_active and self.is_superuser): return True return _user_has_module_perms(self, app_label)
'Sends an email to this User.'
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
'Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles.'
def get_profile(self):
if (not hasattr(self, '_profile_cache')): from django.conf import settings if (not getattr(settings, 'AUTH_PROFILE_MODULE', False)): raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MODULE in your project settings') try: (app_label, ...
'Returns a set of permission strings that this user has through his/her groups.'
def get_group_permissions(self, user_obj, obj=None):
if (user_obj.is_anonymous() or (obj is not None)): return set() if (not hasattr(user_obj, '_group_perm_cache')): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = Permission.objects.filter(group__user=user_obj) perms = perms.values_l...
'Returns True if user_obj has any permissions in the given app_label.'
def has_module_perms(self, user_obj, app_label):
if (not user_obj.is_active): return False for perm in self.get_all_permissions(user_obj): if (perm[:perm.index('.')] == app_label): return True return False
'The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found i...
def authenticate(self, remote_user):
if (not remote_user): return user = None username = self.clean_username(remote_user) if self.create_unknown_user: (user, created) = User.objects.get_or_create(username=username) if created: user = self.configure_user(user) else: try: user = Use...
'Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, returns the username unchanged.'
def clean_username(self, username):
return username
'Configures a user after creation and returns the updated user. By default, returns the user unmodified.'
def configure_user(self, user):
return user
'Use special form during user creation'
def get_form(self, request, obj=None, **kwargs):
defaults = {} if (obj is None): defaults.update({'form': self.add_form, 'fields': admin.util.flatten_fieldsets(self.add_fieldsets)}) defaults.update(kwargs) return super(UserAdmin, self).get_form(request, obj, **defaults)
'Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.'
def response_add(self, request, obj, post_url_continue='../%s/'):
if (('_addanother' not in request.POST) and ('_popup' not in request.POST)): request.POST['_continue'] = 1 return super(UserAdmin, self).response_add(request, obj, post_url_continue)
'Generates a cryptographically secure nonce salt in ascii'
def salt(self):
return get_random_string()
'Checks if the given password is correct'
def verify(self, password, encoded):
raise NotImplementedError()
'Creates an encoded database value The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters.'
def encode(self, password, salt):
raise NotImplementedError()
'Returns a summary of safe values The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password.'
def safe_summary(self, encoded):
raise NotImplementedError()
'If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation.'
def __init__(self, request=None, *args, **kwargs):
self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs)
'Validates that an active user exists with the given email address.'
def clean_email(self):
email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email, is_active=True) if (not len(self.users_cache)): raise forms.ValidationError(self.error_messages['unknown']) if any(((user.password == UNUSABLE_PASSWORD) for user in self.users_cache)): raise fo...
'Generates a one-use only link for resetting password and sends to the user.'
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None):
from django.core.mail import send_mail for user in self.users_cache: if (not domain_override): current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override c ...
'Validates that the old_password field is correct.'
def clean_old_password(self):
old_password = self.cleaned_data['old_password'] if (not self.user.check_password(old_password)): raise forms.ValidationError(self.error_messages['password_incorrect']) return old_password
'Saves the new password.'
def save(self, commit=True):
self.user.set_password(self.cleaned_data['password1']) if commit: self.user.save() return self.user
'Returns a token that can be used once to do a password reset for the given user.'
def make_token(self, user):
return self._make_token_with_timestamp(user, self._num_days(self._today()))