Пример #1
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ("blocked-uri", "violated-directive", "original-policy")

    if not waffle.sample_is_active("csp-store-reports"):
        return HttpResponse()

    try:
        v = json.loads(request.body)["csp-report"]
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta["PATH_INFO"] = v.get("document-uri", meta["PATH_INFO"])
        v = [(k, v[k]) for k in report if k in v]
        log_cef(
            "CSPViolation",
            5,
            meta,
            signature="CSPREPORT",
            msg="A client reported a CSP violation",
            cs6=v,
            cs6Label="ContentPolicy",
        )
    except (KeyError, ValueError), e:
        log.debug("Exception in CSP report: %s" % e, exc_info=True)
        return HttpResponseBadRequest()
Пример #2
0
def browserid_authenticate(request, assertion, is_mobile=False, browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    extra_params = {}
    url = settings.NATIVE_FXA_VERIFICATION_URL
    log.debug("Verifying Native FxA at %s, audience: %s, " "extra_params: %s" % (url, browserid_audience, extra_params))
    v = BrowserIDBackend().get_verifier()
    v.verification_service_url = url
    result = v.verify(assertion, browserid_audience, url=url, **extra_params)
    if not result:
        return None, _("Native FxA authentication failure.")

    if "unverified-email" in result._response:
        email = result._response["unverified-email"]
        verified = False
    elif result._response.get("issuer") == settings.NATIVE_FXA_ISSUER and "fxa-verifiedEmail" in result._response.get(
        "idpClaims", {}
    ):
        email = result._response["idpClaims"]["fxa-verifiedEmail"]
        verified = True
    else:
        email = result.email
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. Don't let that happen.
            log.debug("Verified user %s attempted to log in with an " "unverified assertion!" % profile)
            return None, _("Please use the verified email for this account.")
        else:
            profile.is_verified = verified
            profile.save()

        return profile, None

    source = mkt.LOGIN_SOURCE_MMO_BROWSERID
    display_name = email.partition("@")[0]
    profile = UserProfile.objects.create(email=email, source=source, display_name=display_name, is_verified=verified)
    log_cef(
        "New Account",
        5,
        request,
        username=display_name,
        signature="AUTHNOTICE",
        msg="User created a new account (from Persona)",
    )
    record_action("new-user", request)

    return profile, None
Пример #3
0
    def create_action(self, request, serializer):
        client_id = request.POST.get('client_id', settings.FXA_CLIENT_ID)
        secret = settings.FXA_SECRETS[client_id]
        session = OAuth2Session(
            client_id,
            scope=u'profile',
            state=serializer.data['state'])

        auth_response = serializer.data['auth_response']
        fxa_authorization = fxa_authorize(session, secret, auth_response)

        if 'user' in fxa_authorization:
            email = fxa_authorization['email']
            fxa_uid = fxa_authorization['user']
            profile, created = find_or_create_user(email, fxa_uid)
            if created:
                log_cef('New Account', 5, request, username=fxa_uid,
                        signature='AUTHNOTICE',
                        msg='User created a new account (from FxA)')
                record_action('new-user', request)
            auth.login(request, profile)
            profile.update(last_login_ip=request.META.get('REMOTE_ADDR', ''))

            auth.signals.user_logged_in.send(sender=profile.__class__,
                                             request=request,
                                             user=profile)
        else:
            raise AuthenticationFailed('No profile.')

        request.user = profile
        request.groups = profile.groups.all()
        # Remember whether the user has logged in to highlight the register or
        # sign in nav button. 31536000 == one year.
        request.set_cookie('has_logged_in', '1', max_age=5 * 31536000)

        # We want to return completely custom data, not the serializer's.
        data = {
            'error': None,
            'token': commonplace_token(request.user.email),
            'settings': {
                'display_name': request.user.display_name,
                'email': request.user.email,
                'enable_recommendations': request.user.enable_recommendations,
                'source': 'firefox-accounts',
            }
        }
        # Serializers give up if they aren't passed an instance, so we
        # do that here despite PermissionsSerializer not needing one
        # really.
        permissions = PermissionsSerializer(context={'request': request},
                                            instance=True)
        data.update(permissions.data)

        # Add ids of installed/purchased/developed apps.
        data['apps'] = user_relevant_apps(profile)

        return data
Пример #4
0
    def create_action(self, request, serializer):
        client_id = request.POST.get('client_id', settings.FXA_CLIENT_ID)
        secret = settings.FXA_SECRETS[client_id]
        session = OAuth2Session(
            client_id,
            scope=u'profile',
            state=serializer.data['state'])

        auth_response = serializer.data['auth_response']
        fxa_authorization = fxa_authorize(session, secret, auth_response)

        if 'user' in fxa_authorization:
            email = fxa_authorization['email']
            fxa_uid = fxa_authorization['user']
            profile, created = find_or_create_user(email, fxa_uid)
            if created:
                log_cef('New Account', 5, request, username=fxa_uid,
                        signature='AUTHNOTICE',
                        msg='User created a new account (from FxA)')
                record_action('new-user', request)
            auth.login(request, profile)
            profile.update(last_login_ip=request.META.get('REMOTE_ADDR', ''))

            auth.signals.user_logged_in.send(sender=profile.__class__,
                                             request=request,
                                             user=profile)
        else:
            raise AuthenticationFailed('No profile.')

        request.user = profile
        request.groups = profile.groups.all()
        # Remember whether the user has logged in to highlight the register or
        # sign in nav button. 31536000 == one year.
        request.set_cookie('has_logged_in', '1', max_age=5 * 31536000)

        # We want to return completely custom data, not the serializer's.
        data = {
            'error': None,
            'token': commonplace_token(request.user.email),
            'settings': {
                'display_name': request.user.display_name,
                'email': request.user.email,
                'enable_recommendations': request.user.enable_recommendations,
                'source': 'firefox-accounts',
            }
        }
        # Serializers give up if they aren't passed an instance, so we
        # do that here despite PermissionsSerializer not needing one
        # really.
        permissions = PermissionsSerializer(context={'request': request},
                                            instance=True)
        data.update(permissions.data)

        # Add ids of installed/purchased/developed apps.
        data['apps'] = user_relevant_apps(profile)

        return data
Пример #5
0
    def explode(self):
        error = self.cleaned_data.get('error')

        if error == 'zerodivisionerror':
            1 / 0
        elif error == 'iorequesterror':
            class IOError(Exception):
                pass
            raise IOError('request data read error')
        elif error == 'heka_cef':
            environ = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
                       'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
                       'HTTP_USER_AGENT': 'MySuperBrowser'}

            config = {'cef.version': '0',
                      'cef.vendor': 'Mozilla',
                      'cef.device_version': '3',
                      'cef.product': 'zamboni',
                      'cef': True}

            settings.HEKA.cef('xx\nx|xx\rx', 5, environ, config,
                              username='******', ext1='ok=ok', ext2='ok\\ok',
                              logger_info='settings.HEKA')
        elif error == 'heka_statsd':
            settings.HEKA.incr(name=LOGGER_NAME)
        elif error == 'heka_json':
            settings.HEKA.heka(type="heka_json",
                               fields={'foo': 'bar', 'secret': 42,
                                       'logger_type': 'settings.HEKA'})

        elif error == 'heka_sentry':
            # These are local variables only used
            # by Sentry's frame hacking magic.
            # They won't be referenced which may trigger flake8
            # errors.
            heka_conf = settings.HEKA_CONF  # NOQA
            active_heka_conf = settings.HEKA._config  # NOQA
            try:
                1 / 0
            except:
                settings.HEKA.raven('heka_sentry error triggered')
        elif error == 'amo_cef':
            from mkt.site.utils import log_cef
            env = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
                   'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
                   'HTTP_USER_AGENT': 'MySuperBrowser'}
            log_cef(settings.STATSD_PREFIX, 6, env)
Пример #6
0
def _get_user_profile(request, buyer_email):
    user_profile = UserProfile.objects.filter(email=buyer_email)

    if user_profile.exists():
        user_profile = user_profile.get()
    else:
        source = mkt.LOGIN_SOURCE_WEBPAY
        user_profile = UserProfile.objects.create(
            email=buyer_email,
            is_verified=True,
            source=source)

        log_cef('New Account', 5, request, username=buyer_email,
                signature='AUTHNOTICE',
                msg='A new account was created from Webpay (using FxA)')
        record_action('new-user', request)

    return user_profile
Пример #7
0
def _get_user_profile(request, buyer_email):
    user_profile = UserProfile.objects.filter(email=buyer_email)

    if user_profile.exists():
        user_profile = user_profile.get()
    else:
        source = mkt.LOGIN_SOURCE_WEBPAY
        user_profile = UserProfile.objects.create(
            email=buyer_email,
            is_verified=True,
            source=source)

        log_cef('New Account', 5, request, username=buyer_email,
                signature='AUTHNOTICE',
                msg='A new account was created from Webpay (using FxA)')
        record_action('new-user', request)

    return user_profile
Пример #8
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.body)['csp-report']
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta['PATH_INFO'] = v.get('document-uri', meta['PATH_INFO'])
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSPViolation', 5, meta,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs6=v, cs6Label='ContentPolicy')
    except (KeyError, ValueError), e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Пример #9
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.body)['csp-report']
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta['PATH_INFO'] = v.get('document-uri', meta['PATH_INFO'])
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSPViolation',
                5,
                meta,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs6=v,
                cs6Label='ContentPolicy')
    except (KeyError, ValueError), e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Пример #10
0
def browserid_authenticate(request,
                           assertion,
                           is_mobile=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    extra_params = {}
    url = settings.NATIVE_FXA_VERIFICATION_URL
    log.debug('Verifying Native FxA at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    v = BrowserIDBackend().get_verifier()
    v.verification_service_url = url
    result = v.verify(assertion, browserid_audience, url=url, **extra_params)
    if not result:
        return None, _('Native FxA authentication failure.')

    if 'unverified-email' in result._response:
        email = result._response['unverified-email']
        verified = False
    elif (result._response.get('issuer') == settings.NATIVE_FXA_ISSUER
          and 'fxa-verifiedEmail' in result._response.get('idpClaims', {})):
        email = result._response['idpClaims']['fxa-verifiedEmail']
        verified = True
    else:
        email = result.email
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. Don't let that happen.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
            return None, _('Please use the verified email for this account.')
        else:
            profile.is_verified = verified
            profile.save()

        return profile, None

    source = mkt.LOGIN_SOURCE_MMO_BROWSERID
    display_name = email.partition('@')[0]
    profile = UserProfile.objects.create(email=email,
                                         source=source,
                                         display_name=display_name,
                                         is_verified=verified)
    log_cef('New Account',
            5,
            request,
            username=display_name,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    record_action('new-user', request)

    return profile, None