<commit_before>"""Django views for the Chirper app.

Note that every save call either passes or raises an Exception.
This is because we want to print the messages provided by Stormpath.

"""
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.conf import settings

from django_stormpath.models import APPLICATION
from django_stormpath.forms import StormpathUserCreationForm

from sample.forms import SampleUserCustomInfoForm

from stormpath.error import Error as StormpathError
from stormpath.nonce import Nonce
from stormpath.id_site import IdSiteCallbackResult


def my_handle_id_site_callback(self, url_response):
    try:
        from urlparse import urlparse
    except ImportError:
        from urllib.parse import urlparse

    import jwt
    try:
        jwt_response = urlparse(url_response).query.split('=')[1]
    except Exception:  # because we wan't to catch everything
        return None

    api_key_secret = self._client.auth.secret

    # validate signature
    try:
        decoded_data = jwt.decode(
            jwt_response, api_key_secret, audience=self._client.auth.id,
            algorithms=['HS256'])
    except (jwt.DecodeError, jwt.ExpiredSignature):
        return None

    if 'err' in decoded_data:
        raise StormpathError(decoded_data.get('err'))

    nonce = Nonce(decoded_data['irt'])

    # check if nonce is in cache already
    # if it is throw an Exception
    if self._store._cache_get(nonce.href):
        raise ValueError('JWT has already been used.')

    # store nonce in cache store
    self._store._cache_put(href=nonce.href, data={'value': nonce.value})

    # issuer = decoded_data['iss']
    account_href = decoded_data['sub']
    is_new_account = decoded_data['isNewSub']
    state = decoded_data.get('state')
    status = decoded_data.get('status')

    if account_href:
        account = self.accounts.get(account_href)
        if self.has_account(account):
            # We modify the internal parameter sp_http_status which indicates if an account
            # is new (ie. just created). This is so we can take advantage of the account.is_new_account
            # property
            account.sp_http_status  # NOTE: this forces account retrieval and building of the actual Account object
            account.__dict__['sp_http_status'] = 201 if is_new_account else 200
        else:
            account = None
    else:
        account = None
    return IdSiteCallbackResult(account=account, state=state, status=status)<commit_msg>Update views.py<commit_after>"""Django views for the Chirper app.

Note that every save call either passes or raises an Exception.
This is because we want to print the messages provided by Stormpath.

"""
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.conf import settings

from django_stormpath.models import APPLICATION
from django_stormpath.forms import StormpathUserCreationForm

from sample.forms import SampleUserCustomInfoForm

from stormpath.error import Error as StormpathError
from stormpath.nonce import Nonce
from stormpath.id_site import IdSiteCallbackResult


def my_handle_id_site_callback(self, url_response):
    try:
        from urlparse import urlparse
    except ImportError:
        from urllib.parse import urlparse

    import jwt
    try:
        jwt_response = urlparse(url_response).query.split('=')[1]
    except Exception:  # because we wan't to catch everything
        return None

    api_key_secret = self._client.auth.secret

    # validate signature
    try:
        decoded_data = jwt.decode(
            jwt_response, api_key_secret, audience=self._client.auth.id,
            algorithms=['HS256'])
    except (jwt.DecodeError, jwt.ExpiredSignature):
        return None
    except jwt.MissingRequiredClaimError as missing_claim_error:
        if missing_claim_error.claim != 'aud':
            return None

        decoded_data = jwt.decode(
            jwt_response, api_key_secret, algorithms=['HS256'])

        if 'err' in decoded_data:
            raise StormpathError(decoded_data.get('err'))
        else:
            raise missing_claim_error

    nonce = Nonce(decoded_data['irt'])

    # check if nonce is in cache already
    # if it is throw an Exception
    if self._store._cache_get(nonce.href):
        raise ValueError('JWT has already been used.')

    # store nonce in cache store
    self._store._cache_put(href=nonce.href, data={'value': nonce.value})

    # issuer = decoded_data['iss']
    account_href = decoded_data['sub']
    is_new_account = decoded_data['isNewSub']
    state = decoded_data.get('state')
    status = decoded_data.get('status')

    if account_href:
        account = self.accounts.get(account_href)
        if self.has_account(account):
            # We modify the internal parameter sp_http_status which indicates if an account
            # is new (ie. just created). This is so we can take advantage of the account.is_new_account
            # property
            account.sp_http_status  # NOTE: this forces account retrieval and building of the actual Account object
            account.__dict__['sp_http_status'] = 201 if is_new_account else 200
        else:
            account = None
    else:
        account = None
    return IdSiteCallbackResult(account=account, state=state, status=status)
{'fraction_non_alphanumeric': 0.07157857892894645, 'fraction_numerical': 0.004025201260063003, 'mean_word_length': 3.2969924812030076, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '179579', 'n_tokens_mistral': 1613, 'n_tokens_neox': 1556, 'n_words': 489}