Example #1
0
def get_option(option_name, **kwargs):
    """
    Get option from database
    """

    _db = get_db()
    dbc = _db.cursor()

    q = '''SELECT o_value FROM options where o_key = '{}' '''.format(option_name)
    try:
        dbc.execute(q)
    except IntegrityError as e:
        log.critical('Error getting option {}: {}'.format(option_name, e))
        return base_common.msg.error(msgs.ERROR_GET_OPTION)

    if dbc.rowcount != 1:
        log.warning('Found {} options {}'.format(dbc.rowcount, option_name))
        return base_common.msg.error(msgs.OPTION_NOT_EXIST)

    _dbr = dbc.fetchone()
    _dbrk = _dbr['o_value']
    res = {}
    res[option_name] = _dbrk

    return base_common.msg.get_ok(res)
Example #2
0
def get_current_datetime():

    _db = get_db()
    dbc = _db.cursor()
    _t = 'test_datetime'

    if base_config.settings.TEST_MODE:
        q = '''SELECT o_value FROM options where o_key = '{}' '''.format(_t)
        try:
            dbc.execute(q)
        except IntegrityError as e:
            log.critical('Error reading {} from database: {}'.format(_t, e))
            return False

        if dbc.rowcount != 1:
            log.warning('Found {} current date occurrences'.format(dbc.rowcount))
            return datetime.datetime.now()

        _td = dbc.fetchone()

        try:
            _td_datetime = datetime.datetime.strptime(_td['o_value'], '%Y-%m-%d %H:%M:%S.%f')
        except ValueError as e:
            log.critical('Error creating datetime from {}: {}'.format(_td['o_value'], e))
            return False

        return _td_datetime
    else:
        return datetime.datetime.now()
Example #3
0
def _authorized_by_token_in_redis(tk):

    if not __get_user_by_token_from_redis(tk, True):
        log.warning("Access token {} not found".format(tk))
        return False

    return True
Example #4
0
def _authorized_by_token_in_redis(tk):

    if not __get_user_by_token_from_redis(tk, True):
        log.warning("Access token {} not found".format(tk))
        return False

    return True
Example #5
0
def get_current_datetime():

    _db = get_db()
    dbc = _db.cursor()
    _t = 'test_datetime'

    if base_config.settings.TEST_MODE:
        q = '''SELECT o_value FROM options where o_key = '{}' '''.format(_t)
        try:
            dbc.execute(q)
        except IntegrityError as e:
            log.critical('Error reading {} from database: {}'.format(_t, e))
            return False

        if dbc.rowcount != 1:
            log.warning('Found {} current date occurrences'.format(
                dbc.rowcount))
            return datetime.datetime.now()

        _td = dbc.fetchone()

        try:
            _td_datetime = datetime.datetime.strptime(_td['o_value'],
                                                      '%Y-%m-%d %H:%M:%S.%f')
        except ValueError as e:
            log.critical('Error creating datetime from {}: {}'.format(
                _td['o_value'], e))
            return False

        return _td_datetime
    else:
        return datetime.datetime.now()
Example #6
0
def authorized_by_token(db, tk):

    if not tk:
        log.warning("Access token not provided")
        return False

    if SESSION_STORAGE in ss.map_ and ss.map_[SESSION_STORAGE] == ss.REDIS:
        return _authorized_by_token_in_redis(tk)

    return _authorized_by_token_in_sql(db, tk)
Example #7
0
def authorized_by_token(db, tk):

    if not tk:
        log.warning("Access token not provided")
        return False

    if SESSION_STORAGE in ss.map_ and ss.map_[SESSION_STORAGE] == ss.REDIS:
        return _authorized_by_token_in_redis(tk)

    return _authorized_by_token_in_sql(db, tk)
Example #8
0
def _authorized_by_token_in_sql(db, tk):

    dbc = db.cursor()
    if not __get_user_by_token_from_sql(dbc, tk, True):
        log.warning("Access token {} not found".format(tk))
        return False

    db_u = dbc.fetchone()
    if db_u['closed']:
        log.warning("Session {} closed".format(tk))
        return False

    return True
Example #9
0
def _authorized_by_token_in_sql(db, tk):

    dbc = db.cursor()
    if not __get_user_by_token_from_sql(dbc, tk, True):
        log.warning("Access token {} not found".format(tk))
        return False

    db_u = dbc.fetchone()
    if db_u["closed"]:
        log.warning("Session {} closed".format(tk))
        return False

    return True
Example #10
0
        def wrapper(*args, **kwargs):

            ags = []
            request = kwargs['request_handler']

            for a in arguments:

                default_arg_value = a['default'] if 'default' in a else None
                argmnt = a['arg'].strip()

                atr = request.get_argument(argmnt, default=default_arg_value)

                required = a['required'] if 'required' in a else True

                if atr is None:
                    if not required:
                        converted = None
                    else:
                        log.critical(
                            'Missing request argument: {}'.format(argmnt))
                        return base_common.msg.error(
                            amsgs.MISSING_REQUEST_ARGUMENT)
                else:
                    tip = a['type'] if 'type' in a else str
                    esc = a['escaped'] if 'escaped' in a else (
                        tip in [str, 'e-mail'])

                    converted = _convert_args(atr, tip, esc)
                    if tip != bool and converted is None:

                        if not (tip == int
                                and converted == 0):  # count 0 as int

                            c_type = "|type get error|"
                            try:
                                c_type = type(atr)
                            except Exception as e:
                                log.warning(
                                    'Get argument type error: {}'.format(e))

                            log.critical(
                                'Invalid request argument {} type {}, expected {}'
                                .format(atr, c_type, tip))
                            return base_common.msg.error(
                                amsgs.INVALID_REQUEST_ARGUMENT)

                ags.append(converted)

            return original(*ags, **kwargs)
Example #11
0
def check_user_exists(username, db, userid=None):
    dbc = db.cursor()
    if userid:
        q = "select id from users where id = '{}'".format(userid)
    else:
        q = "select id from users where username = '******'".format(username)

    try:
        dbc.execute(q)
    except IntegrityError as e:
        log.critical('Check user: {}'.format(e))
        return False

    if dbc.rowcount != 1:
        log.warning('Fund {} users with {} username'.format(dbc.rowcount, username))
        return False

    return True
Example #12
0
def do_get(h, grant_access, **kwargs):
    """
    Get data for given hash
    """

    _db = get_db()
    dbc = _db.cursor()

    get_data_q = prepare_get_query(h)

    try:
        dbc.execute(get_data_q)
    except IntegrityError as e:
        log.critical('Retrieve data for hash: {}'.format(e))
        return base_common.msg.error('Retrieve hash data')

    if dbc.rowcount != 1:
        log.warning('Found {} hashes'.format(dbc.rowcount))
        return base_common.msg.error('No data found for given hash')

    dbd = dbc.fetchone()
    d = dbd['data']
    did = dbd['id']
    d_last_accessed = dbd['last_access']

    if d_last_accessed:
        log.warning('New access to {}'.format(h))

        if not log_hash_access(_db, did, kwargs['r_ip']):
            log.warning("Error save hash access log")

        if not grant_access:
            return base_common.msg.error(msgs.WRONG_OR_EXPIRED_TOKEN)

    try:
        d = json.loads(d)
    except Exception as e:
        log.warning('Load hash data: {}'.format(e))

    if not log_hash_access(_db, did, kwargs['r_ip']):
        log.warning("Error save hash access log")

    return base_common.msg.get_ok(d)
Example #13
0
def check_user_exists(username, db, userid=None):
    dbc = db.cursor()
    if userid:
        q = "select id from users where id = '{}'".format(userid)
    else:
        q = "select id from users where username = '******'".format(username)

    try:
        dbc.execute(q)
    except IntegrityError as e:
        log.critical('Check user: {}'.format(e))
        return False

    if dbc.rowcount != 1:
        log.warning('Fund {} users with {} username'.format(
            dbc.rowcount, username))
        return False

    return True
Example #14
0
def do_get(h, grant_access, **kwargs):
    """
    Get data for given hash
    """

    _db = get_db()
    dbc = _db.cursor()

    get_data_q = prepare_get_query(h)

    try:
        dbc.execute(get_data_q)
    except IntegrityError as e:
        log.critical('Retrieve data for hash: {}'.format(e))
        return base_common.msg.error('Retrieve hash data')

    if dbc.rowcount != 1:
        log.warning('Found {} hashes'.format(dbc.rowcount))
        return base_common.msg.error('No data found for given hash')

    dbd = dbc.fetchone()
    d = dbd['data']
    did = dbd['id']
    d_last_accessed = dbd['last_access']

    if d_last_accessed:
        log.warning('New access to {}'.format(h))

        if not log_hash_access(_db, did, kwargs['r_ip']):
            log.warning("Error save hash access log")

        if not grant_access:
            return base_common.msg.error(msgs.WRONG_OR_EXPIRED_TOKEN)

    try:
        d = json.loads(d)
    except Exception as e:
        log.warning('Load hash data: {}'.format(e))

    if not log_hash_access(_db, did, kwargs['r_ip']):
        log.warning("Error save hash access log")

    return base_common.msg.get_ok(d)
Example #15
0
        def wrapper(*args, **kwargs):

            ags = []
            request = kwargs['request_handler']

            for a in arguments:

                default_arg_value = a['default'] if 'default' in a else None
                argmnt = a['arg'].strip()

                atr = request.get_argument(argmnt, default=default_arg_value)

                required = a['required'] if 'required' in a else True

                if not atr:
                    if not required:
                        converted = None
                    else:
                        log.critical('Missing request argument: {}'.format(argmnt))
                        return base_common.msg.error(amsgs.MISSING_REQUEST_ARGUMENT)
                else:
                    tip = a['type'] if 'type' in a else str
                    esc = a['escaped'] if 'escaped' in a else (tip in [str, 'e-mail'])

                    converted = _convert_args(atr, tip, esc)
                    if not converted:

                        if not (tip == int and converted == 0):   # count 0 as int

                            c_type = "|type get error|"
                            try:
                                c_type = type(atr)
                            except Exception as e:
                                log.warning('Get argument type error: {}'.format(e))

                            log.critical('Invalid request argument {} type {}, expected {}'.format(atr, c_type, tip))
                            return base_common.msg.error(amsgs.INVALID_REQUEST_ARGUMENT)

                ags.append(converted)

            return original(*ags, **kwargs)
Example #16
0
def do_post(**kwargs):
    """
    Logout user
    """

    _db = get_db()
    dbc = _db.cursor()

    request = kwargs['request_handler']

    tk = request.auth_token

    dbuser = get_user_by_token(_db, tk)

    if not close_session_by_token(dbc, tk):
        log.warning("Closing session with token {}".format(tk))
        return base_common.msg.error(msgs.CLOSE_USER_SESSION)

    _db.commit()

    apphooks.action_log_hook(dbuser.id_user, kwargs['r_ip'], 'logout', 'user {} successfuly logged out'.format(dbuser.username))
    return base_common.msg.post_ok()
Example #17
0
def send_message(sender, _to, subject, message):

    receiver = [{'email': _to, 'name': _to, 'type': 'to'}]
    msg = {
        'from_email': sender,
        'from_name': sender,
        'html': message,
        'subject': subject,
        'to': receiver,
        # 'auto_html': None,        # automatic html generating if html not provided
        # 'auto_text': None,        # automatic text generating if text not provided
        # 'bcc_address': '*****@*****.**', # bcc address
        # 'headers': {'Reply-To': '*****@*****.**'}, # additional headers
        # 'inline_css': None,       # if css has to be inline (only for <=256 line messages)
        # 'preserve_recipients': None,  # if every receiver has to see other receivers in header
        # 'text': 'Example text content',   # message plain text
        # 'view_content_link': None     # False for disable content logging for sensitive mails
    }
    # if _site:
    #     msg['metadata'] = {'website': _site}
    # if tags:
    #     msg['tags'] = tags

    m = get_mail_api()
    try:
        res = m.messages.send(message=msg, async=False)
    except mandrill.Error as e:
        log.critical('MANDRILL send message error: {}'.format(e))
        return False

    if 'status' not in res or res['status'] != 'sent':
        log.warning('MANDRILL send mail error status: {}'.format(res))
        return False

    log.info('Receiver: {}, status: {}'.format(_to, res))
    return True
Example #18
0
def send_message(sender, _to, subject, message):

    receiver = [{'email': _to, 'name': _to, 'type': 'to'}]
    msg = {
        'from_email': sender,
        'from_name': sender,
        'html': message,
        'subject': subject,
        'to': receiver,
        # 'auto_html': None,        # automatic html generating if html not provided
        # 'auto_text': None,        # automatic text generating if text not provided
        # 'bcc_address': '*****@*****.**', # bcc address
        # 'headers': {'Reply-To': '*****@*****.**'}, # additional headers
        # 'inline_css': None,       # if css has to be inline (only for <=256 line messages)
        # 'preserve_recipients': None,  # if every receiver has to see other receivers in header
        # 'text': 'Example text content',   # message plain text
        # 'view_content_link': None     # False for disable content logging for sensitive mails
    }
    # if _site:
    #     msg['metadata'] = {'website': _site}
    # if tags:
    #     msg['tags'] = tags

    m = get_mail_api()
    try:
        res = m.messages.send(message=msg, async=False)
    except mandrill.Error as e:
        log.critical('MANDRILL send message error: {}'.format(e))
        return False

    if 'status' not in res or res['status'] != 'sent':
        log.warning('MANDRILL send mail error status: {}'.format(res))
        return False

    log.info('Receiver: {}, status: {}'.format(_to, res))
    return True