Exemplo n.º 1
0
Arquivo: views.py Projeto: pmac/basket
def send_recovery_message(request):
    """
    Send a recovery message to an email address.

    required form parameter: email

    If email not provided or not syntactically correct, returns 400.
    If email not known, returns 404.
    Otherwise, queues a task to send the message and returns 200.
    """
    email = process_email(request.POST.get('email'))
    if not email:
        return invalid_email_response()

    if email_is_blocked(email):
        # don't let on there's a problem
        return HttpResponseJSON({'status': 'ok'})

    try:
        user_data = get_user_data(email=email)
    except NewsletterException as e:
        return newsletter_exception_response(e)

    if not user_data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'Email address not known',
            'code': errors.BASKET_UNKNOWN_EMAIL,
        }, 404)  # Note: Bedrock looks for this 404

    send_recovery_message_task.delay(email)
    return HttpResponseJSON({'status': 'ok'})
Exemplo n.º 2
0
def send_recovery_message(request):
    """
    Send a recovery message to an email address.

    required form parameter: email

    If email not provided or not syntactically correct, returns 400.
    If email not known, returns 404.
    Otherwise, queues a task to send the message and returns 200.
    """
    email = process_email(request.POST.get("email"))
    if not email:
        return invalid_email_response()

    if email_is_blocked(email):
        # don't let on there's a problem
        return HttpResponseJSON({"status": "ok"})

    try:
        user_data = get_user_data(email=email)
    except NewsletterException as e:
        return newsletter_exception_response(e)

    if not user_data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "Email address not known",
                "code": errors.BASKET_UNKNOWN_EMAIL,
            },
            404,
        )  # Note: Bedrock looks for this 404

    send_recovery_message_task.delay(email)
    return HttpResponseJSON({"status": "ok"})
Exemplo n.º 3
0
    def to_python(self, value):
        value = super(EmailField, self).to_python(value)
        email = process_email(value)
        if not email:
            raise ValidationError('Enter a valid email address.', 'invalid')

        return email
Exemplo n.º 4
0
    def to_python(self, value):
        value = super(EmailField, self).to_python(value)
        email = process_email(value)
        if not email:
            raise ValidationError('Enter a valid email address.', 'invalid')

        return email
Exemplo n.º 5
0
def fxa_register(request):
    if settings.FXA_EVENTS_QUEUE_ENABLE:
        # When this setting is true these requests will be handled by
        # a queue via which we receive various events from FxA. See process_fxa_queue.py.
        # This is still here to avoid errors during the transition to said queue.
        # TODO remove after complete transistion to queue
        return HttpResponseJSON({'status': 'ok'})

    if not has_valid_api_key(request):
        return HttpResponseJSON(
            {
                'status': 'error',
                'desc': 'fxa-register requires a valid API-key',
                'code': errors.BASKET_AUTH_ERROR,
            }, 401)

    data = request.POST.dict()
    if 'email' not in data:
        return HttpResponseJSON(
            {
                'status': 'error',
                'desc': 'fxa-register requires an email address',
                'code': errors.BASKET_USAGE_ERROR,
            }, 401)

    email = process_email(data['email'])
    if not email:
        return invalid_email_response()

    if 'fxa_id' not in data:
        return HttpResponseJSON(
            {
                'status': 'error',
                'desc': 'fxa-register requires a Firefox Account ID',
                'code': errors.BASKET_USAGE_ERROR,
            }, 401)
    if 'accept_lang' not in data:
        return HttpResponseJSON(
            {
                'status': 'error',
                'desc': 'fxa-register requires accept_lang',
                'code': errors.BASKET_USAGE_ERROR,
            }, 401)

    lang = get_best_language(get_accept_languages(data['accept_lang']))
    if lang is None:
        return HttpResponseJSON(
            {
                'status': 'error',
                'desc': 'invalid language',
                'code': errors.BASKET_INVALID_LANGUAGE,
            }, 400)

    update_fxa_info.delay(email, lang, data['fxa_id'])
    return HttpResponseJSON({'status': 'ok'})
Exemplo n.º 6
0
Arquivo: views.py Projeto: pmac/basket
def user(request, token):
    if request.method == 'POST':
        data = request.POST.dict()
        data['token'] = token
        if 'email' in data:
            email = process_email(data['email'])
            if not email:
                return invalid_email_response()

            data['email'] = email
        return update_user_task(request, SET, data)

    return get_user(token)
Exemplo n.º 7
0
def user(request, token):
    if request.method == 'POST':
        data = request.POST.dict()
        data['token'] = token
        if 'email' in data:
            email = process_email(data['email'])
            if not email:
                return invalid_email_response()

            data['email'] = email
        return update_user_task(request, SET, data)

    return get_user(token)
Exemplo n.º 8
0
Arquivo: views.py Projeto: pmac/basket
def fxa_register(request):
    if settings.FXA_EVENTS_QUEUE_ENABLE:
        # When this setting is true these requests will be handled by
        # a queue via which we receive various events from FxA. See process_fxa_queue.py.
        # This is still here to avoid errors during the transition to said queue.
        # TODO remove after complete transistion to queue
        return HttpResponseJSON({'status': 'ok'})

    if not has_valid_api_key(request):
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'fxa-register requires a valid API-key',
            'code': errors.BASKET_AUTH_ERROR,
        }, 401)

    data = request.POST.dict()
    if 'email' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'fxa-register requires an email address',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    email = process_email(data['email'])
    if not email:
        return invalid_email_response()

    if 'fxa_id' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'fxa-register requires a Firefox Account ID',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if 'accept_lang' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'fxa-register requires accept_lang',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    lang = get_best_language(get_accept_languages(data['accept_lang']))
    if lang is None:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'invalid language',
            'code': errors.BASKET_INVALID_LANGUAGE,
        }, 400)

    update_fxa_info.delay(email, lang, data['fxa_id'])
    return HttpResponseJSON({'status': 'ok'})
Exemplo n.º 9
0
def user(request, token):
    token = str(token)
    if request.method == "POST":
        data = request.POST.dict()
        data["token"] = token
        if "email" in data:
            email = process_email(data["email"])
            if not email:
                return invalid_email_response()

            data["email"] = email
        return update_user_task(request, SET, data)

    get_fxa = "fxa" in request.GET
    return get_user(token, get_fxa=get_fxa)
Exemplo n.º 10
0
 def test_invalid_email(self, ve_mock):
     """Should return None for an invalid email."""
     ve_mock.side_effect = EmailSyntaxError
     self.assertIsNone(utils.process_email(self.email))
Exemplo n.º 11
0
 def test_valid_email(self):
     """Should return without raising an exception for a valid email."""
     self.assertEqual(utils.process_email(self.email), self.email)
Exemplo n.º 12
0
 def test_valid_email(self):
     """Should not return None for valid email."""
     self.assertEqual(process_email('*****@*****.**'), '*****@*****.**')
     self.assertEqual(process_email('*****@*****.**'),
                      '*****@*****.**')
     self.assertEqual(process_email('*****@*****.**'), '*****@*****.**')
Exemplo n.º 13
0
Arquivo: views.py Projeto: pmac/basket
def lookup_user(request):
    """Lookup a user in Exact Target given email or token (not both).

    To look up by email, a valid API key are required.

    If email and token are both provided, an error is returned rather
    than trying to define all the possible behaviors.

    SSL is always required when using this call. If no SSL, it'll fail
    with 401 and an appropriate message in the response body.

    Response content is always JSON.

    If user is not found, returns a 404 status and json is::

        {
            'status': 'error',
            'desc': 'No such user'
        }

    (If you need to distinguish user not found from an error calling
    the API, check the response content.)

    If a required, valid API key is not provided, status is 401 Unauthorized.
    The API key can be provided either as a GET query parameter ``api-key``
    or a request header ``X-api-key``. If it's provided as a query parameter,
    any request header is ignored.

    For other errors, similarly
    response status is 4xx and the json 'desc' says what's wrong.

    Otherwise, status is 200 and json is the return value from
    `get_user_data`. See that method for details.

    Note that because this method always calls Exact Target one or
    more times, it can be slower than some other Basket APIs, and will
    fail if ET is down.
    """
    if settings.MAINTENANCE_MODE and not settings.MAINTENANCE_READ_ONLY:
        # can't return user data during maintenance
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'user data is not available in maintenance mode',
            'code': errors.BASKET_NETWORK_FAILURE,
        }, 400)

    token = request.GET.get('token', None)
    email = request.GET.get('email', None)

    if (not email and not token) or (email and token):
        return HttpResponseJSON({
            'status': 'error',
            'desc': MSG_EMAIL_OR_TOKEN_REQUIRED,
            'code': errors.BASKET_USAGE_ERROR,
        }, 400)

    if email and not has_valid_api_key(request):
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'Using lookup_user with `email`, you need to pass a '
                    'valid `api-key` GET parameter or X-api-key header',
            'code': errors.BASKET_AUTH_ERROR,
        }, 401)

    if email:
        email = process_email(email)
        if not email:
            return invalid_email_response()

    try:
        user_data = get_user_data(token=token, email=email)
    except NewsletterException as e:
        return newsletter_exception_response(e)

    status_code = 200
    if not user_data:
        code = errors.BASKET_UNKNOWN_TOKEN if token else errors.BASKET_UNKNOWN_EMAIL
        user_data = {
            'status': 'error',
            'desc': MSG_USER_NOT_FOUND,
            'code': code,
        }
        status_code = 404

    return HttpResponseJSON(user_data, status_code)
Exemplo n.º 14
0
 def test_invalid_email(self):
     """Should return None for invalid email."""
     self.assertIsNone(process_email('dude@[email protected]'))
     self.assertIsNone(process_email(''))
     self.assertIsNone(process_email(None))
Exemplo n.º 15
0
 def test_valid_email(self):
     """Should return without raising an exception for a valid email."""
     self.assertEqual(utils.process_email(self.email), self.email)
Exemplo n.º 16
0
def subscribe(request):
    data = request.POST.dict()
    newsletters = data.get("newsletters", None)
    if not newsletters:
        # request.body causes tests to raise exceptions
        # while request.read() works.
        raw_request = request.read().decode()
        if "newsletters=" in raw_request:
            # malformed request from FxOS
            # Can't use QueryDict since the string is not url-encoded.
            # It will convert '+' to ' ' for example.
            data = dict(
                pair.split("=") for pair in raw_request.split("&")
                if "=" in pair)
            statsd.incr("news.views.subscribe.fxos-workaround")
        else:
            return HttpResponseJSON(
                {
                    "status": "error",
                    "desc": "newsletters is missing",
                    "code": errors.BASKET_USAGE_ERROR,
                },
                400,
            )

    if "email" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "email is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )

    email = process_email(data["email"])
    if not email:
        return invalid_email_response()

    data["email"] = email

    if email_is_blocked(data["email"]):
        statsd.incr("news.views.subscribe.email_blocked")
        # don't let on there's a problem
        return HttpResponseJSON({"status": "ok"})

    optin = data.pop("optin", "N").upper() == "Y"
    sync = data.pop("sync", "N").upper() == "Y"

    authorized = False
    if optin or sync:
        if is_authorized(request, email):
            authorized = True

    if optin and not authorized:
        # for backward compat we just ignore the optin if
        # no valid API key is sent.
        optin = False

    if sync:
        if not authorized:
            return HttpResponseJSON(
                {
                    "status": "error",
                    "desc": "Using subscribe with sync=Y, you need to pass a "
                    "valid `api-key` or FxA OAuth Authorization.",
                    "code": errors.BASKET_AUTH_ERROR,
                },
                401,
            )

    # NOTE this is not a typo; Referrer is misspelled in the HTTP spec
    # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.36
    if not data.get("source_url") and request.META.get("HTTP_REFERER"):
        # try to get it from referrer
        statsd.incr("news.views.subscribe.use_referrer")
        data["source_url"] = request.META["HTTP_REFERER"]

    return update_user_task(request,
                            SUBSCRIBE,
                            data=data,
                            optin=optin,
                            sync=sync)
Exemplo n.º 17
0
Arquivo: views.py Projeto: pmac/basket
def get_involved(request):
    data = request.POST.dict()
    if 'email' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'email is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if email_is_blocked(data['email']):
        # don't let on there's a problem
        return HttpResponseJSON({'status': 'ok'})
    if 'interest_id' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'interest_id is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    try:
        Interest.objects.get(interest_id=data['interest_id'])
    except Interest.DoesNotExist:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'invalid interest_id',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    if 'lang' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'lang is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if not language_code_is_valid(data['lang']):
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'invalid language',
            'code': errors.BASKET_INVALID_LANGUAGE,
        }, 400)
    if 'name' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'name is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if 'country' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'country is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    email = process_email(data.get('email'))
    if not email:
        return invalid_email_response()

    update_get_involved.delay(
        data['interest_id'],
        data['lang'],
        data['name'],
        email,
        data['country'],
        data.get('format', 'H'),
        data.get('subscribe', False),
        data.get('message', None),
        data.get('source_url', None),
    )
    return HttpResponseJSON({'status': 'ok'})
Exemplo n.º 18
0
 def test_non_ascii_email_domain(self):
     """Should return IDNA version of domain"""
     self.assertEqual(process_email('dude@黒川.日本'),
                      '[email protected]')
     self.assertEqual(process_email('dude@黒川.日本'),
                      '[email protected]')
Exemplo n.º 19
0
 def test_non_ascii_email_username(self):
     """Should return none as SFDC does not support non-ascii characters in emails"""
     self.assertIsNone(process_email(u'düde@黒川.日本'))
     self.assertIsNone(process_email(u'dü[email protected]'))
Exemplo n.º 20
0
def subscribe(request):
    data = request.POST.dict()
    newsletters = data.get('newsletters', None)
    if not newsletters:
        # request.body causes tests to raise exceptions
        # while request.read() works.
        raw_request = request.read()
        if 'newsletters=' in raw_request:
            # malformed request from FxOS
            # Can't use QueryDict since the string is not url-encoded.
            # It will convert '+' to ' ' for example.
            data = dict(pair.split('=') for pair in raw_request.split('&') if '=' in pair)
            statsd.incr('news.views.subscribe.fxos-workaround')
        else:
            return HttpResponseJSON({
                'status': 'error',
                'desc': 'newsletters is missing',
                'code': errors.BASKET_USAGE_ERROR,
            }, 400)

    if 'email' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'email is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    email = process_email(data['email'])
    if not email:
        return invalid_email_response()

    data['email'] = email

    if email_is_blocked(data['email']):
        statsd.incr('news.views.subscribe.email_blocked')
        # don't let on there's a problem
        return HttpResponseJSON({'status': 'ok'})

    optin = data.pop('optin', 'N').upper() == 'Y'
    sync = data.pop('sync', 'N').upper() == 'Y'

    authorized = False
    if optin or sync:
        if is_authorized(request, email):
            authorized = True

    if optin and not authorized:
        # for backward compat we just ignore the optin if
        # no valid API key is sent.
        optin = False

    if sync:
        if not authorized:
            return HttpResponseJSON({
                'status': 'error',
                'desc': 'Using subscribe with sync=Y, you need to pass a '
                        'valid `api-key` or FxA OAuth Authorization.',
                'code': errors.BASKET_AUTH_ERROR,
            }, 401)

    # NOTE this is not a typo; Referrer is misspelled in the HTTP spec
    # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.36
    if not data.get('source_url') and request.META.get('HTTP_REFERER'):
        # try to get it from referrer
        statsd.incr('news.views.subscribe.use_referrer')
        data['source_url'] = request.META['HTTP_REFERER']

    return update_user_task(request, SUBSCRIBE, data=data, optin=optin, sync=sync)
Exemplo n.º 21
0
def get_involved(request):
    data = request.POST.dict()
    if 'email' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'email is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if email_is_blocked(data['email']):
        # don't let on there's a problem
        return HttpResponseJSON({'status': 'ok'})
    if 'interest_id' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'interest_id is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    try:
        Interest.objects.get(interest_id=data['interest_id'])
    except Interest.DoesNotExist:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'invalid interest_id',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    if 'lang' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'lang is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if not language_code_is_valid(data['lang']):
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'invalid language',
            'code': errors.BASKET_INVALID_LANGUAGE,
        }, 400)
    if 'name' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'name is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)
    if 'country' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'country is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    email = process_email(data.get('email'))
    if not email:
        return invalid_email_response()

    update_get_involved.delay(
        data['interest_id'],
        data['lang'],
        data['name'],
        email,
        data['country'],
        data.get('format', 'H'),
        data.get('subscribe', False),
        data.get('message', None),
        data.get('source_url', None),
    )
    return HttpResponseJSON({'status': 'ok'})
Exemplo n.º 22
0
 def test_valid_email(self):
     """Should not return None for valid email."""
     self.assertEqual(process_email('*****@*****.**'), '*****@*****.**')
     self.assertEqual(process_email('*****@*****.**'), '*****@*****.**')
     self.assertEqual(process_email('*****@*****.**'), '*****@*****.**')
Exemplo n.º 23
0
 def test_invalid_email(self, ve_mock):
     """Should return None for an invalid email."""
     ve_mock.side_effect = EmailSyntaxError
     self.assertIsNone(utils.process_email(self.email))
Exemplo n.º 24
0
 def test_non_ascii_email_username(self):
     """Should return none as SFDC does not support non-ascii characters in emails"""
     self.assertIsNone(process_email('düde@黒川.日本'))
     self.assertIsNone(process_email('dü[email protected]'))
Exemplo n.º 25
0
def get_involved(request):
    data = request.POST.dict()
    if "email" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "email is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )
    if email_is_blocked(data["email"]):
        # don't let on there's a problem
        return HttpResponseJSON({"status": "ok"})
    if "interest_id" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "interest_id is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )

    try:
        Interest.objects.get(interest_id=data["interest_id"])
    except Interest.DoesNotExist:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "invalid interest_id",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )

    if "lang" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "lang is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )
    if not language_code_is_valid(data["lang"]):
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "invalid language",
                "code": errors.BASKET_INVALID_LANGUAGE,
            },
            400,
        )
    if "name" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "name is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )
    if "country" not in data:
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "country is required",
                "code": errors.BASKET_USAGE_ERROR,
            },
            401,
        )

    email = process_email(data.get("email"))
    if not email:
        return invalid_email_response()

    update_get_involved.delay(
        data["interest_id"],
        data["lang"],
        data["name"],
        email,
        data["country"],
        data.get("format", "H"),
        data.get("subscribe", False),
        data.get("message", None),
        data.get("source_url", None),
    )
    return HttpResponseJSON({"status": "ok"})
Exemplo n.º 26
0
Arquivo: views.py Projeto: pmac/basket
def subscribe(request):
    data = request.POST.dict()
    newsletters = data.get('newsletters', None)
    if not newsletters:
        # request.body causes tests to raise exceptions
        # while request.read() works.
        raw_request = request.read()
        if 'newsletters=' in raw_request:
            # malformed request from FxOS
            # Can't use QueryDict since the string is not url-encoded.
            # It will convert '+' to ' ' for example.
            data = dict(pair.split('=') for pair in raw_request.split('&') if '=' in pair)
            statsd.incr('news.views.subscribe.fxos-workaround')
        else:
            return HttpResponseJSON({
                'status': 'error',
                'desc': 'newsletters is missing',
                'code': errors.BASKET_USAGE_ERROR,
            }, 400)

    if 'email' not in data:
        return HttpResponseJSON({
            'status': 'error',
            'desc': 'email is required',
            'code': errors.BASKET_USAGE_ERROR,
        }, 401)

    email = process_email(data['email'])
    if not email:
        return invalid_email_response()

    data['email'] = email

    if email_is_blocked(data['email']):
        statsd.incr('news.views.subscribe.email_blocked')
        # don't let on there's a problem
        return HttpResponseJSON({'status': 'ok'})

    optin = data.pop('optin', 'N').upper() == 'Y'
    sync = data.pop('sync', 'N').upper() == 'Y'

    if optin and not has_valid_api_key(request):
        # for backward compat we just ignore the optin if
        # no valid API key is sent.
        optin = False

    if sync:
        if not has_valid_api_key(request):
            return HttpResponseJSON({
                'status': 'error',
                'desc': 'Using subscribe with sync=Y, you need to pass a '
                        'valid `api-key` GET or POST parameter or X-api-key header',
                'code': errors.BASKET_AUTH_ERROR,
            }, 401)

    # NOTE this is not a typo; Referrer is misspelled in the HTTP spec
    # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.36
    if not data.get('source_url') and request.META.get('HTTP_REFERER'):
        # try to get it from referrer
        statsd.incr('news.views.subscribe.use_referrer')
        data['source_url'] = request.META['HTTP_REFERER']

    return update_user_task(request, SUBSCRIBE, data=data, optin=optin, sync=sync)
Exemplo n.º 27
0
 def test_non_ascii_email_domain(self):
     """Should return IDNA version of domain"""
     self.assertEqual(process_email(u'dude@黒川.日本'), u'[email protected]')
     self.assertEqual(process_email('dude@黒川.日本'), u'[email protected]')
Exemplo n.º 28
0
 def test_invalid_email(self):
     """Should return None for invalid email."""
     self.assertIsNone(process_email('dude@[email protected]'))
     self.assertIsNone(process_email(''))
     self.assertIsNone(process_email(None))
Exemplo n.º 29
0
def lookup_user(request):
    """Lookup a user in Exact Target given email or token (not both).

    To look up by email, a valid API key are required.

    If email and token are both provided, an error is returned rather
    than trying to define all the possible behaviors.

    SSL is always required when using this call. If no SSL, it'll fail
    with 401 and an appropriate message in the response body.

    Response content is always JSON.

    If user is not found, returns a 404 status and json is::

        {
            'status': 'error',
            'desc': 'No such user'
        }

    (If you need to distinguish user not found from an error calling
    the API, check the response content.)

    If a required, valid API key is not provided, status is 401 Unauthorized.
    The API key can be provided either as a GET query parameter ``api-key``
    or a request header ``X-api-key``. If it's provided as a query parameter,
    any request header is ignored.

    For other errors, similarly
    response status is 4xx and the json 'desc' says what's wrong.

    Otherwise, status is 200 and json is the return value from
    `get_user_data`. See that method for details.

    Note that because this method always calls Exact Target one or
    more times, it can be slower than some other Basket APIs, and will
    fail if ET is down.
    """
    if settings.MAINTENANCE_MODE and not settings.MAINTENANCE_READ_ONLY:
        # can't return user data during maintenance
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "user data is not available in maintenance mode",
                "code": errors.BASKET_NETWORK_FAILURE,
            },
            400,
        )

    token = request.GET.get("token", None)
    email = request.GET.get("email", None)
    get_fxa = "fxa" in request.GET

    if (not email and not token) or (email and token):
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": MSG_EMAIL_OR_TOKEN_REQUIRED,
                "code": errors.BASKET_USAGE_ERROR,
            },
            400,
        )

    if email and not is_authorized(request, email):
        return HttpResponseJSON(
            {
                "status": "error",
                "desc": "Using lookup_user with `email`, you need to pass a "
                "valid `api-key` or FxA OAuth Autorization header.",
                "code": errors.BASKET_AUTH_ERROR,
            },
            401,
        )

    if email:
        email = process_email(email)
        if not email:
            return invalid_email_response()

    try:
        user_data = get_user_data(token=token, email=email, get_fxa=get_fxa)
    except NewsletterException as e:
        return newsletter_exception_response(e)

    status_code = 200
    if not user_data:
        code = errors.BASKET_UNKNOWN_TOKEN if token else errors.BASKET_UNKNOWN_EMAIL
        user_data = {
            "status": "error",
            "desc": MSG_USER_NOT_FOUND,
            "code": code,
        }
        status_code = 404

    return HttpResponseJSON(user_data, status_code)
Exemplo n.º 30
0
 def test_valid_email(self):
     """Should not return None for valid email."""
     self.assertEqual(process_email("*****@*****.**"), "*****@*****.**")
     self.assertEqual(process_email("*****@*****.**"), "*****@*****.**")
     self.assertEqual(process_email("*****@*****.**"), "*****@*****.**")