Пример #1
0
    def test_welcome_mail_for_verified_email(self):
        Switch.objects.get_or_create(name='welcome_email', active=True)
        testuser = user(username='******',
                        email='*****@*****.**',
                        password='******',
                        save=True)
        request = self.setup_request_for_messages()
        self.get_messages(request)
        user_signed_up.send(sender=testuser.__class__,
                            request=request,
                            user=testuser)

        # no email sent
        self.assertEqual(len(mail.outbox), 0)

        EmailAddress.objects.create(user=testuser,
                                    email='*****@*****.**',
                                    verified=True)

        user_signed_up.send(sender=testuser.__class__,
                            request=request,
                            user=testuser)

        # only one email, the welcome email, is sent, no confirmation needed
        self.assertEqual(len(mail.outbox), 1)
        welcome_email = mail.outbox[0]
        expected_to = [testuser.email]
        self.assertEqual(expected_to, welcome_email.to)
        self.assertTrue(u'utm_campaign=welcome' in welcome_email.body)
Пример #2
0
    def test_welcome_mail_for_verified_email(self):
        testuser = create_user(
            username="******",
            email="*****@*****.**",
            password="******",
            save=True,
        )
        request = self.setup_request_for_messages()
        self.get_messages(request)
        user_signed_up.send(sender=testuser.__class__,
                            request=request,
                            user=testuser)

        # no email sent
        self.assertEqual(len(mail.outbox), 0)

        EmailAddress.objects.create(user=testuser,
                                    email="*****@*****.**",
                                    verified=True)

        user_signed_up.send(sender=testuser.__class__,
                            request=request,
                            user=testuser)

        # only one email, the welcome email, is sent, no confirmation needed
        self.assertEqual(len(mail.outbox), 1)
        welcome_email = mail.outbox[0]
        expected_to = [testuser.email]
        self.assertEqual(expected_to, welcome_email.to)
Пример #3
0
    def test_auto_activiate_if_qualified_after_signup(self, mock_vouched):
        """Users qualified after sign-up should be auto-activated on sign-in"""
        mock_vouched.return_value = False

        sociallogin = SocialLogin(user=self.user)

        self.user.is_active = True
        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)

        self.assertEqual(False, self.user.is_active)

        pre_social_login.send(sender=SocialLogin,
                              request=None,
                              sociallogin=sociallogin)

        self.assertEqual(False, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(True, profile.invite_pending)

        mock_vouched.return_value = True

        pre_social_login.send(sender=SocialLogin,
                              request=None,
                              sociallogin=sociallogin)

        self.assertEqual(True, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(False, profile.invite_pending)
Пример #4
0
    def test_welcome_mail_for_verified_email(self):
        Switch.objects.get_or_create(name='welcome_email', active=True)
        u = user(username='******',
                 email='*****@*****.**',
                 password='******',
                 save=True)
        request = RequestFactory().get('/')
        request.locale = 'en-US'
        user_signed_up.send(sender=u.__class__, request=request, user=u)

        # no email sent
        eq_(len(mail.outbox), 0)

        EmailAddress.objects.create(user=u,
                                    email='*****@*****.**',
                                    verified=True)

        user_signed_up.send(sender=u.__class__, request=request, user=u)

        # only one email, the welcome email, is sent, no confirmation needed
        eq_(len(mail.outbox), 1)
        welcome_email = mail.outbox[0]
        expected_to = [u.email]
        eq_(expected_to, welcome_email.to)
        ok_(u'utm_campaign=welcome' in welcome_email.body)
Пример #5
0
 def test_setting(self):
     user = get_user_model().objects.create_user("user_a",
                                                 "user_a@localhost",
                                                 "user_a")
     user_signed_up.send(sender=None, request=None, user=user)
     assert user.is_verified_user == True
     assert user.status == "ok"
Пример #6
0
    def test_welcome_mail_for_verified_email(self):
        Switch.objects.get_or_create(name='welcome_email', active=True)
        u = user(username='******',
                 email='*****@*****.**',
                 password='******',
                 save=True)
        request = RequestFactory().get('/')
        request.locale = 'en-US'
        user_signed_up.send(sender=u.__class__, request=request, user=u)

        # no email sent
        eq_(len(mail.outbox), 0)

        EmailAddress.objects.create(user=u,
                                    email='*****@*****.**',
                                    verified=True)

        user_signed_up.send(sender=u.__class__, request=request, user=u)

        # only one email, the welcome email, is sent, no confirmation needed
        eq_(len(mail.outbox), 1)
        welcome_email = mail.outbox[0]
        expected_to = [u.email]
        eq_(expected_to, welcome_email.to)
        ok_(u'utm_campaign=welcome' in welcome_email.body)
Пример #7
0
    def test_welcome_mail_for_verified_email(self):
        Switch.objects.get_or_create(name='welcome_email', active=True)
        testuser = user(username='******', email='*****@*****.**',
                        password='******', save=True)
        request = self.setup_request_for_messages()
        self.get_messages(request)
        user_signed_up.send(sender=testuser.__class__, request=request,
                            user=testuser)

        # no email sent
        self.assertEqual(len(mail.outbox), 0)

        EmailAddress.objects.create(user=testuser,
                                    email='*****@*****.**',
                                    verified=True)

        user_signed_up.send(sender=testuser.__class__, request=request,
                            user=testuser)

        # only one email, the welcome email, is sent, no confirmation needed
        self.assertEqual(len(mail.outbox), 1)
        welcome_email = mail.outbox[0]
        expected_to = [testuser.email]
        self.assertEqual(expected_to, welcome_email.to)
        self.assertTrue(u'utm_campaign=welcome' in welcome_email.body)
Пример #8
0
    def test_invite_only_signup(self, mock_vouched):
        """User.is_active should be False on signup with invite mode"""
        mock_vouched.return_value = False
        self.user.is_active = True
        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)

        self.assertEqual(False, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(True, profile.invite_pending)
Пример #9
0
 def test_signup_uninvited(self):
     """
     A 404 error should be returned if a user who has not been invited
     tries to sign up.
     """
     request = self.factory.get(reverse('authentication-signup'))
     self.middleware.process_request(request)
     request.session.save()
     with self.assertRaises(Http404):
         user_signed_up.send(sender=self.surveyor_user.__class__,
                             request=request,
                             user=self.surveyor_user)
Пример #10
0
    def test_open_signup(self, mock_vouched):
        """User.is_active should be True on signup without invite mode"""
        self.user.is_active = True
        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)
        self.assertEqual(True, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(False, profile.invite_pending)

        mock_vouched.assert_not_called()
Пример #11
0
    def test_invite_only_mozillians_autoactivation(self, mock_vouched):
        """Users vouched on mozillians.org should be auto-activated"""
        mock_vouched.return_value = True
        self.user.is_active = True
        self.user.email = '*****@*****.**'

        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)

        self.assertEqual(True, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(False, profile.invite_pending)
Пример #12
0
 def test_organisation_created(self):
     """
     An organisation should be created if a Surveyor signs up
     through `/create-organisation`.
     """
     request = self.factory.get(reverse('authentication-signup'))
     self.middleware.process_request(request)
     request.session['organisation_name'] = 'Organisation'
     request.session.save()
     user_signed_up.send(sender=self.surveyor_user.__class__,
                         request=request,
                         user=self.surveyor_user)
     self.assertTrue(
         Organisation.objects.filter(name='Organisation').exists())
Пример #13
0
 def test_user_signed_up(self):
     Profile.objects.get(user=self.user).delete()
     EmailAddress.objects.create(user=self.user,
                                 email=self.user.email,
                                 verified=True)
     EmailAddress.objects.create(user=self.user,
                                 email='*****@*****.**',
                                 verified=False)
     with patch('django_mailman3.signals.add_address_to_mailman_user') \
             as aatmu:
         user_signed_up.send(sender=User, user=self.user)
     self.assertEqual(aatmu.call_args_list,
                      [call(self.user, self.user.email)])
     self.assertTrue(Profile.objects.filter(user=self.user).exists())
Пример #14
0
    def test_signup_getting_started_message(self):
        testuser = user(username='******', email='*****@*****.**',
                        password='******', save=True)
        request = self.setup_request_for_messages()
        messages = self.get_messages(request)
        self.assertEqual(len(messages), 0)

        user_signed_up.send(sender=testuser.__class__, request=request,
                            user=testuser)

        queued_messages = list(messages)
        self.assertEqual(len(queued_messages), 1)
        self.assertEqual(django_messages.SUCCESS, queued_messages[0].level)
        self.assertTrue('getting started' in queued_messages[0].message)
Пример #15
0
    def test_signup_getting_started_message(self):
        testuser = user(username='******', email='*****@*****.**',
                        password='******', save=True)
        request = self.setup_request_for_messages()
        messages = self.get_messages(request)
        self.assertEqual(len(messages), 0)

        user_signed_up.send(sender=testuser.__class__, request=request,
                            user=testuser)

        queued_messages = list(messages)
        self.assertEqual(len(queued_messages), 1)
        self.assertEqual(django_messages.SUCCESS, queued_messages[0].level)
        self.assertTrue('getting started' in queued_messages[0].message)
Пример #16
0
 def mutate_and_get_payload(cls, root, info, email, password, username, name='Someone'):
     # print('>> join')
     user = User.objects.create_user(username, email, password, name=name)
     Token.objects.get_or_create(user=user)
     user = authenticate(
         email=email,
         password=password,
     )
     user_signed_up.send(
         sender=user.__class__,
         request=info,
         user=user
     )
     return JoinMutation(user=user, token=user.auth_token)
Пример #17
0
    def test_newuser_log_event(self):
        """testpilot.newuser log event should be emitted on signup"""
        self.user.is_active = True
        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)

        self.assertEquals(len(self.handler.records), 1)
        record = self.handler.records[0]

        details = json.loads(self.formatter.format(record))
        self.assertTrue('Fields' in details)

        fields = details['Fields']
        self.assertEqual(fields['uid'], self.user.id)
Пример #18
0
 def mutate_and_get_payload(cls,
                            root,
                            info,
                            email,
                            password,
                            username,
                            name='Someone'):
     # print('>> join')
     user = User.objects.create_user(username, email, password, name=name)
     Token.objects.get_or_create(user=user)
     user = authenticate(
         email=email,
         password=password,
     )
     user_signed_up.send(sender=user.__class__, request=info, user=user)
     return JoinMutation(user=user, token=user.auth_token)
Пример #19
0
    def test_invite_only_mozillacom_autoactivation(self, mock_vouched):
        """Users with @mozilla.com email addresses should be auto-activated"""
        mock_vouched.return_value = False
        self.user.is_active = True
        self.user.email = '*****@*****.**'

        user_signed_up.send(sender=self.user.__class__,
                            request=None,
                            user=self.user)

        self.assertEqual(True, self.user.is_active)

        profile = UserProfile.objects.get_profile(self.user)
        self.assertEqual(False, profile.invite_pending)

        mock_vouched.assert_not_called()
Пример #20
0
    def get(self, request, *args, **kwargs):
        template_html = 'account/login.html'

        # 如果申请登陆页面成功后,就会返回code和state
        if 'code' not in request.GET:
            return render(request, template_html)

        code = request.GET('code')
        # 第二步
        # 将得到的code,通过下面的url请求得到access_token
        url = 'https://github.com/login/oauth/access_token'
        data = {
            'grant_type': 'authorization_code',
            'client_id': settings.GITHUB_CLIENTID,
            'client_secret': settings.GITHUB_CLIENTSECRET,
            'code': code,
            'redirect_uri': settings.GITHUB_CALLBACK,
        }

        # 请求参数需要bytes类型
        binary_data = urlencode(data).encode('utf-8')
        # 设置请求返回的数据类型
        headers = {'Accept': 'application/json'}
        req = Request(url, binary_data, headers)
        # json是str类型的,将bytes转成str
        result = json.loads(urlopen(req).read().decode('utf-8'))
        access_token = result['access_token']
        url2 = 'https://api.github.com/user?access_token=%s' % (access_token)
        response = json.loads(urlopen(url2).read().decode('utf-8'))
        print(response)
        username = '******' + str(response['id'])
        password = '******'

        # 如果不存在username,则创建
        try:
            user = User.objects.get(username=username)
        except:
            user = User.objects.create_user(username=username,
                                            password=password)
            user.save()
            user_signed_up.send(sender=self, request=request, user=user)

        # 登陆认证
        user = auth.authenticate(username=username, password=password)
        auth.login(request, user, backend=None)
        user_logged_in.send(sender=self, request=request, user=user)
        return super().get(self, request, *args, **kwargs)
Пример #21
0
    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        new_user = serializer.instance
        user_signed_up.send(sender=self.__class__, request=request, user=new_user)

        # Creo un token para el nuevo usuario
        token, created = Token.objects.get_or_create(user=new_user)
        headers = self.get_success_headers(serializer.data)

        # Y lo agrego a la respuesta que se le envía
        request_data = request.data
        request_data['token'] = token.key
        request_data['user_profile'] = UserProfileSerializer(new_user.profile).data
        return Response(request_data, status=status.HTTP_201_CREATED, headers=headers)
Пример #22
0
def registration(request, form_class=RegistrationForm):
    if not settings.ACCOUNT_REGISTRATION_ENABLED:
        return message_view(request, _('Sorry. Registration is disabled.'))
    if request.user.is_authenticated():
        return message_view(request, _('You have to logout before registration'))

    if 'POST' == request.method:
        form = form_class(request.POST, request.FILES)
    else:
        form = form_class()

    if form.is_valid():
        if form.cleaned_data['username'].endswith('mesuchesy'):
            # handling a possible spam user registration 2019/03/25
            return message_view(request, _('Sorry. Registration is disabled.'))

        user = form.save(request)

        user_signed_up.send(None, user=user, request=request)
        password = form.cleaned_data['password1']

        hostname = Site.objects.get_current().domain
        if settings.ACCOUNT_ACTIVATION_REQUIRED:
            url = 'http://%s%s' % (hostname, reverse('registration_complete'))
            url = wrap_url(url, uid=user.id, action='activation')
            params = {'domain': hostname, 'login': user.username, 'url': url,
                      'password': password}
            if email_template(user.email, 'account/mail/activation_required', **params):
                next_url = reverse('activation_required')
                if form.cleaned_data.get('signup_ann', False):
                    next_url += '?email=' + user.email
                return HttpResponseRedirect(next_url)
            else:
                user.delete()
                msg = ('The error was occuried while sending email '
                       'with activation code. Account was not created. '
                       'Please, try later.')
                return message_view(request, _(msg))
        else:
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            auth.login(request, user)
            args = {'domain': hostname, 'user': user, 'password': password}
            email_template(user.email, 'account/mail/registration_complete', **args)
            return redirect(reverse(settings.ACCOUNT_REGISTRATION_REDIRECT_URLNAME))

    return {'form': form}
Пример #23
0
 def test_signup_from_invite_surveyor(self):
     """
     A Surveyor object should be created if a Respondent signs up
     by accepting an invite.
     """
     organisation = Organisation.objects.create(name='Organisation')
     UserInvitation.create(self.surveyor_user.email,
                           organisation=organisation,
                           is_respondent=False)
     request = self.factory.get(reverse('authentication-signup'))
     self.middleware.process_request(request)
     request.session.save()
     user_signed_up.send(sender=self.surveyor_user.__class__,
                         request=request,
                         user=self.surveyor_user)
     self.assertTrue(
         Surveyor.objects.filter(
             firstname=self.surveyor_user.first_name).exists())
Пример #24
0
 def test_signup_from_invite_respondent(self):
     """
     A Respondent object should be created if a Respondent signs up
     by accepting an invite.
     """
     group = Group.objects.create(name='Group')
     UserInvitation.create(self.respondent_user.email,
                           group=group,
                           is_respondent=True)
     request = self.factory.get(reverse('authentication-signup'))
     self.middleware.process_request(request)
     request.session.save()
     user_signed_up.send(sender=self.respondent_user.__class__,
                         request=request,
                         user=self.respondent_user)
     self.assertTrue(
         Respondent.objects.filter(
             firstname=self.respondent_user.first_name).exists())
Пример #25
0
    def test_invite_only_account_autoactivation_domains(self, mock_vouched):
        """Users with valid email address domains should be auto-activated"""
        mock_vouched.return_value = False
        self.user.is_active = True

        for email in ['*****@*****.**', '*****@*****.**']:

            self.user.email = email

            user_signed_up.send(sender=self.user.__class__,
                                request=None,
                                user=self.user)

            self.assertEqual(True, self.user.is_active)

            profile = UserProfile.objects.get_profile(self.user)
            self.assertEqual(False, profile.invite_pending,
                             'Invite not expected for {0}'.format(email))

            mock_vouched.assert_not_called()
            mock_vouched.reset_mock()

        for email in ['*****@*****.**', '[email protected]@aol.com']:

            self.user.email = email

            user_signed_up.send(sender=self.user.__class__,
                                request=None,
                                user=self.user)

            self.assertEqual(False, self.user.is_active)

            profile = UserProfile.objects.get_profile(self.user)
            self.assertEqual(True, profile.invite_pending,
                             'Invite expected for {0}'.format(email))

            mock_vouched.assert_called_once_with(self.user)
            mock_vouched.reset_mock()
Пример #26
0
    def test_auto_activate_after_settings_change(self, mock_vouched):
        """Pending invitations should be auto-activated on sign-in after invite mode turned off"""
        mock_vouched.return_value = False
        sociallogin = SocialLogin(user=self.user)

        with self.settings(ACCOUNT_INVITE_ONLY_MODE=True):

            self.user.is_active = True
            user_signed_up.send(sender=self.user.__class__,
                                request=None,
                                user=self.user)

            self.assertEqual(False, self.user.is_active)

            profile = UserProfile.objects.get_profile(self.user)
            self.assertEqual(True, profile.invite_pending)

            pre_social_login.send(sender=SocialLogin,
                                  request=None,
                                  sociallogin=sociallogin)

            self.assertEqual(False, self.user.is_active)

            profile = UserProfile.objects.get_profile(self.user)
            self.assertEqual(True, profile.invite_pending)

        with self.settings(ACCOUNT_INVITE_ONLY_MODE=False):

            pre_social_login.send(sender=SocialLogin,
                                  request=None,
                                  sociallogin=sociallogin)

            self.assertEqual(True, self.user.is_active)

            profile = UserProfile.objects.get_profile(self.user)
            self.assertEqual(False, profile.invite_pending)
Пример #27
0
    def save_task(self, validated_data, instance=None):
        current_user = self.get_current_user()
        if current_user and current_user.is_authenticated(
        ) and not instance and not profile_check(current_user):
            ValidationError(
                'You need complete your profile before you can post tasks')

        if instance and 'fee' in validated_data and validated_data[
                'fee'] < instance.fee:
            raise ValidationError({
                'fee':
                'You cannot reduce the fee for the task, Please contact [email protected] for assistance'
            })

        skills = None
        participation = None
        milestones = None
        participants = None
        ratings = None
        if 'skills' in validated_data:
            skills = validated_data.pop('skills')
        if 'participation' in validated_data:
            participation = validated_data.pop('participation')
        if 'milestones' in validated_data:
            milestones = validated_data.pop('milestones')
        if 'participants' in validated_data:
            participants = validated_data.pop('participants')
        if 'ratings' in validated_data:
            ratings = validated_data.pop('ratings')

        initial_apply = True
        initial_closed = False
        initial_approved = False
        new_user = None
        is_update = bool(instance)

        if instance:
            initial_apply = instance.apply
            initial_closed = instance.closed
            initial_approved = instance.approved

            if not instance.closed and validated_data.get('closed'):
                validated_data['closed_at'] = datetime.datetime.utcnow()

            if not instance.paid and validated_data.get('paid'):
                validated_data['paid_at'] = datetime.datetime.utcnow()
            instance = super(TaskSerializer,
                             self).update(instance, validated_data)
        else:
            if not current_user or not current_user.is_authenticated():
                validated_data['source'] = TASK_SOURCE_NEW_USER
            if participation or participants:
                # Close applications if paticipants are provided when creating task
                validated_data['apply'] = False
                validated_data['apply_closed_at'] = datetime.datetime.utcnow()

            if not current_user or not current_user.is_authenticated():
                # Create user and add them as the creator or task, indicate if task was unauthenticated
                email = self.initial_data.get('email', None)
                first_name = self.initial_data.get('first_name', None)
                last_name = self.initial_data.get('last_name', None)

                new_user = get_user_model().objects.create_user(
                    username=email,
                    email=email,
                    password=get_user_model().objects.make_random_password(),
                    first_name=first_name,
                    last_name=last_name,
                    type=USER_TYPE_PROJECT_OWNER,
                    source=USER_SOURCE_TASK_WIZARD)
                if new_user:
                    validated_data.update({'user': new_user})
                    user_signed_up.send(sender=get_user_model(),
                                        request=None,
                                        user=new_user)

            instance = super(TaskSerializer, self).create(validated_data)

        self.save_skills(instance, skills)
        self.save_participants(instance, participants)
        self.save_participation(instance, participation)
        self.save_milestones(instance, milestones)
        self.save_ratings(instance, ratings)

        if is_update:
            if not initial_approved and instance.approved:
                task_approved.send(sender=Task, task=instance)

            if initial_apply and not instance.apply:
                task_applications_closed.send(sender=Task, task=instance)

            if not initial_closed and instance.closed:
                task_closed.send(sender=Task, task=instance)
        else:
            # Triggered here instead of in the post_save signal to allow skills to be attached first
            # TODO: Consider moving this trigger
            notify_new_task.delay(instance.id, new_user=bool(new_user))
        return instance