<commit_before>from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render
import json
import uuid

def json_response(object):
    return HttpResponse(json.dumps(object, indent=4),
                        content_type="application/json")

def docs(request):
    return render(request, "docs.html", { "test": "foox" })

def create_account(request):
    cursor = connection.cursor()
    # TODO reject empty names etc
    # TODO check if the password is not good enough according to some policy
    # TODO likewise for the username

    # the following checks are 'polite' ways to discover emails and
    # username already in use and give a friendly error message:
    # obviously there is also a race here due to concurrency, and the
    # database will enforce uniqueness (the error will just be uglier
    # if we get there); in theory you'd just use the DB and detect
    # those errors specially, a job for another day
    
    # check if the email address is already known to us
    cursor.execute("""SELECT 1
                        FROM person
                       WHERE email = %s""",
                   (request.POST["email"],))
    if cursor.fetchone():
        return json_response({ "status" : "EMAIL_IN_USE" })

    # check if the email address is already known to us
    cursor.execute("""SELECT 1
                        FROM person
                       WHERE username = %s""",
                   (request.POST["username"],))
    if cursor.fetchone():
        return json_response({ "status" : "USERNAME_IN_USE" })
    
    # clear to proceed
    cursor.execute("""INSERT INTO person (username, firstname, lastname, email, status, password_hash, created, logins)
                      VALUES (%s, %s, %s, %s, 'ACTIVE', crypt(%s, gen_salt('bf')), now(), 0)""",
                   (request.POST["username"],
                    request.POST["firstname"],
                    request.POST["lastname"],
                    request.POST["email"],
                    request.POST["password"]))
    return json_response({ "status" : "OK" })

def login(request):
    cursor = connection.cursor()
    cursor.execute("""SELECT id, firstname, lastname, email, status
                        FROM person
                       WHERE username = %s
                         AND password_hash = crypt(%s, password_hash)""",
                  (request.POST["username"], request.POST["password"]))
    row = cursor.fetchone()
    if row == None:
        # TODO count failures, implement back-off
        response = { "status": "FAIL" }
    else:
        id, firstname, lastname, email, status = row        
        if status == "ACTIVE":
            token = uuid.uuid4().hex
            cursor.execute("""INSERT INTO login_session (token, person, created)
                              VALUES (%s, %s, now())""",
                           (token, id))
            cursor.execute("""UPDATE person
                                 SET last_login = now(),
                                     logins = logins + 1
                               WHERE id = %s""",
                           (id,))
            response = { "status" : "OK",
                         "firstname" : firstname,
                         "lastname" : lastname,
                         "email" : email,
                         "token" : token }
        else:
            response = { "status" : "FAIL" }
            # TODO handle this case
    return json_response(response)

def logout(request):
    cursor = connection.cursor()
    cursor.execute("""UPDATE login_session
                         SET ended = now()
                       WHERE token = %s
                         AND ended IS NULL""",
                   (request.POST["token"],))
    if cursor.rowcount == 1:
        response = { "status" : "OK" }
    else:
        response = { "status" : "FAIL" }
    return json_response(response)

def schedule(request, username):
    cursor = connection.cursor()<commit_msg>This deserves simple flow control.<commit_after>from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render
import json
import uuid

def json_response(object):
    """A convenience function for generating a JSON HTTP response."""
    return HttpResponse(json.dumps(object, indent=4),
                        content_type="application/json")

def docs(request):
    return render(request, "docs.html", { "test": "foox" })

def create_account(request):
    cursor = connection.cursor()
    # TODO reject empty names etc
    # TODO check if the password is not good enough according to some policy
    # TODO likewise for the username

    # the following checks are 'polite' ways to discover emails and
    # username already in use and give a friendly error message:
    # obviously there is also a race here due to concurrency, and the
    # database will enforce uniqueness (the error will just be uglier
    # if we get there); in theory you'd just use the DB and detect
    # those errors specially, a job for another day
    
    # check if the email address is already known to us
    cursor.execute("""SELECT 1
                        FROM person
                       WHERE email = %s""",
                   (request.POST["email"],))
    if cursor.fetchone():
        return json_response({ "status" : "EMAIL_IN_USE" })

    # check if the email address is already known to us
    cursor.execute("""SELECT 1
                        FROM person
                       WHERE username = %s""",
                   (request.POST["username"],))
    if cursor.fetchone():
        return json_response({ "status" : "USERNAME_IN_USE" })
    
    # clear to proceed
    cursor.execute("""INSERT INTO person (username, firstname, lastname, email, status, password_hash, created, logins)
                      VALUES (%s, %s, %s, %s, 'ACTIVE', crypt(%s, gen_salt('bf')), now(), 0)""",
                   (request.POST["username"],
                    request.POST["firstname"],
                    request.POST["lastname"],
                    request.POST["email"],
                    request.POST["password"]))
    return json_response({ "status" : "OK" })

def login(request):
    cursor = connection.cursor()
    cursor.execute("""SELECT id, firstname, lastname, email, status
                        FROM person
                       WHERE username = %s
                         AND password_hash = <PASSWORD>, password_<PASSWORD>)""",
                  (request.POST["username"], request.POST["password"]))
    row = cursor.fetchone()
    if row == None:
        # TODO count failures, implement back-off
        return json_response({ "status": "FAIL" })
        
    id, firstname, lastname, email, status = row        
    if status == "ACTIVE":
        token = <KEY>
        cursor.execute("""INSERT INTO login_session (token, person, created)
                          VALUES (%s, %s, now())""",
                       (token, id))
        cursor.execute("""UPDATE person
                             SET last_login = now(),
                                 logins = logins + 1
                           WHERE id = %s""",
                       (id,))
        return json_response({ "status" : "OK",
                               "firstname" : firstname,
                               "lastname" : lastname,
                               "email" : email,
                               "token" : token })
    else:
        # TODO handle this case better (say 'you're banned'?)
        return json_response({ "status" : "FAIL" })

def logout(request):
    cursor = connection.cursor()
    cursor.execute("""UPDATE login_session
                         SET ended = now()
                       WHERE token = %s
                         AND ended IS NULL""",
                   (request.POST["token"],))
    if cursor.rowcount == 1:
        return json_response({ "status" : "OK" })
    else:
        return json_response({ "status" : "FAIL" })

def schedule(request, username):
    cursor = connection.cursor()
{'fraction_non_alphanumeric': 0.10929368029739776, 'fraction_numerical': 0.00161090458488228, 'mean_word_length': 1.7725867399519066, 'pattern_counts': {'":': 6, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '233832', 'n_tokens_mistral': 2046, 'n_tokens_neox': 1971, 'n_words': 666}