<commit_before>from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib import messages
from django.contrib.sites.models import Site
from django.core import management
from django.core.signing import Signer
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.views.decorators.cache import never_cache

import ditto.config
from users.models import User

from . import forms
from . import models
from . import tenant as utils


def my_network(request):
    if request.user.is_anonymous():
        return render(request, 'landing.html')
    else:
        try:
            tenant = models.Tenant.objects.get(user=request.user)
        except models.Tenant.DoesNotExist:
            return _create_my_network(request)
        else:
            return _go_to_my_network(request, tenant)

    
def _create_my_network(request):
    if request.method == 'POST':
        form = forms.TenantForm(request.user, data=request.POST)
        if form.is_valid():
            tenant = form.save()
            _create_network_instance(tenant)
            messages.success(request, 'Network successfully created!')
            return HttpResponseRedirect(reverse('ditto:home'))
    else:
        form = forms.TenantForm(request.user)
    return render(request, 'tenant/create.html', {
        'form': form,
        'networks': models.Tenant.objects.all(),
    })


def _go_to_my_network(request, tenant):
    return render(request, 'tenant/go.html', {
        'tenant': tenant,
        'networks': models.Tenant.objects.all(),
    })


def _create_network_instance(tenant):
    admin = tenant.user
    admin_emails = list(admin.emailaddress_set.all())
    subdomain = tenant.slug
    network_name = tenant.network_name
    parent_domain = Site.objects.get_current().domain
    with utils._tenant(tenant.slug):
        # TODO in the real world we'll send a task off to some queue that'll go do bunch of stuff

        management.call_command('migrate', verbosity=0)

        management.call_command('runscript', 'setup_test_data')

        # remove dummy users created by test data script
        get_user_model().objects.all().delete()
        
        # copy the current user to the network database and make an admin
        admin.pk = None
        admin.is_new = True
        admin.save()
        for email in admin_emails:
            admin.emailaddress_set.create(
                email=email.email,
                verified=1
            )
        admin.groups.add(Group.objects.get(name=ditto.config.ADMIN_ROLE))

        # copy over network name
        site = Site.objects.get_current()
        site.domain = '%s.%s' % (subdomain, parent_domain)
        site.name = network_name
        site.save()


# TODO restrict this to requests from chat (localhost for now)?
@never_cache
def get_password(request):
    if settings.DEBUG:
        return HttpResponse()
    username = request.GET['user']
    user = get_object_or_404(User, username=username)
    signer = Signer()
    value = signer.sign(user.username)
    return HttpResponse(value)<commit_msg>Fix chat auth to check correct tenant<commit_after>from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib import messages
from django.contrib.sites.models import Site
from django.core import management
from django.core.signing import Signer
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.views.decorators.cache import never_cache

import ditto.config
from users.models import User

from . import forms
from . import models
from . import tenant as utils


def my_network(request):
    if request.user.is_anonymous():
        return render(request, 'landing.html')
    else:
        try:
            tenant = models.Tenant.objects.get(user=request.user)
        except models.Tenant.DoesNotExist:
            return _create_my_network(request)
        else:
            return _go_to_my_network(request, tenant)

    
def _create_my_network(request):
    if request.method == 'POST':
        form = forms.TenantForm(request.user, data=request.POST)
        if form.is_valid():
            tenant = form.save()
            _create_network_instance(tenant)
            messages.success(request, 'Network successfully created!')
            return HttpResponseRedirect(reverse('ditto:home'))
    else:
        form = forms.TenantForm(request.user)
    return render(request, 'tenant/create.html', {
        'form': form,
        'networks': models.Tenant.objects.all(),
    })


def _go_to_my_network(request, tenant):
    return render(request, 'tenant/go.html', {
        'tenant': tenant,
        'networks': models.Tenant.objects.all(),
    })


def _create_network_instance(tenant):
    admin = tenant.user
    admin_emails = list(admin.emailaddress_set.all())
    subdomain = tenant.slug
    network_name = tenant.network_name
    parent_domain = Site.objects.get_current().domain
    with utils._tenant(tenant.slug):
        # TODO in the real world we'll send a task off to some queue that'll go do bunch of stuff

        management.call_command('migrate', verbosity=0)

        management.call_command('runscript', 'setup_test_data')

        # remove dummy users created by test data script
        get_user_model().objects.all().delete()
        
        # copy the current user to the network database and make an admin
        admin.pk = None
        admin.is_new = True
        admin.save()
        for email in admin_emails:
            admin.emailaddress_set.create(
                email=email.email,
                verified=1
            )
        admin.groups.add(Group.objects.get(name=ditto.config.ADMIN_ROLE))

        # copy over network name
        site = Site.objects.get_current()
        site.domain = '%s.%s' % (subdomain, parent_domain)
        site.name = network_name
        site.save()


# TODO restrict this to requests from chat (localhost for now)?
@never_cache
def get_password(request):
    if settings.DEBUG:
        return HttpResponse()
    username = request.GET['user']
    tenant_slug = _get_tenant(request.GET['server'])
    with _tenant(tenant_slug):
        user = get_object_or_404(User, username=username)
    signer = Signer()
    value = signer.sign(user.username)
    return HttpResponse(value)


def _get_tenant(server):
    chat_domain = server
    network = chat_domain.split('.')[0]
    tenant_pk = network.replace('network', '')
    tenant = get_object_or_404(models.Tenant, pk=tenant_pk)
    return tenant.slug
{'fraction_non_alphanumeric': 0.09322033898305085, 'fraction_numerical': 0.003798947983635301, 'mean_word_length': 2.9612268518518516, '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': '2334150', 'n_tokens_mistral': 1959, 'n_tokens_neox': 1949, 'n_words': 490}