def test_reuse_one_time_token(self): params = get_parameters(self.user) response = self.client.get("/", params) self.assertUserLoggedIn(response, redirect_url="/") self.client.logout() response = self.client.get("/", params) self.assertUserNotLoggedIn(response)
def test_a_vote(self): # creating a fake election election = Election.objects.create(name="lion", state=Election.START) candidates = [ Candidate.objects.create(label="Opt %d" % i, election=election) for i in range(5) ] user = User.objects.create_user("Fred", "*****@*****.**", "secret") Voter.objects.create(user=user, election=election) names = ["Excellent", "Very good", "Good", "To reject"] grade = [ Grade.objects.create(name=n, election=election) for n in names ] # Fred clicks on the link on his mail invitation. login_token = utils.get_parameters(user)['url_auth_token'] login_link = "/vote/{}/?url_auth_token={}".format( election.pk, login_token) self.browser.get(self.live_server_url + login_link) # Fred always chooses excellent offset = candidates[0].pk for i in range(5): radio = self.wait_for(self.browser.find_element_by_id, 'id_c.{:d}_1'.format(i + offset)) self.browser.execute_script("arguments[0].checked = true;", radio) # Fred validates his votes and is redirected self.browser.find_element_by_id("cast").click() url = self.live_server_url + "/vote/success/{:d}".format(election.pk) self.wait_for(self.assertEqual, url, self.browser.current_url) # Fred tries to access to the result, but the vote is still opened self.wait_for(self.browser.find_element_by_id, "go_results").click() self.wait_for(self.browser.find_element_by_class_name, "error") # Someone closes the vote in the meantime, so Fred can access to the results election.state = Election.OVER election.save() self.wait_for(self.browser.find_element_by_id, "go_results").click() self.wait_for(self.browser.find_element_by_class_name, "results")
def send_invite(voter): """ Send a mail to the voter for an election """ email = voter.user.email login_token = utils.get_parameters(voter.user) if PORT != 80: login_link = "http://{}:{:d}/vote/{}/?url_auth_token={}".format( DOMAIN, PORT, voter.election.pk, login_token['url_auth_token'] ) else: login_link = "http://{}/vote/{}/?url_auth_token={}".format( DOMAIN, voter.election.pk, login_token['url_auth_token'] ) name = voter.user.first_name.title() + " " + voter.user.last_name.title() html_message = format_lazy(""" <p>Dear {name},</p> <p>You have been invited to participate to <a href="{login_link}"> {election_name}</a>. </p> <p>If this link does not work, you can copy/paste the following link:</p> <p><a href="{login_link}">{login_link}</a></p> <p>Thanks,</p> <p>Mieux Voter</p> """, name=name, login_link=login_link, election_name=voter.election.name) send_mail( _('Invite to vote at ') + voter.election.name, html_message, DEFAULT_FROM_EMAIL, [email], fail_silently=False, html_message=html_message )
def form_valid(self, form): """Forward the user, no matter if we found them or not. Don't want to leak email existance information. """ if form.is_valid(): next_url = self.get_success_url() email = form.cleaned_data['email'] try: user = UserModel.objects.get(email=email) token_params = token_utils.get_parameters(user.profile) token_str = token_params['url_auth_token'] abs_url = "{}?token={}&next={}".format( self.request.build_absolute_uri(reverse(email_token_login)), token_str, next_url) mailutils.send_email(user.email, 'Jacobs Alumni Association - Login Link', 'emails/token_email.html', name=user.firstName, login_url=abs_url) except UserModel.DoesNotExist: # Can't complain to the user here, or we'll give away that we don't know this address. pass return HttpResponseRedirect(reverse('token_sent'))
def test_get_parameters(self): self.assertEqual(get_parameters(self.user), {"sesame": get_token(self.user)})
def test_one_time_token(self): response = self.client.get("/", get_parameters(self.user)) self.assertUserLoggedIn(response, redirect_url="/")
def test_bad_token(self): params = get_parameters(self.user) params["sesame"] = params["sesame"].lower() response = self.client.get("/", params) self.assertUserNotLoggedIn(response)
def test_token_in_iOS_request(self): response = self.client.get("/", get_parameters(self.user), HTTP_USER_AGENT=CHROME_IOS_USER_AGENT) self.assertUserLoggedIn(response, redirect_url=None)
def test_token_with_path_and_params(self): params = get_parameters(self.user) params["bar"] = 42 response = self.client.get("/foo", params) self.assertUserLoggedIn(response, redirect_url="/foo?bar=42")
def get_request_with_token(self): return RequestFactory().get("/", get_parameters(self.user))
def test_get_parameters(self): self.assertEqual(list(get_parameters(self.user)), ['url_auth_token'])
def email_user(email_address, status): person = Person.objects.get(email_address=email_address) person_id = person.id fields = FIELDS_PUBLIC ## abstracted to use same fields as the submission form fields.append('status') ## add status field bc it's not included in the SubmitForm and it's necessary for sending email person = Person.objects.filter(email_address=email_address).values(*fields).exclude()[0] person_info = '<table>' spaces = ' ' * 5 ## loop thru and unpack values for key, value in person.items(): if value: new_key = key.title().replace('_', ' ') person_info += '\ <tr> \ <td><b>{}</b>:</td> \ <td>{}</td> \ <td>{}</td>\ </tr>'.format( new_key, spaces, value ) person_info += '</table>' admin_url = '{}/admin/sources/person/{}/change/'.format(SITE_URL, person_id) ## django-sesame bits for magic link user = User.objects.get(email=email_address) # login_token = utils.get_query_string(user) ## using their URL login_token = utils.get_parameters(user) ## making your own URL login_link = '{}?method=magic&url_auth_token={}'.format(admin_url, login_token['url_auth_token']) ## change from admin url to live url? ## confirmation url (for both user and admin?) confirm_token = account_confirmation_token.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) confirm_url = '{}/confirmation/{}/{}'.format( SITE_URL, uid.decode(), confirm_token ) status = person['status'] status_type = status.split('_')[0] message = '' if status_type == 'added': subject_title = 'Please confirm your profile' # if status == 'added_by_self': # subject_title += 'yourself' # elif status == 'added_by_other': # subject_title += 'someone else' # elif status == 'added_by_admin': # subject_title += 'an admin' html_message = '\ <p>{project_name} is a searchable database of underrepresented experts in the areas of science, health and the environment. Anyone who considers themselves underrepresented and is willing to respond to journalists on deadline is encouraged to join (including but not limited to appearance, ethnicity, gender expression, gender identity, language, mental health experience, nationality, physical abilities, race, religion, sex, sexual orientation, etc.).</p> \ <p>This database aims to make it easy for journalists and others to include a wider range of backgrounds, experiences and perspectives in their work. By doing so, we can improve our coverage and better reflect the world we cover.</p> \ <p>To confirm you would like be included in the {project_name} public database and to confirm the following information is correct, please click here:</p> \ <p>{confirm_url}</p> \ <p>{person_info}</p> \ <p>If the information is incorrect, please edit your entry:</p> \ <p>{login_link}</p> \ <p>View the database:</p> \ <p>{site_url}</p>\ '.format( project_name=PROJECT_NAME, confirm_url=confirm_url, person_info=person_info, login_link=login_link, site_url=SITE_URL ) # elif status_type == 'approved': # subject_title = 'You have been approved as a source!' # html_message = 'Congratulations! Your entry has been approved and now be viewed or updated by you here: {}'.format(person_url) subject = '[{}] {}'.format(PROJECT_NAME, subject_title) sender = EMAIL_SENDER recipients = [email_address] # reply_email = sender send_mail( subject, message, sender, recipients, # reply_to=[reply_email], html_message=html_message, fail_silently=False, )
def generate_login_token(user: User) -> str: """ Generates a login token for a user """ token_params = token_utils.get_parameters(user) return token_params['url_auth_token']
def test_get_parameters_with_scope(self): self.assertEqual( get_parameters(self.user, scope="test"), {"sesame": get_token(self.user, scope="test")}, )
def test_one_time_token_num_queries(self): with self.assertNumQueries(self.ONE_TIME_NUM_QUERIES): response = self.client.get("/", get_parameters(self.user)) self.assertUserLoggedIn(response, redirect_url="/")
def test_get_user_request(self): request = RequestFactory().get("/", get_parameters(self.user)) self.assertEqual(get_user(request), self.user)
def test_get_parameters(self): self.assertEqual(list(get_parameters(self.user)), ["url_auth_token"])