コード例 #1
0
ファイル: database.py プロジェクト: reiosantos/tip-api
def update_request_token(user_id):
    sessions = get_sessions()
    token = generate_token()
    if not isinstance(user_id, ObjectId):
        if not len(user_id) == 24:
            return False
        mt = sessions.find_one_and_update(
            {"data.user_id": ObjectId(user_id)}, {
                "$set": {
                    "data.token": token,
                    "data.expiration": make_date_time(SESSION_LIFETIME)
                }
            },
            upsert=False,
            return_document=True)
        if not mt:
            return False
    else:
        mt = sessions.find_one_and_update({"data.user_id": user_id}, {
            "$set": {
                "data.token": token,
                "data.expiration": make_date_time(SESSION_LIFETIME)
            }
        },
                                          upsert=False,
                                          return_document=True)
        if not mt:
            return False
    return True
コード例 #2
0
def get_new_local_alerts():
    """
    alerts from own local network
    :return:
    """
    ip_details = my_ip_details()
    m = int(minutes_a_record_remains_new())
    new_date = make_date_time(seconds_to_subtract=m * 60)
    f = []
    if not ip_details:
        return None
    data = get_feeds().find({"time.observation": {"$gt": new_date}, "source.network": ip_details['network'],
                             "$or": [{"source.ip": {"$exists": True}, "source.network": {"$exists": True}}]})\
        .sort([("time_observation", DESCENDING)])
    if data and data.count() > 0:
        data = normalize_dict(data)
        for x, value in data.items():
            value['id'] = x
            if '_id' in value:
                del value['_id']
            if 'raw' in value:
                del value['raw']

            f.append(value)

    create_log(None, None, "{0} Local attacks detected : ".format(len(f)),
               LOG_SYSTEM_TYPE)
    return f
コード例 #3
0
def clear_old_records():
    days_for_keeping = int(minutes_to_keep_feed())
    lock.acquire()

    current_date = make_date_time(seconds_to_subtract=days_for_keeping * 60)

    feeds = get_feeds()
    blocked = get_blocked_by_ip()
    n_blocked = get_blocked_by_network()
    warned = get_warned_by_ip()
    n_warned = get_warned_by_network()

    to_delete = feeds.find({"time.observation": {"$lt": current_date}})
    with open(os.path.join(os.getcwd(), "backup.txt"), "a+",
              encoding="utf-8") as f:
        tmp = []
        for x in to_delete:
            del x['_id']
            tmp.append(x)
        f.write(json.dumps(tmp, ensure_ascii=False))
        f.close()

    blocked.delete_many({"time.observation": {"$lt": current_date}})
    n_blocked.delete_many({"time.observation": {"$lt": current_date}})
    warned.delete_many({"time.observation": {"$lt": current_date}})
    n_warned.delete_many({"time.observation": {"$lt": current_date}})
    feeds.delete_many(
        {"time.observation": {
            "$lt": parser.parse(current_date).isoformat()
        }})
    lock.release()
コード例 #4
0
ファイル: database.py プロジェクト: reiosantos/tip-api
def update_last_login(email):
    users = get_mongodb_connection(MONGO_USER_COLLECTION)
    return users.find_one_and_update(
        {"email": email}, {"$set": {
            "last_login": make_date_time()
        }},
        upsert=True)
コード例 #5
0
ファイル: database.py プロジェクト: reiosantos/tip-api
def create_log(user, request, action, log_type):
    logs = get_logs()
    if not user:
        user = {"username": SYSTEM_NAME, "email": SYSTEM_EMAIL}
    if not request:
        request = namedtuple("request", ["path"])
        request.path = "/system"

    logs.insert({
        "username": user['username'],
        "email": user['email'],
        "accessUrl": request.path,
        "lastAccessTime": make_date_time(),
        "event": action,
        "type": log_type
    })
コード例 #6
0
ファイル: users.py プロジェクト: reiosantos/tip-api
def confirm_email(token):
    """
    :param token
    :rtype: object
    """
    if not token:
        return make_response(
            jsonify({
                "error": "Confirmation link is invalid or has expired.",
                "data": False
            }), 200)
    email = confirm_token(token)
    users = get_users()
    user = users.find_one({"email": email})
    if user:
        if user['confirmed'] is True:
            return make_response(
                jsonify({
                    "error": False,
                    "token": get_request_token(user['_id']),
                    "data": "Account already confirmed. Please login"
                }), 200)
        else:
            users.update_one({"email": email}, {
                "$set": {
                    "status": "active",
                    "confirmation_token": "",
                    "confirmed": True,
                    "confirmed_on": make_date_time()
                }
            })

            return make_response(
                jsonify({
                    "error": False,
                    "token": get_request_token(user['_id']),
                    "data": "You have confirmed your account! Thanks"
                }), 200)

    return make_response(
        jsonify({
            "error": "Confirmation link is invalid or has expired.",
            "data": False
        }), 200)
コード例 #7
0
def auto_unblocking():

    lock.acquire()

    unblocking_mins = minutes_before_ip_is_unblocked()
    blocked = get_blocked_by_ip()
    n_blocked = get_blocked_by_network()
    current_date = make_date_time(seconds_to_subtract=(unblocking_mins * 60))

    records = blocked.find({"block_date": {"$lte": current_date}})
    data = []
    if records:
        for record in records:
            data.append({record['source_ip'], record['source_network']})

    records_2 = n_blocked.find({"block_date": {"$lte": current_date}})
    if records_2:
        for record in records_2:
            data.append({record['source_ip'], record['source_network']})

    lock.release()

    unblock_all(ips=data)
コード例 #8
0
def block_all(ips=None, networks=None, by_country=None):
    """
    :param by_country: string eg 'US'
    :param ips :{as format: [{document}, {document}...]}
    :param networks :{as format: [{document}, {document}...]}
    :rtype: object
    """
    if ips is None:
        ips = []
    if networks is None:
        networks = []
    if not ips and not networks and not by_country:
        return

    lock.acquire()

    blocked_collection = get_blocked_by_ip()
    warning_collection = get_warned_by_ip()
    n_blocked_collection = get_blocked_by_network()
    n_warning_collection = get_warned_by_network()

    if ips:
        for threat in ips:
            ip = threat['source_ip'] or None
            network = threat['source_network'] or None
            if ip:
                if '_id' in threat:
                    del threat['_id']
                threat['block_date'] = make_date_time()
                threat['unblock_date'] = ""
                blocked_collection.find_one_and_update(
                    {
                        "source_ip": ip,
                        "source_network": network
                    }, {"$set": threat},
                    upsert=True)
                warning_collection.find_one_and_delete({
                    "source_ip":
                    ip,
                    "source_network":
                    network
                })

                threading.Thread(target=__do_the_actual_blocking,
                                 kwargs={
                                     'ip': ip
                                 },
                                 daemon=True).start()

    if networks:
        for threat in networks:
            ip = threat['source_ip']
            network = threat['source_network']
            if network:
                if '_id' in threat:
                    del threat['_id']
                threat['block_date'] = make_date_time()
                threat['unblock_date'] = ""
                n_blocked_collection.find_one_and_update(
                    {
                        "source_ip": ip,
                        "source_network": network
                    }, {"$set": threat},
                    upsert=True)
                n_warning_collection.find_one_and_delete({
                    "source_ip":
                    ip,
                    "source_network":
                    network
                })

                threading.Thread(target=__do_the_actual_blocking,
                                 kwargs={
                                     'network': network
                                 },
                                 daemon=True).start()

    if by_country:
        records = blocked_collection.find(
            {"source_geolocation_cc": by_country})
        if not records:
            records_2 = warning_collection.find(
                {"source_geolocation_cc": by_country})
            if records_2:
                for rec in records_2:
                    if '_id' in rec:
                        del rec['_id']
                    rec['block_date'] = make_date_time()
                    rec['unblock_date'] = ""
                    blocked_collection.insert_one(rec)

                    threading.Thread(target=__do_the_actual_blocking,
                                     kwargs={
                                         'ip': rec['source_ip']
                                     },
                                     daemon=True).start()

                warning_collection.delete_many(
                    {"source_geolocation_cc": by_country})

        records_1 = n_blocked_collection.find(
            {"source_geolocation_cc": by_country})
        if not records_1:
            records_2 = n_warning_collection.find(
                {"source_geolocation_cc": by_country})
            if records_2:
                for rec in records_2:
                    if '_id' in rec:
                        del rec['_id']
                    rec['block_date'] = make_date_time()
                    rec['unblock_date'] = ""
                    n_blocked_collection.insert_one(rec)

                    threading.Thread(target=__do_the_actual_blocking,
                                     kwargs={
                                         'network': rec['source_network']
                                     },
                                     daemon=True).start()

                n_warning_collection.delete_many(
                    {"source_geolocation_cc": by_country})

    lock.release()
コード例 #9
0
def unblock_all(ips=None, by_country=None):
    """
    :param by_country: country name/geolocation to unblock eg 'US'
    :param ips :{as format: [{source_ip, source_network}, ...]}
    :rtype: object
    """
    if not ips and not by_country:
        return

    lock.acquire()

    blocked_collection = get_blocked_by_ip()
    warning_collection = get_warned_by_ip()
    n_blocked_collection = get_blocked_by_network()
    n_warning_collection = get_warned_by_network()
    if ips:
        for ip in ips:
            i_p = ip['source_ip']
            net = ip['source_network']
            record = blocked_collection.find_one_and_delete({
                "source_ip":
                i_p,
                "source_network":
                net
            })
            if record:
                if '_id' in record:
                    del record['_id']
                record['block_date'] = ""
                record['unblock_date'] = make_date_time()
                warning_collection.find_one_and_update({"source_ip": i_p},
                                                       {"$set": record},
                                                       upsert=True)

                threading.Thread(target=__do_the_actual_unblocking,
                                 kwargs={
                                     'ip': i_p
                                 },
                                 daemon=True).start()
            else:
                record = n_blocked_collection.find_one_and_delete({
                    "source_ip":
                    i_p,
                    "source_network":
                    net
                })
                if record:
                    if '_id' in record:
                        del record['_id']
                    record['block_date'] = ""
                    record['unblock_date'] = make_date_time()
                    n_warning_collection.find_one_and_update(
                        {"source_network": net}, {"$set": record}, upsert=True)

                    threading.Thread(target=__do_the_actual_unblocking,
                                     kwargs={
                                         'network': net
                                     },
                                     daemon=True).start()

    if by_country:
        records = blocked_collection.find(
            {"source_geolocation_cc": by_country})
        if records:
            for rec in records:
                if '_id' in rec:
                    del rec['_id']
                rec['block_date'] = ""
                rec['unblock_date'] = make_date_time()
                warning_collection.insert_one(rec)

                threading.Thread(target=__do_the_actual_unblocking,
                                 kwargs={
                                     'ip': rec['source_ip']
                                 },
                                 daemon=True).start()

            blocked_collection.delete_many(
                {"source_geolocation_cc": by_country})

        records_1 = n_blocked_collection.find(
            {"source_geolocation_cc": by_country})
        if records_1:
            for rec in records_1:
                if '_id' in rec:
                    del rec['_id']
                rec['block_date'] = ""
                rec['unblock_date'] = make_date_time()
                n_warning_collection.insert_one(rec)

                threading.Thread(target=__do_the_actual_unblocking,
                                 kwargs={
                                     'network': rec['source_network']
                                 },
                                 daemon=True).start()

            n_blocked_collection.delete_many(
                {"source_geolocation_cc": by_country})

    lock.release()
コード例 #10
0
ファイル: authenticate.py プロジェクト: reiosantos/tip-api
def login():
    if not request.is_json or not (request.json.keys()
                                   & {"username", "password"}):
        return make_response(
            jsonify({
                "error": 'request is missing information',
                "data": False
            }), 200)

    username = request.json['username']
    password = request.json['password']
    if not username or not password:
        return make_response(
            jsonify({
                "error": 'required fields are not provided',
                "data": False
            }), 200)

    try:
        users = get_users()
        user = users.find_one(
            {"$or": [{
                "username": username
            }, {
                "email": username
            }]})
        if not user:
            return make_response(
                jsonify({
                    "error": 'Wrong username',
                    "data": False
                }), 200)

        if not verify_password(password, user['password']):
            return make_response(
                jsonify({
                    "error": 'Invalid user credentials',
                    "data": False
                }))

        if 'status' not in user.keys() or not user['status'] == "active":
            return make_response(
                jsonify({
                    "error": 'Access denied. User was deactivated.',
                    "data": False
                }), 200)

        user['id'] = user['_id']
        del user['_id']
        del user['password']

        if user_has_session(user['id']):
            if is_session_active(user_id=user['id']):
                return make_response(
                    jsonify({
                        "error": False,
                        "data": "already logged in",
                        "token": get_request_token(user['id']),
                        "user": json.dumps(user, cls=JSONEncoder)
                    }), 200)

            return session_expired()

        session['username'] = user['username']
        session['email'] = user['email']
        session['is_logged_in'] = True
        session['user_id'] = user['id']
        session['token'] = generate_token()
        session['expiration'] = make_date_time(SESSION_LIFETIME)

        update_last_login(user['email'])

        create_log(user, request, "Logged in", LOG_USER_TYPE)

    except IndexError:
        return make_response(jsonify({
            "error": 'No data found',
            "data": False
        }))
    return make_response(
        jsonify({
            "error": False,
            "token": session["token"],
            "data": json.dumps(user, cls=JSONEncoder)
        }))