Exemple #1
0
def documets():
    user = check_auth(request.headers, __name__)
    if user != True:
        return user
    user = authorize.get(request.headers.get('UserToken'))
    try:
        database = Database(config)
    except TypeError:
        return jsonify({"message": "Нет подключения к БД"})

    result = {}

    if request.method == "GET":
        pk = str(crypto_file.generate_public_key()).split('\\n')
        result = {
            "document_type": {},
            "public_key": ''.join(i for i in pk[1:-1])
        }
        for row in database.select_data(
                "SELECT id, title FROM document_type;"):
            result["document_type"][row[0]] = row[1]

    elif request.method == "POST":
        json = request.get_json(silent=True)
        if not json:
            return jsonify({"message": "JSON не найден"}), 400
        fields = ["hash", "document_type_id", "photo"]
        for field in fields:
            if not json.get(field):
                return jsonify({"message": f"Поле {field} не найдено"}), 400

        hash_md5 = hashlib.md5()
        hash_md5.update(str(json.get("photo")).encode())

        if not hash_md5.hexdigest() == json.get("hash").lower():
            return jsonify({"message": f"hash не совпадает"}), 406

        query = "INSERT INTO {table}({fields}) VALUES ({values}, now())"

        values = {
            "table":
            sql.Identifier("public", "documents"),
            "fields":
            sql.SQL(",").join(
                sql.Identifier(i) for i in
                ["hash", "user_id", "document_type_id", "photo", "dt_upload"]),
            "values":
            sql.SQL(",").join(
                sql.Literal(i) for i in [
                    json.get("hash"),
                    user.get_id(),
                    json.get("document_type_id"),
                    json.get("photo"),
                ])
        }

        result = database.insert_data(sql.SQL(query).format(**values))

    database.close()
    return jsonify(result)
Exemple #2
0
def get_password():
    try:
        database = Database(config)
    except TypeError:
        return jsonify({"message": "Нет подключения к БД"})

    result = {}
    if not request.get_json(silent=True):
        return jsonify({"message": "JSON не найден"}), 400

    number_phone = request.get_json(silent=True).get("number_phone")
    if not number_phone:
        return jsonify({"error": "Телефон не найден"}), 404

    isFind = database.select_data(
        sql.SQL("SELECT id FROM users WHERE number_phone={number_phone}").
        format(number_phone=sql.Literal(number_phone)))

    if not isFind:
        isFind = create_user(database, number_phone)

    if isFind:
        password = generate_password()
        update_password(database, isFind[0],
                        generate_password_hash(password, method='sha256'))
        send_password(password, number_phone)
        update_connection_log(database, isFind[0], request.remote_addr)

    database.close()
    return "Ok"
Exemple #3
0
def get_status_code(isCall=False):
    if not isCall:
        user = check_auth(request.headers, __name__)
        if user != True:
            return user
        user = authorize.get(request.headers.get('UserToken'))
    try:
        database = Database(config)
    except TypeError:
        return jsonify({"message": "Нет подключения к БД"})

    result = {}

    for row in database.select_data("SELECT id, title FROM status_code;"):
        result[row[0]] = row[1]

    database.close()
    return jsonify(result)
def my_documents_processing():
    user = check_auth(request.headers, __name__)
    if user != True:
        return user
    user = authorize.get(request.headers.get('UserToken'))
    try:
        database = Database(config)
    except TypeError:
        return jsonify({"message": "Нет подключения к БД"})

    result = []

    query = """
    SELECT 
        doc.id,
        u.lastname,
        u.firstname,
        u.patronymic,
        doc.dt_upload,
		dt.title,
        sc.title
    FROM documents doc
    LEFT JOIN document_processing dp ON dp.document_id = doc.id
    LEFT JOIN users u ON u.id = doc.user_id
	LEFT JOIN document_type dt ON dt.id = doc.document_type_id
    LEFT JOIN status_code sc ON sc.id = dp.status_code_id
    WHERE dp.manager_id={};""".format(user.get_id())

    for row in database.select_data(query):
        result.append({
            "document_id": row[0],
            "lastname": row[1],
            "firstname": row[2],
            "patronymic": row[3],
            "dt_upload": row[4],
            "document_type": row[5],
            "status_code": row[6]
        })

    database.close()
    return jsonify(result)
def change_status():
    user = check_auth(request.headers, __name__)
    if user != True:
        return user
    user = authorize.get(request.headers.get('UserToken'))
    try:
        database = Database(config)
    except TypeError:
        return jsonify({"message": "Нет подключения к БД"})

    result = {}

    if request.method == 'GET':
        return get_status_code(True)
    elif request.method == 'POST':
        json = request.get_json(silent=True)
        if not json:
            return jsonify({"message": "JSON не найден"}), 400

        fields = ["document_id", "status_code_id"]
        for field in fields:
            if not json.get(field):
                return jsonify({"message": f"Поле {field} не найдено"}), 400

        query = None
        values = None
        isManager = database.select_data(
            sql.SQL(
                "SELECT manager_id FROM document_processing WHERE document_id={document_id}"
            ).format(document_id=sql.Literal(json.get("document_id"))))
        if isManager:
            isManager = isManager[0][0]

        if isManager == user.get_id() and isManager:
            query = "UPDATE {table} SET {fields}={values} WHERE document_id={document_id}"

            values = {
                "table":
                sql.Identifier("public", "document_processing"),
                "fields":
                sql.SQL(",").join(
                    sql.Identifier(i) for i in ["status_code_id"]),
                "values":
                sql.SQL(",").join(
                    sql.Literal(i) for i in [json.get("status_code_id")]),
                "document_id":
                sql.Literal(json.get("document_id"))
            }
        elif isManager != user.get_id() and isManager:
            return jsonify({"message": f"Документ не найден"})
        else:
            query = "INSERT INTO {table}({fields}) VALUES({values})"

            values = {
                "table":
                sql.Identifier("public", "document_processing"),
                "fields":
                sql.SQL(",").join(
                    sql.Identifier(i)
                    for i in ["document_id", "status_code_id", "manager_id"]),
                "values":
                sql.SQL(",").join(
                    sql.Literal(i) for i in [
                        json.get("document_id"),
                        json.get("status_code_id"),
                        user.get_id()
                    ])
            }

        result = database.insert_data(sql.SQL(query).format(**values))

    database.close()
    return jsonify(result)
Exemple #6
0
    [makedirs(name=dirname(d), exist_ok=True) for d in makePaths if d]

    if not app.config.get("DEBUG", False):
        logLevel = logging.INFO
    else:
        logLevel = logging.DEBUG
    logging.basicConfig(filename=app.config["FLASK_LOGGING_FILE"],
                        level=logLevel)

    app.wsgi_app = ReverseProxied(app.wsgi_app)

    from app import api
    from app import swagger

    encrypter.setKeyFile(app.config["ENCRYPTION_KEY_FILE"])

    db.start(app.config["SQLALCHEMY_DATABASE_URI"])
    db.initDB()
    db.updateServiceJobs()
    db.updateProjectJobs()
    db.updateExecutions()

    scheduler.start(maxWorkers=app.config["JOBS_MAX_CONCURRENT_WORKERS"])

except KeyboardInterrupt:
    print("Captured Ctrl+C Interrupt")
    db.close()
except Exception as e:
    raise (e)
finally:
    db.close()