tobyqin/testcube

View on GitHub
testcube/core/api/client_auth.py

Summary

Maintainability
A
35 mins
Test Coverage
"""
Will provide auth to testcube clients, will not expose such API to all users.
"""

import re
import uuid

from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from ipware.ip import get_ip

from testcube.core.models import TestClient
from testcube.settings import VERSION


@csrf_exempt
def register(request):
    """To register a new client, must provide a token"""
    if request.method == 'POST':
        data = request.POST
        client_type = data.get('client_type')
        pattern = r'testcube_([\d\w]+)_client'
        match = re.search(pattern, client_type)

        try:
            if match:
                client_type = match.group(1)
                client_name = data.get('client_name')
                client_user = data.get('client_user')
                client_ip = get_ip(request)
                username = '_<{}>_'.format(client_name)
                email = '{}@{}.client'.format(client_name, client_type).lower()

                user, created = User.objects.update_or_create(
                    username=username,
                    defaults={'email': email,
                              'first_name': client_user,
                              'last_name': client_ip})

                token = uuid.uuid4()
                user.set_password(token)
                user.save()

                TestClient.objects.update_or_create(
                    name=client_name,
                    defaults={'ip': client_ip,
                              'platform': data.get('platform'),
                              'owner': client_user})

                return JsonResponse(
                    {'client': user.username,
                     'token': token,
                     'first_time_register': created})
            else:
                raise ValueError('client_type should match pattern: "testcube_xxx_client".')

        except Exception as e:
            error = '{}: {}'.format(type(e).__name__, ','.join(e.args))
            return HttpResponseBadRequest('Failed to register testcube, {}'.format(error))

    else:
        return HttpResponse(content=VERSION)