def clean_email(self): existing = UserModel().objects.filter(email__iexact=self.cleaned_data['email']) if existing.exists(): raise forms.ValidationError(_("A user with that email already exists.")) else: return self.cleaned_data['email']
def create_inactive_user(self, username, email, password, site, send_email=True, request=None): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template. """ new_user = UserModel().objects.create_user(username, email, password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) #send_email = False if send_email: registration_profile.send_activation_email(site, request) return new_user
def test_registration_no_sites(self): """ Registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ Site._meta.installed = False resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) self.assertEqual(302, resp.status_code) new_user = UserModel().objects.get(username='******') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') self.failIf(new_user.is_active) self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1) Site._meta.installed = True
def test_registration(self): """ Registration creates a new inactive account and a new profile with activation key, populates the correct account data and sends an activation email. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) self.assertRedirects(resp, reverse('registration_complete')) new_user = UserModel().objects.get(username='******') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') # New user must not be active. self.failIf(new_user.is_active) # A registration profile was created, and an activation email # was sent. self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def test_registration(self): """ Registration creates a new inactive account and a new profile with activation key, populates the correct account data and sends an activation email. """ resp = self.client.post( reverse("registration_register"), data={"username": "******", "email": "*****@*****.**", "password1": "secret", "password2": "secret"}, ) self.assertRedirects(resp, reverse("registration_complete")) new_user = UserModel().objects.get(username="******") self.failUnless(new_user.check_password("secret")) self.assertEqual(new_user.email, "*****@*****.**") # New user must not be active. self.failIf(new_user.is_active) # A registration profile was created, and an activation email # was sent. self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def test_approval(self): """ Approval of an account functions properly. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) profile = self.registration_profile.objects.get(user__username='******') resp = self.client.get( reverse('registration_activate', args=(), kwargs={'activation_key': profile.activation_key})) admin_user = UserModel().objects.create_superuser('admin', '*****@*****.**', 'admin') self.client.login(username=admin_user.get_username(), password=admin_user) resp = self.client.get( reverse('registration_admin_approve', args=(), kwargs={'profile_id': profile.id})) user = profile.user # fail if the user is active (this should not happen yet) self.failIf(not user.is_active) self.assertRedirects(resp, reverse('registration_approve_complete'))
def test_profile_retrieval(self): # Testing User Information Retrieval for Login new_user = UserModel().objects.create_user(**self.user_info) existing_user = UserModel().objects.get(username='******') self.failUnless(existing_user.check_password('letstravel')) self.assertEqual(existing_user.email, '*****@*****.**') self.failUnless(existing_user.is_active)
def setUp(self): self.client = Client() admin_user = UserModel().objects.create_superuser( 'admin', '*****@*****.**', 'admin') self.client.login(username=admin_user.get_username(), password=admin_user) self.user_info = {'username': '******', 'password': '******', 'email': '*****@*****.**'}
def test_users_can_fill_out_registration_form_and_create_profile(self): # Tired of Twitter, Facebook, and Instagram Brad has luckily heard # about the new social network on the block so he visits the website in # his browser self.browser.get(self.live_server_url + reverse('home')) # He notices that the title mentions TSN (so much cooler than Twitter # or Facebook) AND the page welcomes him to the site self.assertIn('TSN', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('Welcome', header_text) # He sees a link telling him to Register and he clicks it self.browser.find_element_by_id('register').click() # He winds up on a brand new page register_url = self.browser.current_url self.assertIn('/accounts/register', register_url) # Brad fills out the form on this page to create an account with TSN # and presses enter for name, value in [('first_name', 'Brad'), ('last_name', 'Pitt'), ('username', 'brad'), ('email', '*****@*****.**'), ('password1', 'bradiscool'), ('password2', 'bradiscool\t\n')]: self.browser.find_element_by_name(name).send_keys(value) # He finds himself on another page telling him to activate his account p_text = self.browser.find_element_by_tag_name('p').text self.assertEquals('Please check your email to complete the registration process.', p_text) # After activating, he goes to the login page and logs in brad = UserModel().objects.get(username='******') brad.is_active = True brad.save() self.browser.get(self.live_server_url + reverse('auth_login')) self.browser.find_element_by_name('username').send_keys('brad') self.browser.find_element_by_name('password').send_keys('bradiscool\t\n') # He is then immediately redirected to a page asking him to create a # profile self.browser.implicitly_wait(3) self.assertIn('profile/create', self.browser.current_url) # He provides his birthday and his gender self.browser.find_element_by_name('birthday').send_keys('12/18/1963') self.browser.find_element_by_name('gender').send_keys('M\t\n') # He is now on the homepage again, this time he sees a post box self.browser.implicitly_wait(3) self.assertEqual(self.live_server_url + reverse('home'), self.browser.current_url) self.assertIn('new_post', self.browser.page_source)
def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ existing = UserModel().objects.filter(username__iexact=self.cleaned_data['username']) if existing.exists(): raise forms.ValidationError(_("A user with that username already exists.")) else: return self.cleaned_data['username']
def clean_email(self): if self.instance.pk != None: existing_user = UserModel().objects.filter(username__iexact=self.cleaned_data['email']) existing = Rolnik.objects.get(pk=self.instance.pk) if existing_user.exists() and existing.user != existing_user[0]: raise forms.ValidationError(_("This email belongs to someone else.")) return self.cleaned_data['email'] existing = UserModel().objects.filter(username__iexact=self.cleaned_data['email']) if existing.exists(): raise forms.ValidationError(_("A user with that username already exists.")) else: return self.cleaned_data['email']
def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ kwargs = {UserModel().USERNAME_FIELD: self.cleaned_data['username']} existing = UserModel().objects.filter(**kwargs) if existing.exists(): raise forms.ValidationError(_("A user with that username already exists.")) else: return self.cleaned_data['username']
def register(self, request, **cleaned_data): username, email, password, first_name, last_name = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1'], cleaned_data['first_name'], cleaned_data['last_name'] theuser = UserModel().objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name ) theuser.save() profile = UserProfile(user = theuser, location = cleaned_data['location'], career = cleaned_data['career']) profile.save() #(username, email, password, first_name, last_name) new_user = authenticate(username=username, password=password) login(request, new_user) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def create_inactive_user(self, username, email, password, site, send_email=True): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. """ new_user = UserModel().objects.create_user(username, email, password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) if send_email: registration_profile.send_activation_email(site) return new_user
def create_inactive_user(self, site, new_user=None, send_email=True, request=None, **user_info): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template. """ if new_user == None: password = user_info.pop('password') new_user = UserModel()(**user_info) new_user.set_password( password ) new_user.is_active = True new_user.save() #user_for_choice = Student(student_text = new_user.username) #user_for_choice.save() registration_profile = self.create_profile(new_user) if send_email: registration_profile.send_activation_email(site, request) return new_user
def test_management_command(self): """ The ``cleanupregistration`` management command properly deletes expired accounts. """ self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) expired_user = (self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) expired_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) expired_user.save() management.call_command('cleanupregistration') self.assertEqual(self.registration_profile.objects.count(), 1) self.assertRaises(UserModel().DoesNotExist, UserModel().objects.get, username='******')
def test_expired_user_deletion_activation_window(self): """ ``RegistrationProfile.objects.delete_expired_users()`` only deletes inactive users whose activation window has expired. """ self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) expired_user = (self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) expired_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) expired_user.save() self.registration_profile.objects.delete_expired_users() self.assertEqual(self.registration_profile.objects.count(), 1) self.assertRaises(UserModel().DoesNotExist, UserModel().objects.get, username='******')
def test_admin_approval_email_is_html_by_default(self): """ ``SupervisedRegistrationProfile.send_activation_email`` sends an html email by default. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.activated = True self.registration_profile.objects.send_admin_approve_email( new_user, Site.objects.get_current()) self.assertEqual(len(mail.outbox[0].alternatives), 1)
def register(self, request, **cleaned_data): username, email, password = cleaned_data['username'], cleaned_data[ 'email'], cleaned_data['password1'] new_user_mod = UserModel().objects.create_user(username, email, password) new_user_p = UserProfile.objects.get_or_create(user=new_user_mod) new_user = authenticate(username=username, password=password) login(request, new_user) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def test_admin_approval_complete_email_falls_back_to_django_default_from_email( self): """ ``SupervisedRegistrationManager.send_admin_approve_complete_email`` sends an email """ settings.REGISTRATION_DEFAULT_FROM_EMAIL = None new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_admin_approval_complete_email_is_plain_text_if_html_disabled( self): """ ``SupervisedRegistrationProfile.send_admin_approve_complete_email`` sends a plain text email if settings.REGISTRATION_EMAIL_HTML is False. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox[0].alternatives), 0)
def test_admin_approval_not_activated(self): """ Approving a non activated user's account fails """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) user = self.registration_profile.objects.admin_approve_user( profile.id, Site.objects.get_current()) self.failIf(isinstance(user, UserModel())) self.assertEqual(user, False) self.assertEqual(profile.user.is_active, False)
def test_expired_activation(self): """ Attempting to activate outside the permitted window does not activate the account. """ new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(), **self.user_info) new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1) new_user.save() profile = RegistrationProfile.objects.get(user=new_user) activated = RegistrationProfile.objects.activate_user(profile.activation_key) self.failIf(isinstance(activated, UserModel())) self.failIf(activated) new_user = UserModel().objects.get(username='******') self.failIf(new_user.is_active) profile = RegistrationProfile.objects.get(user=new_user) self.assertNotEqual(profile.activation_key, RegistrationProfile.ACTIVATED)
def test_admin_approval_email_falls_back_to_django_default_from_email( self): """ ``SupervisedRegistrationManager.send_admin_approve_email`` sends an email. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.activated = True self.registration_profile.objects.send_admin_approve_email( new_user, Site.objects.get_current()) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_registration_no_sites(self): """ Registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ resp = self.client.post( reverse("registration_register"), data={"username": "******", "email": "*****@*****.**", "password1": "secret", "password2": "secret"}, ) self.assertEqual(302, resp.status_code) new_user = UserModel().objects.get(username="******") self.failUnless(new_user.check_password("secret")) self.assertEqual(new_user.email, "*****@*****.**") self.failIf(new_user.is_active) self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def test_registered_users_can_add_friends_and_accept_friend_requests(self): # Sally is back and she's so excited because her best friend Jo Smo has # just joined TSN jo = UserModel().objects.create_user(username='******', first_name='Jo', last_name='Smo', password='******', email='*****@*****.**') UserProfile.objects.create(user=jo, birthday='1985-03-15', gender='M') self.login('sally', 'sallyiscooler') # Sally decides goes to view her friends and realizes that she doesn't # have any :( self.browser.find_element_by_id('my_friends').click() self.assertIn("doesn't have any friends", self.browser.page_source) # To remedy this, she goes to the find friend page to find Jo self.browser.find_element_by_id('find_friends').click() self.browser.find_element_by_name('query').send_keys('jo smo\n') # Jo Smo appears in her results and she clicks the button to add him # as a friend self.assertIn( 'Jo Smo', self.browser.find_element_by_class_name('media-heading').text) self.browser.find_element_by_class_name('btn-success').click() # The button now reads 'Cancel Request' and is yellow self.assertIn('Cancel Request', self.browser.page_source) self.assertIn('btn-warning', self.browser.page_source) # Since Sally and Jo share a computer Sally logs out and Jo logs in self.browser.find_element_by_id('logout').click() self.login('josmo', 'josmoyouknow') # Jo notices that he has a notification and clicks on the link notifications = self.browser.find_element_by_id('my_notifications') self.assertIn('1', notifications.text) notifications.click() # He clicks on the notification on the page and accepts the request self.browser.find_element_by_class_name('panel-heading').click() self.browser.find_element_by_class_name('btn-success').click() # Jo then goes to his friends and sees Sally is one of them self.browser.find_element_by_id('my_friends').click() self.assertIn( 'Sally Hayes', self.browser.find_element_by_class_name('media-heading').text)
def test_profile_creation(self): """ Creating a registration profile for a user populates the profile with the correct user and a SHA256 hash to use as activation key. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(profile.user.id, new_user.id) self.assertTrue(re.match('^[a-f0-9]{40,64}$', profile.activation_key)) self.assertEqual(str(profile), "Registration information for alice")
def test_registration(self): """ Registration creates a new account and logs the user in. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) new_user = UserModel().objects.get(username='******') self.assertEqual(302, resp.status_code) self.failUnless(reverse('registration_complete') in resp['Location']) self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') # New user must be active. self.failUnless(new_user.is_active) # New user must be logged in. resp = self.client.get(reverse('registration_register')) self.failUnless(resp.context['user'].is_authenticated())
def test_registration_no_sites(self): """ Registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) self.assertEqual(302, resp.status_code) new_user = UserModel().objects.get(username='******') self.assertTrue(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') self.assertFalse(new_user.is_active) self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def create_inactive_user(self, username, email, password, site, send_email=True, request=None): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template. """ new_user = UserModel().objects.create_user(username, email, password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) if send_email: registration_profile.send_activation_email(site, request) return new_user
def delete_expired_users(self): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for profile in self.all(): try: if profile.activation_key_expired(): user = profile.user if not user.is_active: user.delete() profile.delete() except UserModel().DoesNotExist: profile.delete()
def test_registration(self): """ Registration creates a new account and logs the user in. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) new_user = UserModel().objects.get(username='******') self.assertEqual(302, resp.status_code) self.assertIn(getattr(settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'), resp['Location']) self.assertTrue(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') # New user must be active. self.assertTrue(new_user.is_active) # New user must be logged in. resp = self.client.get(reverse('registration_register'), follow=True) self.assertTrue(resp.context['user'].is_authenticated)
def test_admin_approval_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_email`` sends an email to the site administrators """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.activated = True self.registration_profile.objects.send_admin_approve_email( new_user, Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) admins_emails = [value[1] for value in settings.REGISTRATION_ADMINS] for email in mail.outbox[0].to: self.assertIn(email, admins_emails)
def test_registration_exception(self, create_inactive_user): """ User is not created beforehand if an exception occurred at creating registration profile. """ create_inactive_user.side_effect = DatabaseError() valid_data = { 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' } with self.assertRaises(DatabaseError): self.client.post(reverse('registration_register'), data=valid_data) assert not UserModel().objects.filter(username='******').exists()
def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self.browser.wait = WebDriverWait(self.browser, 10) sally = UserModel().objects.create_user( first_name='Sally', last_name='Hayes', username='******', email='[email protected]:8081', password='******' ) sally_profile = UserProfile() sally_profile.user = sally sally_profile.birthday = '1985-07-22' sally_profile.gender = 'F' sally_profile.save()
def register(self, request, **cleaned_data): username, email, password = cleaned_data['username'], cleaned_data[ 'email'], cleaned_data['password1'] UserModel().objects.create_user(username, email, password) new_user = authenticate(username=username, password=password) login(request, new_user) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) UserProfile.objects.create(user=new_user, website=cleaned_data['website'], picture=cleaned_data['picture']) # else: # UserProfile.objects.create(user=new_user,website=cleaned_data['website']) return new_user
def test_valid_activation(self): """ Activating a user within the permitted window makes the account active, and resets the activation key. """ new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(), **self.user_info) profile = RegistrationProfile.objects.get(user=new_user) activated = RegistrationProfile.objects.activate_user(profile.activation_key) self.failUnless(isinstance(activated, UserModel())) self.assertEqual(activated.id, new_user.id) self.failUnless(activated.is_active) profile = RegistrationProfile.objects.get(user=new_user) self.assertEqual(profile.activation_key, RegistrationProfile.ACTIVATED)
def test_registration_form(self): """ Test that ``RegistrationForm`` enforces username constraints and matching passwords. """ # Create a user so we can verify that duplicate usernames aren't # permitted. UserModel().objects.create_user('alice', '*****@*****.**', 'secret') bad_username_error = 'This value may contain only letters, numbers and @/./+/-/_ characters.' if DJANGO_VERSION >= StrictVersion('1.8'): bad_username_error = 'Enter a valid username. ' + bad_username_error invalid_data_dicts = [ # Non-alphanumeric username. {'data': {'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo'}, 'error': ('username', [bad_username_error])}, # Already-existing username. {'data': {'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}, 'error': ('username', ["A user with that username already exists."])}, # Mismatched passwords. {'data': {'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'bar'}, 'error': ('password2', ["The two password fields didn't match."])}, ] for invalid_dict in invalid_data_dicts: form = forms.RegistrationForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) form = forms.RegistrationForm(data={'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo'}) self.failUnless(form.is_valid())
def test_resend_activation_email(self): """ Test the admin custom command 'resend activation email' """ new_user = UserModel().objects.create_user(**self.user_info) profile = RegistrationProfile.objects.create_profile(new_user) registrationprofile_list = reverse( 'admin:registration_registrationprofile_changelist') post_data = { 'action': 'resend_activation_email', helpers.ACTION_CHECKBOX_NAME: [profile.pk], } self.client.post(registrationprofile_list, post_data, follow=True) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
def register(self, request, **cleaned_data): # Create a new User username, email, password = cleaned_data['username'], cleaned_data[ 'email'], cleaned_data['password1'] new_user_object = UserModel().objects.create_user( username, email, password) # And links that user to a new (empty) UserProfile profile = UserProfile(user=new_user_object) profile.save() new_user = authenticate(username=username, password=password) login(request, new_user) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def register(self, request, form): """ Given a username, email address and password, register a new user account, which will initially be inactive. Along with the new ``User`` object, a new ``registration.models.RegistrationProfile`` will be created, tied to that ``User``, containing the activation key which will be used for this account. An email will be sent to the supplied email address; this email should contain an activation link. The email will be rendered using two templates. See the documentation for ``RegistrationProfile.send_activation_email()`` for information about these templates and the contexts provided to them. After the ``User`` and ``RegistrationProfile`` are created and the activation email is sent, the signal ``registration.signals.user_registered`` will be sent, with the new ``User`` as the keyword argument ``user`` and the class of this backend as the sender. """ if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) if hasattr(form, 'save'): new_user_instance = form.save() else: new_user_instance = UserModel().objects.create_user( **form.cleaned_data) new_user = RegistrationProfile.objects.create_inactive_user( new_user=new_user_instance, site=site, send_email=self.SEND_ACTIVATION_EMAIL, request=request, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def clean(self): email = self.cleaned_data['email'] email_domain = email.split('@')[1] email_group = email.split('@')[0].split('.')[-1] group = self.cleaned_data['group'] if UserModel().objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_("This email address is already in use. Please supply a different email address.")) if group == 'faculty': if email_group == 'faculty' and email_domain in ['iitbhu.ac.in', 'itbhu.ac.in']: pass else: raise forms.ValidationError(_("Registration in IIT BHU Faculty group only allowed for IIT BHU faculty.")) elif group == 'iitbhustudent': if email_domain not in ['iitbhu.ac.in', 'itbhu.ac.in']: raise forms.ValidationError(_("Registration in IIT BHU Student group only allowed for iitbhu domains.")) else: pass return self.cleaned_data
def test_valid_activation(self): """ Activating a user within the permitted window makes the account active, and resets the activation key. """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) user, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.assertIsInstance(user, UserModel()) self.assertEqual(user.id, new_user.id) self.assertFalse(user.is_active) self.assertTrue(activated) profile = self.registration_profile.objects.get(user=new_user) self.assertTrue(profile.activated)
def test_manually_registered_account(self): """ Test if a user failed to go through the registration flow but was manually marked ``is_active`` in the DB. Although the profile is expired and not active, we should never delete active users. """ active_user = (self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) active_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) active_user.is_active = True active_user.save() self.registration_profile.objects.delete_expired_users() self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(UserModel().objects.get(username='******'), active_user)
def test_activate_users(self): """ Test the admin custom command 'activate users' """ new_user = UserModel().objects.create_user(**self.user_info) profile = RegistrationProfile.objects.create_profile(new_user) self.assertFalse(profile.activated) registrationprofile_list = reverse( 'admin:registration_registrationprofile_changelist') post_data = { 'action': 'activate_users', helpers.ACTION_CHECKBOX_NAME: [profile.pk], } self.client.post(registrationprofile_list, post_data, follow=True) profile = RegistrationProfile.objects.get(user=new_user) self.assertTrue(profile.activated)
def test_registration_no_email(self): """ Overriden Registration view does not send an activation email if the associated class variable is set to ``False`` """ class RegistrationNoEmailView(RegistrationView): SEND_ACTIVATION_EMAIL = False request_factory = RequestFactory() view = RegistrationNoEmailView.as_view() resp = view(request_factory.post('/', data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'})) new_user = UserModel().objects.get(username='******') # A registration profile was created, and no activation email was sent. self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 0)
def test_registration_form_unique_email(self): """ Test that ``RegistrationFormUniqueEmail`` validates uniqueness of email addresses. """ # Create a user so we can verify that duplicate addresses # aren't permitted. UserModel().objects.create_user('alice', '*****@*****.**', 'secret') form = forms.RegistrationFormUniqueEmail(data={'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo'}) self.failIf(form.is_valid()) self.assertEqual(form.errors['email'], ["This email address is already in use. Please supply a different email address."]) form = forms.RegistrationFormUniqueEmail(data={'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo'}) self.failUnless(form.is_valid())
def validate_email(value): existing = UserModel().objects.filter(email__iexact=value) if not existing.exists(): raise forms.ValidationError(_("A user with that email doesn't exists."))