Esempio n. 1
0
def mysql_execute(command, params=None):
    """
    Function to execute a sql statement on the mysql database. This function is
    called by the database_execute function when the mysql backend is set in
    the configuration file.

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    getLogger("database").debug("mysql_execute(" + command + ", " + str(params)
                                + ")", extra=get_sql_log_dict())
    try:
        host = config.get('database', 'hostname')
        user = config.get('database', 'username')
        pawd = config.get('database', 'password')
        dbse = config.get('database', 'database')
        port = config.getint('database', 'port')
        connection = mysql_connect(host=host, port=port, user=user,
                                   passwd=pawd, db=dbse)
        cursor = connection.cursor()
        cursor.execute(command, params)
        connection.commit()
        return cursor.fetchall()
    except MySQLError as mysqlerror:
        print("MySQL Error: %d: %s" %
              (mysqlerror.args[0], mysqlerror.args[1]))
    finally:
        try:
            if connection:
                connection.close()
        except UnboundLocalError:
            pass
Esempio n. 2
0
def get_sql_log_dict():
    dbtype = config.get('database', 'type')
    if dbtype == 'sqlite':
        ip = config.get('database', 'filename')
    else:
        ip = config.get('database', 'hostname')
    return {'ip': ip, 'user': '', 'path': 'database/'}
Esempio n. 3
0
def get_sql_log_dict():
    dbtype = config.get('database', 'type')
    if dbtype == 'sqlite':
        ip = config.get('database', 'filename')
    else:
        ip = config.get('database', 'hostname')
    return {'ip': ip, 'user': '', 'path': 'database/'}
Esempio n. 4
0
    def check(request_handler):
        request_handler.user = check_authorization(request_handler)

        if not request_handler.user:
            request_handler.status = 401

            if request_handler.back_url:
                querystring = urlencode(
                    {'redirect_uri': request_handler.back_url})
            else:
                querystring = urlencode({
                    'redirect_uri':
                    request_handler.protocol +
                    request_handler.headers['Host'] + request_handler.path
                })

            redirect_url = config.get(
                'oauth', 'redirect_url',
                default=defaults.REDIRECT_URL) + "?" + querystring
            getLogger(__name__).debug('redirect_url: %s' % redirect_url,
                                      extra=request_handler.get_log_dict())
            request_handler.new_headers[
                'WWW-Authenticate'] = 'Bearer domain="' + redirect_url + '"'
            request_handler.body = "<h1>401: Forbidden.</h1>" \
                                   "<p>Authorization failed. Please authenticate at" \
                                   "<a href=\"{0}\">{1}</a></p>".format(redirect_url, redirect_url)
        else:
            func(request_handler)
Esempio n. 5
0
def database_execute(command, params=None):
    """
    Function to execute a sql statement on the database. Executes the right
    backend and makes sure '?' is replaced for the local substitution variable
    if needed.

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    getLogger("database").debug("database_execute(" + command + ", " +
                                str(params) + ")",
                                extra=get_sql_log_dict())
    dbtype = config.get('database', 'type')

    if dbtype == "mysql":
        if mysql_execute is None:
            exit("Trying to use a MySQL database without python-MySQL module.")
        command = command.replace('?', '%s')
        return mysql_execute(command, params)

    elif (dbtype == "sqlite3") or (dbtype == "sqlite"):
        return sqlite_execute(command, params)
    else:
        print("Unknown database type, cannot continue")
Esempio n. 6
0
def database_execute(command, params=None):
    """
    Function to execute a sql statement on the database. Executes the right
    backend and makes sure '?' is replaced for the local substitution variable
    if needed.

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    getLogger("database").debug("database_execute(" + command + ", " +
                                str(params) + ")", extra=get_sql_log_dict())
    dbtype = config.get('database', 'type')

    if dbtype == "mysql":
        if mysql_execute is None:
            exit(
                "Trying to use a MySQL database without python-MySQL module.")
        command = command.replace('?', '%s')
        return mysql_execute(command, params)

    elif (dbtype == "sqlite3") or (dbtype == "sqlite"):
        return sqlite_execute(command, params)
    else:
        print("Unknown database type, cannot continue")
Esempio n. 7
0
def mysql_execute(command, params=None):
    """
    Function to execute a sql statement on the mysql database. This function is
    called by the database_execute function when the mysql backend is set in
    the configuration file.

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    getLogger("database").debug("mysql_execute(" + command + ", " +
                                str(params) + ")",
                                extra=get_sql_log_dict())
    try:
        host = config.get('database', 'hostname')
        user = config.get('database', 'username')
        pawd = config.get('database', 'password')
        dbse = config.get('database', 'database')
        port = config.getint('database', 'port')
        connection = mysql_connect(host=host,
                                   port=port,
                                   user=user,
                                   passwd=pawd,
                                   db=dbse)
        cursor = connection.cursor()
        cursor.execute(command, params)
        connection.commit()
        return cursor.fetchall()
    except MySQLError as mysqlerror:
        print("MySQL Error: %d: %s" % (mysqlerror.args[0], mysqlerror.args[1]))
    finally:
        try:
            if connection:
                connection.close()
        except UnboundLocalError:
            pass
Esempio n. 8
0
def check_authorization(request_handler):
    """
    Assert whether the authorization header is valid by checking it against
    the cache first and if unsuccessful, the oauth server. Sets the 'user'
    field of the request_handler object.

    :return: When successful returns user's name. Returns None on failure.
    """
    auth_header = request_handler.headers.getheader('Authorization')
    if auth_header is None:
        getLogger('auth').debug(
            "authentication failed: no Authorization header available",
            extra=request_handler.get_log_dict())
        return None
    auth_url = config.get('oauth', 'verify_url', default=defaults.VERIFY_URL)
    getLogger('auth').debug("verify_url: %s" % auth_url,
                            extra=request_handler.get_log_dict())
    cache = TimedCache(timeout=0)  # FIXME: Cache is broken
    name = cache.get(auth_header)
    if name is not None:
        return name
    auth_request = Request(auth_url, None, {'Authorization': auth_header})
    try:
        ctx = SSLContext(SSL_PROTOCOL)
        response = urlopen(auth_request, context=ctx)
        name = response.read()
    except HTTPError as error:
        if error.code == 403:
            getLogger('auth').debug(
                "authentication failed: Wrong/expired code",
                extra=request_handler.get_log_dict())
        else:
            getLogger('auth').debug("authentication failed: HttpError %s" %
                                    error,
                                    extra=request_handler.get_log_dict())
        name = ''
    if name == '':
        name = None
        getLogger('auth').debug('authentication failed: response %s' % name,
                                extra=request_handler.get_log_dict())
    else:
        getLogger('auth').debug('Authenticated user: ' + name,
                                extra=request_handler.get_log_dict())
        cache.add(auth_header, name)
    return name
Esempio n. 9
0
def check_authorization(request_handler):
    """
    Assert whether the authorization header is valid by checking it against
    the cache first and if unsuccessful, the oauth server. Sets the 'user'
    field of the request_handler object.

    :return: When successful returns user's name. Returns None on failure.
    """
    auth_header = request_handler.headers.getheader('Authorization')
    if auth_header is None:
        getLogger('auth').debug("authentication failed: no Authorization header available",
                                extra=request_handler.get_log_dict())
        return None
    auth_url = config.get('oauth', 'verify_url', default=defaults.VERIFY_URL)
    getLogger('auth').debug("verify_url: %s" % auth_url, extra=request_handler.get_log_dict())
    cache = TimedCache(timeout=0)  # FIXME: Cache is broken
    name = cache.get(auth_header)
    if name is not None:
        return name
    auth_request = Request(auth_url, None, {'Authorization': auth_header})
    try:
        ctx = SSLContext(SSL_PROTOCOL)
        response = urlopen(auth_request, context=ctx)
        name = response.read()
    except HTTPError as error:
        if error.code == 403:
            getLogger('auth').debug("authentication failed: Wrong/expired code",
                                    extra=request_handler.get_log_dict())
        else:
            getLogger('auth').debug("authentication failed: HttpError %s" % error,
                                    extra=request_handler.get_log_dict())
        name = ''
    if name == '':
        name = None
        getLogger('auth').debug('authentication failed: response %s' % name,
                                extra=request_handler.get_log_dict())
    else:
        getLogger('auth').debug('Authenticated user: ' + name,
                                extra=request_handler.get_log_dict())
        cache.add(auth_header, name)
    return name
Esempio n. 10
0
    def check(request_handler):
        request_handler.user = check_authorization(request_handler)

        if not request_handler.user:
            request_handler.status = 401

            if request_handler.back_url:
                querystring = urlencode({'redirect_uri': request_handler.back_url})
            else:
                querystring = urlencode({'redirect_uri': request_handler.protocol
                                                         + request_handler.headers['Host']
                                                         + request_handler.path})

            redirect_url = config.get('oauth', 'redirect_url', default=defaults.REDIRECT_URL) + "?" + querystring
            getLogger(__name__).debug('redirect_url: %s' % redirect_url, extra=request_handler.get_log_dict())
            request_handler.new_headers['WWW-Authenticate'] = 'Bearer domain="' + redirect_url + '"'
            request_handler.body = "<h1>401: Forbidden.</h1>" \
                                   "<p>Authorization failed. Please authenticate at" \
                                   "<a href=\"{0}\">{1}</a></p>".format(redirect_url, redirect_url)
        else:
            func(request_handler)
Esempio n. 11
0
def sqlite_execute(command, params=None):
    """
    Function to execute a sql statement on the mysql database. This function is
    called by the database_execute function when the sqlite backend is set in
    the configuration file

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    # NOTE mostly copypasta'd from mysql_execute, may be a better way
    try:
        filename = config.get('database', 'filename')
        init_db = not exists(filename)
        connection = sqlite_connect(filename)
        cursor = connection.cursor()
        if init_db:
            for sql in open('database.sql').read().split("\n"):
                if sql != "" and sql is not None:
                    cursor.execute(sql)
                    connection.commit()
        if params:
            cursor.execute(command, params)
        else:
            cursor.execute(command)
        connection.commit()
        return cursor.fetchall()
    except MySQLError as mysqlerror:
        print("MySQL Error: %d: %s" %
              (mysqlerror.args[0], mysqlerror.args[1]))
    except NoSectionError:
        print("Please configure the database")
    finally:
        try:
            if connection:
                connection.close()
        except UnboundLocalError:
            pass
Esempio n. 12
0
def sqlite_execute(command, params=None):
    """
    Function to execute a sql statement on the mysql database. This function is
    called by the database_execute function when the sqlite backend is set in
    the configuration file

    :param command: the sql command to execute
    :param params: a list of tuple of values to substitute in command
    :returns: a list of dictionaries representing the sql result
    """
    # NOTE mostly copypasta'd from mysql_execute, may be a better way
    try:
        filename = config.get('database', 'filename')
        init_db = not exists(filename)
        connection = sqlite_connect(filename)
        cursor = connection.cursor()
        if init_db:
            for sql in open('database.sql').read().split("\n"):
                if sql != "" and sql is not None:
                    cursor.execute(sql)
                    connection.commit()
        if params:
            cursor.execute(command, params)
        else:
            cursor.execute(command)
        connection.commit()
        return cursor.fetchall()
    except MySQLError as mysqlerror:
        print("MySQL Error: %d: %s" % (mysqlerror.args[0], mysqlerror.args[1]))
    except NoSectionError:
        print("Please configure the database")
    finally:
        try:
            if connection:
                connection.close()
        except UnboundLocalError:
            pass
Esempio n. 13
0
def get_ssl_cert():
    certfile = config.get('httpd', 'certfile')
    keyfile = config.get('httpd', 'keyfile')

    # TODO: if not exits(certfile) create_self_signed_cert()
    return (certfile, keyfile)
Esempio n. 14
0
def get_bindpoint():
    bindpoint = os.path.expandvars(config.get('filesystem', 'bindpoint'))
    return bindpoint
Esempio n. 15
0
def get_ssl_cert():
    certfile = config.get('httpd', 'certfile')
    keyfile = config.get('httpd', 'keyfile')

    # TODO: if not exits(certfile) create_self_signed_cert()
    return (certfile, keyfile)
Esempio n. 16
0
def get_bindpoint():
    bindpoint = os.path.expandvars(config.get('filesystem', 'bindpoint'))
    return bindpoint