def test_encode_decode_pk_reversible(self): """ Ensure that encoding a PK, then decoding it returns the original value """ for i in range(50): random_pk = randint(1, 10000) encoded = encode_pk(random_pk) decoded = decode_pk(encoded) if str(random_pk) != decoded: self.fail(("Encoding then decoding PK '%d' did not return " "original value.\nEncoded: %s\tDecoded: %s") % \ (random_pk, encoded, decoded))
def verify_token(request, pk_base64, token): """ Verifies a token generated for validating an email address, and notifies the user whether verification was successful. """ next_url = request.GET.get('next') or request.GET.get(REDIRECT_FIELD_NAME) context = {'next_url': next_url, 'is_signup': False} user_model = get_user_model() # Attempt to get the linked email to verify try: email_pk = decode_pk(pk_base64) email = LinkedEmail.objects.get(pk=email_pk) except (TypeError, ValueError, OverflowError, user_model.DoesNotExist, LinkedEmail.DoesNotExist): email = None # In the unlikely scenario that a user is trying to sign up # with an email another verified user has as a primary email # address, reject verification immediately if email is not None and is_tmp_user(email.profile.user) and \ get_user_model().objects.filter(email=email.address).exists(): email = None # If the token successfully verifies, update the linked email if email is not None and token_generator.check_token(email, token): email.is_verified = True email.save() # If the user this email is linked to is a temporary # one, change it to a fully registered user user = email.profile.user if is_tmp_user(user) or is_unlinked_account(user): context['is_signup'] = True old_username = user.username # Change the email + username to the verified email user.email = email.address user.username = choose_username(user.email) user.save() # If the user was created via CAS, add the institution # account described by the temporary username if old_username.startswith("cas"): username_split = get_account_username_split(old_username) _add_institution_account(user.profile, username_split[1], username_split[2]) # If UNIAUTH_ALLOW_SHARED_EMAILS is False, and there were # pending LinkedEmails for this address on other accounts, # delete them if not get_setting('UNIAUTH_ALLOW_SHARED_EMAILS'): LinkedEmail.objects.filter(address=email.address, is_verified=False).delete() return render(request, 'uniauth/verification-success.html', context) # If anything went wrong, just render the failed verification template else: return render(request, 'uniauth/verification-failure.html', context)