<commit_before># -*- coding: UTF-8 -*-
from django import forms
from django import http
from django.conf import settings as dsettings
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.forms.formsets import BaseFormSet, formset_factory
from django.db import transaction
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.views.decorators.csrf import csrf_exempt

from assopy import forms as aforms
from assopy import janrain
from assopy import models
from assopy import settings

from conference import models as cmodels

import logging
from itertools import izip_longest

log = logging.getLogger('assopy.views')

class HttpResponseRedirectSeeOther(http.HttpResponseRedirect):
    status_code = 303

# see: http://www.djangosnippets.org/snippets/821/
def render_to(template):
    """
    Decorator for Django views that sends returned dict to render_to_response function
    with given template and RequestContext as context instance.

    If view doesn't return dict then decorator simply returns output.
    Additionally view can return two-tuple, which must contain dict as first
    element and string with template name as second. This string will
    override template name, given as parameter

    Parameters:

     - template: template name to use
    """
    def renderer(func):
        def wrapper(request, *args, **kw):
            output = func(request, *args, **kw)
            if isinstance(output, (list, tuple)):
                return render_to_response(output[1], output[0], RequestContext(request))
            elif isinstance(output, dict):
                return render_to_response(template, output, RequestContext(request))
            return output
        return wrapper
    return renderer

@login_required
@render_to('assopy/profile.html')
def profile(request):
    user = request.user.assopy_user
    if request.method == 'POST':
        form = aforms.Profile(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            if data['photo']:
                user.photo = data['photo']
                user.save()
            del data['photo']
            user.setBilling(**data)
            return HttpResponseRedirectSeeOther('.')
    else:
        initial = user.billing()
        form = aforms.Profile(initial=initial)
    return {
        'user': user,
        'form': form,
    }

@login_required
@render_to('assopy/billing.html')
def billing(request):
    user = request.user.assopy_user
    if request.method == 'POST':
        form = aforms.BillingData(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            user.setBilling(**data)
            return HttpResponseRedirectSeeOther('.')
    else:
        initial = user.billing()
        form = aforms.BillingData(initial=initial)
    return {
        'user': user,
        'form': form,
    }

@render_to('assopy/new_account.html')
def new_account(request):
    next = request.GET.get('next', reverse('assopy-profile'))
    if not next.startswith('/'):
        next = reverse('assopy-profile')
    if request.user.is_authenticated():
        return redirect(next)

    if request.method == 'GET':
        form = aforms.NewAccountForm()
    else:
        form = aforms.NewAccountForm(data=request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = models.User.objects.create_user(
                email=data['email'],
                first_name=data['first_name'],
                last_name=data['last_name'],
                password=data['<PASSWORD>'],
            )
            # ho creato l'utente che non è ancora verificato, ma intanto lo
            # loggo così può iniziare subito ad usare il sito
            u = auth.authenticate(email=data['email'], password=data['<PASSWORD>'])
            auth.login(request, u)
            return redirect(next)
    return {
        'form': form,
        'next': next,
    }

@transaction.commit_on_success
def otc_code(request, token):
    user, ctype = models.Token.objects.validate(token)
    if user is None:
        return http.HttpResponseBadRequest()
    user.verified = True
    user.save()
    user.backend = 'assopy.auth_backends.EmailBackend'
    auth.login(request, user)
    return redirect('/')

@csrf_exempt
@transaction.commit_on_success
def janrain_token(request):
    if request.method != 'POST':
        return http.HttpResponseNotAllowed(('POST',))
    redirect_to = request.session.get('jr_next', '/')
    try:
        token = request.POST['token']
    except KeyError:
        return http.HttpResponseBadRequest()
    profile = janrain.auth_info(settings.JANRAIN['secret'], token)
    log.info('janrain profile: %s', profile['identifier'])

    current = request.user
    duser = auth.authenticate(identifier=profile['identifier'])<commit_msg>corretta la gestione dell'otc che verifica l'utente<commit_after># -*- coding: UTF-8 -*-
from django import forms
from django import http
from django.conf import settings as dsettings
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.forms.formsets import BaseFormSet, formset_factory
from django.db import transaction
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.views.decorators.csrf import csrf_exempt

from assopy import forms as aforms
from assopy import janrain
from assopy import models
from assopy import settings

from conference import models as cmodels

import logging
from itertools import izip_longest

log = logging.getLogger('assopy.views')

class HttpResponseRedirectSeeOther(http.HttpResponseRedirect):
    status_code = 303

# see: http://www.djangosnippets.org/snippets/821/
def render_to(template):
    """
    Decorator for Django views that sends returned dict to render_to_response function
    with given template and RequestContext as context instance.

    If view doesn't return dict then decorator simply returns output.
    Additionally view can return two-tuple, which must contain dict as first
    element and string with template name as second. This string will
    override template name, given as parameter

    Parameters:

     - template: template name to use
    """
    def renderer(func):
        def wrapper(request, *args, **kw):
            output = func(request, *args, **kw)
            if isinstance(output, (list, tuple)):
                return render_to_response(output[1], output[0], RequestContext(request))
            elif isinstance(output, dict):
                return render_to_response(template, output, RequestContext(request))
            return output
        return wrapper
    return renderer

@login_required
@render_to('assopy/profile.html')
def profile(request):
    user = request.user.assopy_user
    if request.method == 'POST':
        form = aforms.Profile(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            if data['photo']:
                user.photo = data['photo']
                user.save()
            del data['photo']
            user.setBilling(**data)
            return HttpResponseRedirectSeeOther('.')
    else:
        initial = user.billing()
        form = aforms.Profile(initial=initial)
    return {
        'user': user,
        'form': form,
    }

@login_required
@render_to('assopy/billing.html')
def billing(request):
    user = request.user.assopy_user
    if request.method == 'POST':
        form = aforms.BillingData(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            user.setBilling(**data)
            return HttpResponseRedirectSeeOther('.')
    else:
        initial = user.billing()
        form = aforms.BillingData(initial=initial)
    return {
        'user': user,
        'form': form,
    }

@render_to('assopy/new_account.html')
def new_account(request):
    next = request.GET.get('next', reverse('assopy-profile'))
    if not next.startswith('/'):
        next = reverse('assopy-profile')
    if request.user.is_authenticated():
        return redirect(next)

    if request.method == 'GET':
        form = aforms.NewAccountForm()
    else:
        form = aforms.NewAccountForm(data=request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = models.User.objects.create_user(
                email=data['email'],
                first_name=data['first_name'],
                last_name=data['last_name'],
                password=data['<PASSWORD>'],
            )
            # ho creato l'utente che non è ancora verificato, ma intanto lo
            # loggo così può iniziare subito ad usare il sito
            u = auth.authenticate(email=data['email'], password=data['<PASSWORD>'])
            auth.login(request, u)
            return redirect(next)
    return {
        'form': form,
        'next': next,
    }

@transaction.commit_on_success
def otc_code(request, token):
    user, ctype = models.Token.objects.validate(token)
    if user is None:
        return http.HttpResponseBadRequest()

    auth.logout(request)

    user.assopy_user.verified = True
    user.assopy_user.save()
    user = auth.authenticate(uid=user.id)
    auth.login(request, user)
    return redirect('/')

@csrf_exempt
@transaction.commit_on_success
def janrain_token(request):
    if request.method != 'POST':
        return http.HttpResponseNotAllowed(('POST',))
    redirect_to = request.session.get('jr_next', '/')
    try:
        token = request.POST['token']
    except KeyError:
        return http.HttpResponseBadRequest()
    profile = janrain.auth_info(settings.JANRAIN['secret'], token)
    log.info('janrain profile: %s', profile['identifier'])

    current = request.user
    duser = auth.authenticate(identifier=profile['identifier'])
{'fraction_non_alphanumeric': 0.10133411810869139, 'fraction_numerical': 0.0017657445556209534, 'mean_word_length': 2.9091257668711656, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '4176710', 'n_tokens_mistral': 2890, 'n_tokens_neox': 2834, 'n_words': 746}