コード例 #1
0
ファイル: test_release.py プロジェクト: zeuskingzb/sentry
    def test_get_user_from_email(self):
        user = User.objects.create(email="*****@*****.**")
        UserEmail.get_primary_email(user=user)
        project = self.create_project()
        self.create_member(user=user, organization=project.organization)
        release = Release.objects.create(
            organization_id=project.organization_id, version=uuid4().hex, new_groups=1
        )
        release.add_project(project)
        commit_author = CommitAuthor.objects.create(
            name="stebe", email="*****@*****.**", organization_id=project.organization_id
        )
        commit = Commit.objects.create(
            organization_id=project.organization_id,
            repository_id=1,
            key="abc",
            author=commit_author,
            message="waddap",
        )
        ReleaseCommit.objects.create(
            organization_id=project.organization_id,
            project_id=project.id,
            release=release,
            commit=commit,
            order=1,
        )
        release.update(
            authors=[six.text_type(commit_author.id)], commit_count=1, last_commit_id=commit.id
        )

        result = serialize(release, user)
        result_author = result["authors"][0]
        assert int(result_author["id"]) == user.id
        assert result_author["email"] == user.email
        assert result_author["username"] == user.username
コード例 #2
0
ファイル: accounts.py プロジェクト: twolfson/sentry
def account_settings(request):
    user = request.user

    form = AccountSettingsForm(
        user, request, request.POST or None,
        initial={
            'email': UserEmail.get_primary_email(user).email,
            'username': user.username,
            'name': user.name,
        },
    )

    if form.is_valid():
        old_email = user.email

        form.save()

        # remove previously valid email address
        # TODO(dcramer): we should maintain validation here when we support
        # multiple email addresses
        if request.user.email != old_email:
            UserEmail.objects.filter(user=user, email=old_email).delete()
            try:
                with transaction.atomic():
                    user_email = UserEmail.objects.create(
                        user=user,
                        email=user.email,
                    )
            except IntegrityError:
                pass
            else:
                user_email.set_hash()
                user_email.save()
                user.send_confirm_email_singular(user_email)
                msg = _('A confirmation email has been sent to %s.') % user_email.email
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    msg)

        messages.add_message(
            request, messages.SUCCESS, _('Your settings were saved.'))
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update({
        'form': form,
        'page': 'settings',
        'has_2fa': Authenticator.objects.user_has_2fa(request.user),
        'AUTH_PROVIDERS': auth.get_auth_providers(),
        'email': UserEmail.get_primary_email(user),
        'has_newsletters': newsletter.is_enabled,
    })
    return render_to_response('sentry/account/settings.html', context, request)
コード例 #3
0
ファイル: test_releases.py プロジェクト: zanjs/sentry
    def test_assigns_author(self):
        group = self.create_group()
        user = self.create_user(name='Foo Bar',
                                email='*****@*****.**',
                                is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(
            organization=group.project.organization, user=user)
        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message='Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            ))

        assert GroupCommitResolution.objects.filter(
            group_id=group.id,
            commit_id=commit.id,
        ).exists()

        assert GroupAssignee.objects.filter(group=group, user=user).exists()
コード例 #4
0
ファイル: user_subscriptions.py プロジェクト: Kayle009/sentry
    def put(self, request, user):
        """
        Update Account Subscriptions
        ````````````````````````````

        Update account subscriptions to newsletter

        :param int listId: id of newsletter list
        :param boolean subscribed: should be subscribed to newsletter
        :auth: required
        """
        validator = NewsletterValidator(data=request.DATA)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        result = validator.object
        email = UserEmail.get_primary_email(user)

        kwargs = {
            'list_id': result['listId'],
            'subscribed': result['subscribed'],
            'verified': email.is_verified,
        }
        if not result['subscribed']:
            kwargs['unsubscribed_date'] = timezone.now()
        else:
            kwargs['subscribed_date'] = timezone.now()

        newsletter.create_or_update_subscription(user, **kwargs)
        return self.respond(status=204)
コード例 #5
0
    def delete(self, request, user):
        """
        Removes an email from account
        `````````````````````````````

        Removes an email from account, can not remove primary email

        :param string email: email to remove
        :auth required:
        """
        validator = EmailValidator(data=request.DATA)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        email = validator.object['email']
        primary_email = UserEmail.get_primary_email(user)
        del_email = UserEmail.objects.filter(user=user,
                                             email__iexact=email).first()

        # Don't allow deleting primary email?
        if primary_email == del_email:
            return self.respond({'detail': 'Cannot remove primary email'},
                                status=400)

        del_email.delete()

        logger.info('user.email.remove',
                    extra={
                        'user_id': user.id,
                        'ip_address': request.META['REMOTE_ADDR'],
                        'email': email,
                    })

        return self.respond(status=204)
コード例 #6
0
ファイル: useremail.py プロジェクト: liang0/sentry-1
 def serialize(self, obj, attrs, user):
     primary_email = UserEmail.get_primary_email(user)
     return {
         "email": obj.email,
         "isPrimary": obj.email == primary_email.email,
         "isVerified": obj.is_verified,
     }
コード例 #7
0
 def serialize(self, obj, attrs, user):
     primary_email = UserEmail.get_primary_email(user)
     return {
         'email': obj.email,
         'isPrimary': obj.email == primary_email.email,
         'isVerified': obj.is_verified,
     }
コード例 #8
0
ファイル: test_releases.py プロジェクト: liang0/sentry-1
    def test_matching_author_without_assignment(self):
        group = self.create_group()
        user = self.create_user(name="Foo Bar", email="*****@*****.**", is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(name="example", organization_id=self.group.organization.id)
        OrganizationMember.objects.create(organization=group.project.organization, user=user)
        UserOption.objects.set_value(user=user, key="self_assign_issue", value="0")

        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message=u"Foo Biz\n\nFixes {}".format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id, name=user.name, email=user.email
            ),
        )

        self.assertResolvedFromCommit(group, commit)

        assert not Activity.objects.filter(
            project=group.project, group=group, type=Activity.ASSIGNED, user=user
        ).exists()

        assert GroupSubscription.objects.filter(group=group, user=user).exists()
コード例 #9
0
ファイル: test_releases.py プロジェクト: duanshuaimin/sentry
    def test_assigns_author(self):
        group = self.create_group()
        user = self.create_user(name='Foo Bar', email='*****@*****.**', is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(organization=group.project.organization, user=user)
        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message='Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            )
        )

        assert GroupCommitResolution.objects.filter(
            group_id=group.id,
            commit_id=commit.id,
        ).exists()

        assert GroupAssignee.objects.filter(
            group=group,
            user=user
        ).exists()
コード例 #10
0
ファイル: user_subscriptions.py プロジェクト: Kayle009/sentry
    def post(self, request, user):
        """
        Configure Newsletter Subscription
        `````````````````````````````````

        Update the default newsletter subscription.

        :param boolean subscribed: should be subscribed to newsletter
        :auth: required
        """
        validator = DefaultNewsletterValidator(data=request.DATA)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        result = validator.object
        email = UserEmail.get_primary_email(user)

        kwargs = {
            'subscribed': result['subscribed'],
            'verified': email.is_verified,
            'list_ids': newsletter.get_default_list_ids(),
        }
        if not result['subscribed']:
            kwargs['unsubscribed_date'] = timezone.now()
        else:
            kwargs['subscribed_date'] = timezone.now()

        newsletter.create_or_update_subscriptions(user, **kwargs)

        user.update(
            flags=F('flags').bitand(~User.flags.newsletter_consent_prompt),
        )

        return self.respond(status=204)
    def delete(self, request, user):
        """
        Removes an email from account
        `````````````````````````````

        Removes an email from account, can not remove primary email

        :param string email: email to remove
        :auth required:
        """

        email = request.DATA.get('email')
        primary_email = UserEmail.get_primary_email(user)
        del_email = UserEmail.objects.filter(user=user, email=email)[0]

        # Don't allow deleting primary email?
        if primary_email == del_email:
            return Response({'detail': 'Cannot remove primary email'},
                            status=status.HTTP_400_BAD_REQUEST)

        del_email.delete()

        logger.info(
            'user.email.remove',
            extra={
                'user_id': user.id,
                'ip_address': request.META['REMOTE_ADDR'],
                'email': email,
            }
        )

        return Response(status=status.HTTP_204_NO_CONTENT)
コード例 #12
0
ファイル: accounts.py プロジェクト: hosmelq/sentry
def manage_subscriptions(request):
    user = request.user
    email = UserEmail.get_primary_email(user)

    if request.method == 'GET':
        context = csrf(request)
        context.update(
            {
                'page': 'subscriptions',
                'email': email,
                'AUTH_PROVIDERS': auth.get_auth_providers(),
                'has_newsletters': newsletter.is_enabled,
                'subscriptions': newsletter.get_subscriptions(user),
            }
        )
        return render_to_response('sentry/account/subscriptions.html', context, request)

    subscribed = request.POST.get('subscribed') == '1'
    try:
        list_id = int(request.POST.get('listId', ''))
    except ValueError:
        return HttpResponse('bad request', status=400)

    kwargs = {
        'list_id': list_id,
        'subscribed': subscribed,
        'verified': email.is_verified,
    }
    if not subscribed:
        kwargs['unsubscribed_date'] = timezone.now()
    else:
        kwargs['subscribed_date'] = timezone.now()

    newsletter.create_or_update_subscription(user, **kwargs)
    return HttpResponse()
コード例 #13
0
    def put(self, request, user):
        """
        Update Account Subscriptions
        ````````````````````````````

        Update account subscriptions to newsletter

        :param int listId: id of newsletter list
        :param boolean subscribed: should be subscribed to newsletter
        :auth: required
        """
        validator = NewsletterValidator(data=request.data)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        result = validator.validated_data
        email = UserEmail.get_primary_email(user)

        kwargs = {
            'list_id': result['listId'],
            'subscribed': result['subscribed'],
            'verified': email.is_verified,
        }
        if not result['subscribed']:
            kwargs['unsubscribed_date'] = timezone.now()
        else:
            kwargs['subscribed_date'] = timezone.now()

        newsletter.create_or_update_subscription(user, **kwargs)
        return self.respond(status=204)
コード例 #14
0
ファイル: user_emails.py プロジェクト: binlee1990/sentry
    def delete(self, request, user):
        """
        Removes an email from account
        `````````````````````````````

        Removes an email from account, can not remove primary email

        :param string email: email to remove
        :auth required:
        """
        validator = EmailValidator(data=request.DATA)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        email = validator.object['email']
        primary_email = UserEmail.get_primary_email(user)
        del_email = UserEmail.objects.filter(user=user, email__iexact=email).first()

        # Don't allow deleting primary email?
        if primary_email == del_email:
            return self.respond({'detail': 'Cannot remove primary email'},
                                status=400)

        del_email.delete()

        logger.info(
            'user.email.remove',
            extra={
                'user_id': user.id,
                'ip_address': request.META['REMOTE_ADDR'],
                'email': email,
            }
        )

        return self.respond(status=204)
コード例 #15
0
    def post(self, request, user):
        """
        Configure Newsletter Subscription
        `````````````````````````````````

        Update the default newsletter subscription.

        :param boolean subscribed: should be subscribed to newsletter
        :auth: required
        """
        validator = DefaultNewsletterValidator(data=request.data)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        result = validator.validated_data
        email = UserEmail.get_primary_email(user)

        kwargs = {
            'subscribed': result['subscribed'],
            'verified': email.is_verified,
            'list_ids': newsletter.get_default_list_ids(),
        }
        if not result['subscribed']:
            kwargs['unsubscribed_date'] = timezone.now()
        else:
            kwargs['subscribed_date'] = timezone.now()

        newsletter.create_or_update_subscriptions(user, **kwargs)

        user.update(
            flags=F('flags').bitand(~User.flags.newsletter_consent_prompt), )

        return self.respond(status=204)
コード例 #16
0
ファイル: dummy.py プロジェクト: rahulchhabria/sentry-fork-rc
    def __init__(
        self,
        user,
        list_id,
        list_name=None,
        list_description=None,
        email=None,
        verified=None,
        subscribed=False,
        subscribed_date=None,
        unsubscribed_date=None,
        **kwargs,
    ):
        from sentry.models import UserEmail

        self.email = user.email or email
        self.list_id = list_id
        self.list_description = list_description
        self.list_name = list_name
        # is the email address verified?
        self.verified = (UserEmail.get_primary_email(user).is_verified
                         if verified is None else verified)
        # are they subscribed to ``list_id``
        self.subscribed = subscribed
        if subscribed:
            self.subscribed_date = subscribed_date or timezone.now()
        elif subscribed is False:
            self.unsubscribed_date = unsubscribed_date or timezone.now()
コード例 #17
0
ファイル: test_releases.py プロジェクト: monkeyboy123/sentry
    def test_matching_author_with_assignment(self):
        group = self.create_group()
        add_group_to_inbox(group, GroupInboxReason.MANUAL)
        user = self.create_user(name="Foo Bar", email="*****@*****.**", is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(name="example", organization_id=self.group.organization.id)
        OrganizationMember.objects.create(organization=group.project.organization, user=user)
        UserOption.objects.set_value(user=user, key="self_assign_issue", value="1")

        commit = Commit.objects.create(
            key=sha1(uuid4().hex.encode("utf-8")).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message=u"Foo Biz\n\nFixes {}".format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id, name=user.name, email=user.email
            ),
        )

        self.assertResolvedFromCommit(group, commit)

        assert GroupAssignee.objects.filter(group=group, user=user).exists()

        assert Activity.objects.filter(
            project=group.project, group=group, type=Activity.ASSIGNED, user=user
        )[0].data == {
            "assignee": six.text_type(user.id),
            "assigneeEmail": user.email,
            "assigneeType": "user",
        }

        assert GroupSubscription.objects.filter(group=group, user=user).exists()
コード例 #18
0
ファイル: accounts.py プロジェクト: zsirfs/sentry
def manage_subscriptions(request):
    user = request.user
    email = UserEmail.get_primary_email(user)

    if request.method == 'GET':
        context = csrf(request)
        context.update({
            'page': 'subscriptions',
            'email': email,
            'AUTH_PROVIDERS': auth.get_auth_providers(),
            'has_newsletters': newsletter.is_enabled,
            'subscriptions': newsletter.get_subscriptions(user),
        })
        return render_to_response('sentry/account/subscriptions.html', context,
                                  request)

    subscribed = request.POST.get('subscribed') == '1'
    try:
        list_id = int(request.POST.get('listId', ''))
    except ValueError:
        return HttpResponse('bad request', status=400)

    kwargs = {
        'list_id': list_id,
        'subscribed': subscribed,
        'verified': email.is_verified,
    }
    if not subscribed:
        kwargs['unsubscribed_date'] = timezone.now()
    else:
        kwargs['subscribed_date'] = timezone.now()

    newsletter.create_or_update_subscription(user, **kwargs)
    return HttpResponse()
コード例 #19
0
    def delete(self, request, user):
        """
        Removes an email from account
        `````````````````````````````

        Removes an email from account, can not remove primary email

        :param string email: email to remove
        :auth required:
        """
        validator = EmailValidator(data=request.data)
        if not validator.is_valid():
            return self.respond(validator.errors, status=400)

        email = validator.validated_data["email"]
        primary_email = UserEmail.get_primary_email(user)
        del_email = UserEmail.objects.filter(user=user, email__iexact=email).first()

        # Don't allow deleting primary email?
        if primary_email == del_email:
            return self.respond({"detail": "Cannot remove primary email"}, status=400)

        del_email.delete()

        logger.info(
            "user.email.remove",
            extra={"user_id": user.id, "ip_address": request.META["REMOTE_ADDR"], "email": email},
        )

        return self.respond(status=204)
コード例 #20
0
ファイル: tests.py プロジェクト: zanjs/sentry
 def test_send_single_email(self, send_confirm_email):
     user = self.create_user('*****@*****.**')
     email = UserEmail.objects.create(user=user, email='*****@*****.**')
     email.save()
     self.login_as(user)
     self.client.post(reverse('sentry-account-confirm-email-send'),
                     data={'primary-email': '', 'email': '*****@*****.**'},
                     follow=True)
     send_confirm_email.assert_called_once_with(UserEmail.get_primary_email(user))
コード例 #21
0
ファイル: tests.py プロジェクト: faulkner/sentry
 def test_send_single_email(self, send_confirm_email):
     user = self.create_user('*****@*****.**')
     email = UserEmail.objects.create(user=user, email='*****@*****.**')
     email.save()
     self.login_as(user)
     self.client.post(reverse('sentry-account-confirm-email-send'),
                     data={'primary-email': '', 'email': '*****@*****.**'},
                     follow=True)
     send_confirm_email.assert_called_once_with(UserEmail.get_primary_email(user))
コード例 #22
0
ファイル: invite_helper.py プロジェクト: baoxin/sentry
    def _needs_email_verification(self) -> bool:
        organization = self.om.organization
        if not (features.has("organizations:required-email-verification",
                             organization)
                and organization.flags.require_email_verification):
            return False

        user = self.request.user
        primary_email_is_verified = (isinstance(
            user, User) and UserEmail.get_primary_email(user).is_verified)
        return not primary_email_is_verified
コード例 #23
0
    def test_get_user_from_email(self):
        user = User.objects.create(email='*****@*****.**')
        UserEmail.get_primary_email(user=user)
        project = self.create_project()
        self.create_member(user=user, organization=project.organization)
        release = Release.objects.create(
            organization_id=project.organization_id,
            version=uuid4().hex,
            new_groups=1,
        )
        release.add_project(project)
        commit_author = CommitAuthor.objects.create(
            name='stebe',
            email='*****@*****.**',
            organization_id=project.organization_id,
        )
        commit = Commit.objects.create(
            organization_id=project.organization_id,
            repository_id=1,
            key='abc',
            author=commit_author,
            message='waddap',
        )
        ReleaseCommit.objects.create(
            organization_id=project.organization_id,
            project_id=project.id,
            release=release,
            commit=commit,
            order=1,
        )
        release.update(
            authors=[six.text_type(commit_author.id)],
            commit_count=1,
            last_commit_id=commit.id,
        )

        result = serialize(release, user)
        result_author = result['authors'][0]
        assert int(result_author['id']) == user.id
        assert result_author['email'] == user.email
        assert result_author['username'] == user.username
コード例 #24
0
ファイル: test_releases.py プロジェクト: Kayle009/sentry
    def test_matching_author_with_assignment(self):
        group = self.create_group()
        user = self.create_user(
            name='Foo Bar', email='*****@*****.**', is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(
            organization=group.project.organization, user=user)
        UserOption.objects.set_value(
            user=user,
            key='self_assign_issue',
            value='1'
        )

        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message=u'Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            )
        )

        self.assertResolvedFromCommit(group, commit)

        assert GroupAssignee.objects.filter(group=group, user=user).exists()

        assert Activity.objects.filter(
            project=group.project,
            group=group,
            type=Activity.ASSIGNED,
            user=user,
        )[0].data == {
            'assignee': six.text_type(user.id),
            'assigneeEmail': user.email,
            'assigneeType': 'user',
        }

        assert GroupSubscription.objects.filter(
            group=group,
            user=user,
        ).exists()
コード例 #25
0
ファイル: dummy.py プロジェクト: Kayle009/sentry
    def __init__(self, user, list_id, list_name=None, list_description=None, email=None, verified=None, subscribed=False, subscribed_date=None, unsubscribed_date=None, **kwargs):
        from sentry.models import UserEmail

        self.email = user.email or email
        self.list_id = list_id
        self.list_description = list_description
        self.list_name = list_name
        # is the email address verified?
        self.verified = UserEmail.get_primary_email(user).is_verified if verified is None else verified
        # are they subscribed to ``list_id``
        self.subscribed = subscribed
        if subscribed:
            self.subscribed_date = subscribed_date or timezone.now()
        elif subscribed is False:
            self.unsubscribed_date = unsubscribed_date or timezone.now()
コード例 #26
0
    def test_matching_author_with_assignment(self):
        group = self.create_group()
        user = self.create_user(name='Foo Bar',
                                email='*****@*****.**',
                                is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(
            organization=group.project.organization, user=user)
        UserOption.objects.set_value(user=user,
                                     key='self_assign_issue',
                                     value='1')

        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message=u'Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            ))

        self.assertResolvedFromCommit(group, commit)

        assert GroupAssignee.objects.filter(group=group, user=user).exists()

        assert Activity.objects.filter(
            project=group.project,
            group=group,
            type=Activity.ASSIGNED,
            user=user,
        )[0].data == {
            'assignee': six.text_type(user.id),
            'assigneeEmail': user.email,
            'assigneeType': 'user',
        }

        assert GroupSubscription.objects.filter(
            group=group,
            user=user,
        ).exists()
コード例 #27
0
    def test_assigns_author(self):
        group = self.create_group()
        user = self.create_user(name='Foo Bar',
                                email='*****@*****.**',
                                is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(
            organization=group.project.organization, user=user)
        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message='Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            ))

        assert GroupCommitResolution.objects.filter(
            group_id=group.id,
            commit_id=commit.id,
        ).exists()

        assert GroupLink.objects.filter(
            group_id=group.id,
            linked_type=GroupLink.LinkedType.commit,
            linked_id=commit.id).exists()

        assert GroupAssignee.objects.filter(group=group, user=user).exists()

        self.assertEqual(
            Activity.objects.filter(
                project=group.project,
                group=group,
                type=Activity.ASSIGNED,
                user=user,
            )[0].data, {
                'assignee': six.text_type(user.id),
                'assigneeEmail': user.email
            })
コード例 #28
0
ファイル: test_releases.py プロジェクト: alexandrul/sentry
    def test_assigns_author(self):
        group = self.create_group()
        user = self.create_user(
            name='Foo Bar', email='*****@*****.**', is_active=True)
        email = UserEmail.get_primary_email(user=user)
        email.is_verified = True
        email.save()
        repo = Repository.objects.create(
            name='example',
            organization_id=self.group.organization.id,
        )
        OrganizationMember.objects.create(
            organization=group.project.organization, user=user)
        commit = Commit.objects.create(
            key=sha1(uuid4().hex).hexdigest(),
            organization_id=group.organization.id,
            repository_id=repo.id,
            message=u'Foo Biz\n\nFixes {}'.format(group.qualified_short_id),
            author=CommitAuthor.objects.create(
                organization_id=group.organization.id,
                name=user.name,
                email=user.email,
            )
        )

        assert GroupLink.objects.filter(
            group_id=group.id,
            linked_type=GroupLink.LinkedType.commit,
            linked_id=commit.id).exists()

        assert GroupAssignee.objects.filter(group=group, user=user).exists()

        assert Activity.objects.filter(
            project=group.project,
            group=group,
            type=Activity.ASSIGNED,
            user=user,
        )[0].data == {
            'assignee': six.text_type(user.id),
            'assigneeEmail': user.email,
            'assigneeType': 'user',
        }
コード例 #29
0
    def put(self, request, user):
        """
        Update Account Subscriptionsoptions
        `````````````````````````````````

        Update account subscriptions to newsletter

        :param int listId: id of newsletter list
        :param boolean subscribed: should be subscribed to newsletter
        :auth: required
        """

        email = UserEmail.get_primary_email(user)

        # Can't handle subscriptions without a verified email
        if not email.is_verified:
            return Response(
                {
                    'details':
                    'Must have verified email to subscribe to newsletter.'
                },
                status=status.HTTP_400_BAD_REQUEST)

        subscribed = request.DATA.get('subscribed')
        try:
            list_id = int(request.DATA.get('listId', ''))
        except ValueError:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        kwargs = {
            'list_id': list_id,
            'subscribed': subscribed,
            'verified': email.is_verified,
        }
        if not subscribed:
            kwargs['unsubscribed_date'] = timezone.now()
        else:
            kwargs['subscribed_date'] = timezone.now()

        newsletter.create_or_update_subscription(user, **kwargs)
        return Response(status=status.HTTP_204_NO_CONTENT)
コード例 #30
0
ファイル: auth.py プロジェクト: waterdrops/sentry
    def call_to_action(self, org: Organization, user: User,
                       member: OrganizationMember):
        import django.contrib.auth.models

        if isinstance(user, django.contrib.auth.models.User):
            # TODO(RyanSkonnord): Add test to repro this case (or delete check if unable)
            logger.warning(
                "Could not send verified email compliance notification (non-Sentry User model)"
            )
            return
        elif not isinstance(user, User):
            raise TypeError(user)

        email = UserEmail.get_primary_email(user)
        email_context = {
            "confirm_url":
            absolute_uri(
                reverse("sentry-account-confirm-email",
                        args=[user.id, email.validation_hash])),
            "invite_url":
            member.get_invite_link(),
            "email":
            email.email,
            "organization":
            org,
        }
        subject = "{} {} Mandatory: Verify Email Address".format(
            options.get("mail.subject-prefix"), org.name.capitalize())
        message = MessageBuilder(
            subject=subject,
            template="sentry/emails/setup_email.txt",
            html_template="sentry/emails/setup_email.html",
            type="user.setup_email",
            context=email_context,
        )
        message.send_async([email])
コード例 #31
0
ファイル: accounts.py プロジェクト: zsirfs/sentry
def show_emails(request):
    user = request.user
    emails = user.emails.all()
    email_form = EmailForm(user, request.POST or None)
    primary_email = UserEmail.get_primary_email(user)
    alt_emails = emails.exclude(email=primary_email.email)

    if 'remove' in request.POST:
        email = request.POST.get('email')
        del_email = UserEmail.objects.filter(user=user, email=email)
        del_email.delete()
        logger.info('user.email.remove',
                    extra={
                        'user_id': user.id,
                        'ip_address': request.META['REMOTE_ADDR'],
                        'email': email,
                    })

        return HttpResponseRedirect(request.path)

    if 'primary' in request.POST:
        new_primary = request.POST['new_primary_email'].lower().strip()

        if User.objects.filter(
                Q(email__iexact=new_primary)
                | Q(username__iexact=new_primary)).exclude(
                    id=user.id).exists():
            messages.add_message(
                request, messages.ERROR,
                _("That email is already in use for another user"))

        elif new_primary != user.email:

            # update notification settings for those set to primary email with new primary email
            alert_email = UserOption.objects.get_value(user=user,
                                                       key='alert_email')

            if alert_email == user.email:
                UserOption.objects.set_value(user=user,
                                             key='alert_email',
                                             value=new_primary)
            options = UserOption.objects.filter(user=user, key='mail:email')
            for option in options:
                if option.value != user.email:
                    continue
                option.value = new_primary
                option.save()

            has_new_username = user.email == user.username

            user.email = new_primary

            msg = _('Your settings were saved')
            messages.add_message(request, messages.SUCCESS, msg)

            if has_new_username and not User.objects.filter(
                    username__iexact=new_primary).exists():
                user.username = user.email
            user.save()
        return HttpResponseRedirect(request.path)

    if email_form.is_valid():

        alternative_email = email_form.cleaned_data['alt_email'].lower().strip(
        )

        # check if this alternative email already exists for user
        if alternative_email and not UserEmail.objects.filter(
                user=user, email__iexact=alternative_email).exists():
            # create alternative email for user
            try:
                with transaction.atomic():
                    new_email = UserEmail.objects.create(
                        user=user, email=alternative_email)
            except IntegrityError:
                pass
            else:
                new_email.set_hash()
                new_email.save()
                user.send_confirm_email_singular(new_email)
                # Update newsletter subscription and mark as unverified
                newsletter.update_subscription(
                    user=user,
                    verified=False,
                )

                logger.info('user.email.add',
                            extra={
                                'user_id': user.id,
                                'ip_address': request.META['REMOTE_ADDR'],
                                'email': new_email.email,
                            })
                msg = _('A confirmation email has been sent to %s.'
                        ) % new_email.email
                messages.add_message(request, messages.SUCCESS, msg)

        messages.add_message(request, messages.SUCCESS,
                             _('Your settings were saved.'))
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update({
        'email_form': email_form,
        'primary_email': primary_email,
        'alt_emails': alt_emails,
        'page': 'emails',
        'AUTH_PROVIDERS': auth.get_auth_providers(),
        'has_newsletters': newsletter.is_enabled,
    })
    return render_to_response('sentry/account/emails.html', context, request)
コード例 #32
0
 def validate_requireEmailVerification(self, value):
     user = self.context["user"]
     has_verified = UserEmail.get_primary_email(user).is_verified
     if value and not has_verified:
         raise serializers.ValidationError(ERR_EMAIL_VERIFICATION)
     return value
コード例 #33
0
ファイル: accounts.py プロジェクト: ollie314/sentry
def show_emails(request):
    user = request.user
    primary_email = UserEmail.get_primary_email(user)
    alt_emails = user.emails.all().exclude(email=primary_email.email)

    email_form = EmailForm(user, request.POST or None,
        initial={
            'primary_email': primary_email.email,
        },
    )

    if 'remove' in request.POST:
        email = request.POST.get('email')
        del_email = UserEmail.objects.filter(user=user, email=email)
        del_email.delete()
        return HttpResponseRedirect(request.path)

    if email_form.is_valid():
        old_email = user.email

        email_form.save()

        if user.email != old_email:
            useroptions = UserOption.objects.filter(user=user, value=old_email)
            for option in useroptions:
                option.value = user.email
                option.save()
            UserEmail.objects.filter(user=user, email=old_email).delete()
            try:
                with transaction.atomic():
                    user_email = UserEmail.objects.create(
                        user=user,
                        email=user.email,
                    )
            except IntegrityError:
                pass
            else:
                user_email.set_hash()
                user_email.save()
            user.send_confirm_emails()
        alternative_email = email_form.cleaned_data['alt_email']
        # check if this alternative email already exists for user
        if alternative_email and not UserEmail.objects.filter(user=user, email=alternative_email):
            # create alternative email for user
            try:
                with transaction.atomic():
                    new_email = UserEmail.objects.create(
                        user=user,
                        email=alternative_email
                    )
            except IntegrityError:
                pass
            else:
                new_email.set_hash()
                new_email.save()
            # send confirmation emails to any non verified emails
            user.send_confirm_emails()

        messages.add_message(
            request, messages.SUCCESS, 'Your settings were saved.')
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update({
        'email_form': email_form,
        'primary_email': primary_email,
        'alt_emails': alt_emails,
        'page': 'emails',
        'AUTH_PROVIDERS': auth.get_auth_providers(),
    })
    return render_to_response('sentry/account/emails.html', context, request)
コード例 #34
0
ファイル: accounts.py プロジェクト: yuvrajm/sentry
def show_emails(request):
    user = request.user
    primary_email = UserEmail.get_primary_email(user)
    alt_emails = user.emails.all().exclude(email=primary_email.email)

    email_form = EmailForm(
        user,
        request.POST or None,
        initial={
            'primary_email': primary_email.email,
        },
    )

    if 'remove' in request.POST:
        email = request.POST.get('email')
        del_email = UserEmail.objects.filter(user=user, email=email)
        del_email.delete()
        return HttpResponseRedirect(request.path)

    if email_form.is_valid():
        old_email = user.email

        email_form.save()

        if user.email != old_email:
            useroptions = UserOption.objects.filter(user=user, value=old_email)
            for option in useroptions:
                option.value = user.email
                option.save()
            UserEmail.objects.filter(user=user, email=old_email).delete()
            try:
                with transaction.atomic():
                    user_email = UserEmail.objects.create(
                        user=user,
                        email=user.email,
                    )
            except IntegrityError:
                pass
            else:
                user_email.set_hash()
                user_email.save()
            user.send_confirm_emails()
        alternative_email = email_form.cleaned_data['alt_email']
        # check if this alternative email already exists for user
        if alternative_email and not UserEmail.objects.filter(
                user=user, email=alternative_email):
            # create alternative email for user
            try:
                with transaction.atomic():
                    new_email = UserEmail.objects.create(
                        user=user, email=alternative_email)
            except IntegrityError:
                pass
            else:
                new_email.set_hash()
                new_email.save()
            # send confirmation emails to any non verified emails
            user.send_confirm_emails()

        messages.add_message(request, messages.SUCCESS,
                             'Your settings were saved.')
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update({
        'email_form': email_form,
        'primary_email': primary_email,
        'alt_emails': alt_emails,
        'page': 'emails',
        'AUTH_PROVIDERS': auth.get_auth_providers(),
    })
    return render_to_response('sentry/account/emails.html', context, request)
コード例 #35
0
ファイル: auth.py プロジェクト: waterdrops/sentry
 def is_compliant(self, member: OrganizationMember) -> bool:
     return UserEmail.get_primary_email(member.user).is_verified
コード例 #36
0
ファイル: accounts.py プロジェクト: hosmelq/sentry
def show_emails(request):
    user = request.user
    emails = user.emails.all()
    email_form = EmailForm(user, request.POST or None)
    primary_email = UserEmail.get_primary_email(user)
    alt_emails = emails.exclude(email=primary_email.email)

    if 'remove' in request.POST:
        email = request.POST.get('email')
        del_email = UserEmail.objects.filter(user=user, email=email)
        del_email.delete()
        logger.info(
            'user.email.remove',
            extra={
                'user_id': user.id,
                'ip_address': request.META['REMOTE_ADDR'],
                'email': email,
            }
        )
        user.clear_lost_passwords()
        return HttpResponseRedirect(request.path)

    if 'primary' in request.POST:
        new_primary = request.POST['new_primary_email'].lower().strip()

        if User.objects.filter(Q(email__iexact=new_primary) | Q(username__iexact=new_primary)
                               ).exclude(id=user.id).exists():
            messages.add_message(
                request, messages.ERROR, _("That email is already in use for another user")
            )

        elif new_primary != user.email:
            new_primary_email = UserEmail.objects.get(user=user, email__iexact=new_primary)
            if not new_primary_email.is_verified:
                messages.add_message(
                    request, messages.ERROR, _(
                        "Cannot make an unverified address your primary email")
                )
                return HttpResponseRedirect(request.path)
            # update notification settings for those set to primary email with new primary email
            alert_email = UserOption.objects.get_value(user=user, key='alert_email')

            if alert_email == user.email:
                UserOption.objects.set_value(user=user, key='alert_email', value=new_primary)
            options = UserOption.objects.filter(user=user, key='mail:email')
            for option in options:
                if option.value != user.email:
                    continue
                option.value = new_primary
                option.save()

            has_new_username = user.email == user.username

            user.email = new_primary

            msg = _('Your settings were saved')
            messages.add_message(request, messages.SUCCESS, msg)

            if has_new_username and not User.objects.filter(username__iexact=new_primary).exists():
                user.username = user.email
            user.save()
        user.clear_lost_passwords()
        return HttpResponseRedirect(request.path)

    if email_form.is_valid():

        alternative_email = email_form.cleaned_data['alt_email'].lower().strip()

        # check if this alternative email already exists for user
        if alternative_email and not UserEmail.objects.filter(
            user=user, email__iexact=alternative_email
        ).exists():
            # create alternative email for user
            try:
                with transaction.atomic():
                    new_email = UserEmail.objects.create(user=user, email=alternative_email)
            except IntegrityError:
                pass
            else:
                new_email.set_hash()
                new_email.save()
                user.send_confirm_email_singular(new_email)

                logger.info(
                    'user.email.add',
                    extra={
                        'user_id': user.id,
                        'ip_address': request.META['REMOTE_ADDR'],
                        'email': new_email.email,
                    }
                )
                msg = _('A confirmation email has been sent to %s.') % new_email.email
                messages.add_message(request, messages.SUCCESS, msg)

        user.clear_lost_passwords()

        messages.add_message(request, messages.SUCCESS, _('Your settings were saved.'))
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update(
        {
            'email_form': email_form,
            'primary_email': primary_email,
            'alt_emails': alt_emails,
            'page': 'emails',
            'AUTH_PROVIDERS': auth.get_auth_providers(),
            'has_newsletters': newsletter.is_enabled,
        }
    )
    return render_to_response('sentry/account/emails.html', context, request)
コード例 #37
0
ファイル: accounts.py プロジェクト: twolfson/sentry
def show_emails(request):
    user = request.user
    primary_email = UserEmail.get_primary_email(user)
    alt_emails = user.emails.all().exclude(email=primary_email.email)

    email_form = EmailForm(user, request.POST or None,
        initial={
            'primary_email': primary_email.email,
        },
    )

    if 'remove' in request.POST:
        email = request.POST.get('email')
        del_email = UserEmail.objects.filter(user=user, email=email)
        del_email.delete()
        logger.info('user.email.remove', extra={
            'user_id': user.id,
            'ip_address': request.META['REMOTE_ADDR'],
            'email': email,
        })

        return HttpResponseRedirect(request.path)

    if email_form.is_valid():
        old_email = user.email

        email_form.save()

        if user.email != old_email:
            useroptions = UserOption.objects.filter(user=user, value=old_email)
            for option in useroptions:
                option.value = user.email
                option.save()
            UserEmail.objects.filter(user=user, email=old_email).delete()
            try:
                with transaction.atomic():
                    user_email = UserEmail.objects.create(
                        user=user,
                        email=user.email,
                    )
            except IntegrityError:
                pass
            else:
                user_email.set_hash()
                user_email.save()
                user.send_confirm_email_singular(user_email)
                # Update newsletter subscription and mark as unverified
                newsletter.update_subscription(
                    user=user,
                    verified=False,
                )
                logger.info('user.email.add', extra={
                    'user_id': user.id,
                    'ip_address': request.META['REMOTE_ADDR'],
                    'email': user_email.email,
                })
                msg = _('A confirmation email has been sent to %s.') % user_email.email
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    msg)
        alternative_email = email_form.cleaned_data['alt_email']
        # check if this alternative email already exists for user
        if alternative_email and not UserEmail.objects.filter(user=user, email=alternative_email):
            # create alternative email for user
            try:
                with transaction.atomic():
                    new_email = UserEmail.objects.create(
                        user=user,
                        email=alternative_email
                    )
            except IntegrityError:
                pass
            else:
                new_email.set_hash()
                new_email.save()
            # send confirmation emails to any non verified emails
            user.send_confirm_email_singular(new_email)
            logger.info('user.email.add', extra={
                'user_id': user.id,
                'ip_address': request.META['REMOTE_ADDR'],
                'email': new_email.email,
            })
            msg = _('A confirmation email has been sent to %s.') % new_email.email
            messages.add_message(
                request,
                messages.SUCCESS,
                msg)

        messages.add_message(
            request, messages.SUCCESS, _('Your settings were saved.'))
        return HttpResponseRedirect(request.path)

    context = csrf(request)
    context.update({
        'email_form': email_form,
        'primary_email': primary_email,
        'alt_emails': alt_emails,
        'page': 'emails',
        'AUTH_PROVIDERS': auth.get_auth_providers(),
        'has_newsletters': newsletter.is_enabled,
    })
    return render_to_response('sentry/account/emails.html', context, request)