import sys, psycopg2, psycopg2.extras

def generate(user_id, db):
    try:
        with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            cursor.execute("""
            INSERT INTO minicloud_auths (user_id) VALUES (%s) RETURNING token
            """, [int(user_id)])

            data = cursor.fetchone()
            db.commit()
            return data['token']

    except Exception as e:
        db.rollback()
        sys.stderr('%s\n' % 'No token generated!')

    return None

def revoke(user_id, db):
    try:
        with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            cursor.execute("""
            DELETE FROM minicloud_auths WHERE user_id = %s
            """, [user_id])

            db.commit()
            sys.stderr.write('X-Auth-Token revoked\n')
            return True

    except Exception as e:
        db.rollback()
        sys.stderr.write('Revoke X-Auth-Token failed: %s\n' % str(e))

    return False

import sys, psycopg2, psycopg2.extras

def generate(user_id, db):
    try:
        with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            cursor.execute("""
            INSERT INTO minicloud_auths (user_id) VALUES (%s) RETURNING token
            """, [int(user_id)])

            data = cursor.fetchone()
            db.commit()
            return data['token']

    except Exception as e:
        db.rollback()
        sys.stderr('%s\n' % 'No token generated!')

    return None

def revoke(user_id, db):
    try:
        with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
            cursor.execute("""
            DELETE FROM minicloud_auths WHERE user_id = %s
            """, [user_id])

            db.commit()
            sys.stderr.write('X-Auth-Token revoked\n')
            return True

    except Exception as e:
        db.rollback()
        sys.stderr.write('Revoke X-Auth-Token failed: %s\n' % str(e))

    return False

INSERT INTO minicloud_auths (user_id) VALUES (%s) RETURNING token DELETE FROM minicloud_auths WHERE user_id = %s