Beispiel #1
0
def update_email():
    """
    Update email data
    :return:
    """
    params = {
        '_id': FieldString(),
        'email': FieldString(),
        'password': FieldString(),
        'recovery_email': FieldString(),
        'date': FieldString()
    }

    try:
        json_data = parse_req(params)
        _id = json_data.get('_id')
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    email = client.db.email.find_one({'_id': ObjectId(_id)})
    if email is None:
        return send_error(message='Not found email')

    keys = ('email', 'password', 'recovery_email', 'date')

    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            email[k] = v

    client.db.email.update({'_id': ObjectId(_id)}, email)
    return send_result(message='Update email successfully')
Beispiel #2
0
def create_strategy():
    """
    Create email
    :return:
    """
    params = {
        'name': FieldString(),
        'issue': FieldString(),
        'sub_issue': FieldString(),
        'note': FieldString()
    }

    try:
        json_data = parse_req(params)
        new_name = json_data.get('name').strip().lower()
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    strategy = client.db.strategy.find_one({'email': new_name})
    if strategy is not None:
        return send_error(message='Duplicate strategy')

    keys = ('name', 'issue', 'sub_issue', 'note')

    strategy = dict()
    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            strategy[k] = v

    strategy['create_date'] = int(time.time())
    client.db.strategy.insert_one(strategy)
    return send_result(message='Tạo chiến dịch thành công.')
Beispiel #3
0
def bookings_by_year():
    """
        Returns:

        Examples::

    """
    year = request.args.get('year', 2020, type=int)
    results = []
    for i in range(1, 13):
        begin_month = begin_day_of_month(i, year)
        end_month = last_day_of_month(i, year)
        query = {
            "$and": [{
                "is_cancel": 0
            }, {
                "date_check_in": {
                    "$gte": begin_month
                }
            }, {
                "date_check_in": {
                    "$lte": end_month
                }
            }]
        }
        bookings = list(client.db.bookings.find(query))
        n = len(bookings)
        total = 0
        for b in bookings:
            total += b["total"]
        item = {"month": i, "number_of_reservations": n, "total_income": total}
        results.append(item)

    return send_result(data=results)
def post():
    params = {'name': FieldString(requirement=True)}

    try:
        json_data = parse_req(params)
        # Check valid params
        validate(instance=json_data, schema=schema_group)

        name = json_data.get('name', None)
    except Exception as ex:
        return send_error(message="Parameters error:" + str(ex))

    row = Group.query.filter_by(name=name).first()
    if row is not None:
        return send_error(message='The group name has existed!')

    create_date = get_datetime_now_s()
    _id = str(uuid.uuid1())

    new_group = Group(id=_id, name=name, create_date=create_date)
    try:
        db.session.add(new_group)
        db.session.commit()
    except Exception as ex:
        return send_error(message=str(ex))

    data = {'name': name}

    return send_result(data=data, message="Create the group successfully!")
Beispiel #5
0
def create_email():
    """
    Create email
    :return:
    """
    params = {
        'email': fields.Email(),
        'password': FieldString(),
        'recovery_email': fields.Email(),
        'date': FieldString()
    }

    try:
        json_data = parse_req(params)
        new_email = json_data.get('email').strip().lower()
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    email = client.db.email.find_one({'email': new_email})
    if email is not None:
        return send_error(message='Duplicate email')

    keys = ('email', 'password', 'recovery_email', 'date')

    email = dict()
    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            email[k] = v

    email['create_date'] = int(time.time())
    email['status'] = True
    client.db.email.insert_one(email)
    return send_result(message='Create email successfully')
Beispiel #6
0
def get_all_page_search():
    text_search = request.args.get('text_search', '')
    page_size = request.args.get('page_size', '25')
    page_number = request.args.get('page_number', '0')
    skips = int(page_size) * int(page_number)
    '''Give list after filtering'''
    query = \
        {'$and': [
            {'status': USER_ACTIVATED},
            {'$or': [
                {'email': {'$regex': text_search, '$options': "$i"}},
                {'MaNV': {'$regex': text_search, '$options': "$i"}},
                {'full_name': {'$regex': text_search, '$options': "$i"}}
            ]}
        ]}
    users = client.db.user.find(query).skip(skips).limit(int(page_size))
    '''end list'''
    list_user = list(users)
    '''Make a request'''

    for i in list_user:
        if int(i['status']) == USER_ACTIVATED:
            i['status_name'] = STATUS_USER[USER_ACTIVATED]
        if int(i['status']) == USER_DEACTIVATED:
            i['status_name'] = STATUS_USER[USER_DEACTIVATED]
    '''end request'''
    totals = client.db.user.find().count()
    data = {'totals': totals, 'results': list_user}
    return send_result(data=data)
Beispiel #7
0
def get_users():
    """
    Using for get all data of user
    :return:
    """
    try:
        page = int(request.args.get('page'))
        page_size = int(request.args.get('size'))
        search = request.args.get('search', '')
    except Exception as ex:
        return send_error(message='Json parse error')

    query = dict()
    if search and search != '':
        query['username'] = {"$regex": search}

    data = client.db.user.find(query).skip(page_size * page).limit(page_size)
    totals = client.db.user.count({})
    data = list(data)
    for item in data:
        item['_id'] = str(item['_id'])
        del item['password']

    return_data = dict(rows=data, totals=totals)
    return send_result(data=return_data)
Beispiel #8
0
def update_user():
    """
    Update user data
    :return:
    """
    params = {
        '_id': FieldString(),
        'address': FieldString(),
        'phone': FieldString(),
        'fullname': FieldString(),
        'role': FieldString(),
    }

    try:
        json_data = parse_req(params)
        _id = json_data.get('_id')
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    user = client.db.user.find_one({'_id': ObjectId(_id)})
    if user is None:
        return send_error(message='Not found user')

    keys = ('address', 'phone', 'fullname', 'role')

    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            user[k] = v

    client.db.user.update({'_id': ObjectId(_id)}, user)
    return send_result(message='Update user successfully')
Beispiel #9
0
def predictions():
    """ This api predict price of a room.

        Returns:

        Examples::

    """
    _type = request.args.get('type', "linear")
    try:
        json_data = request.get_json()
        # Check valid params
        validate(instance=json_data, schema=feature_validator)
    except Exception as ex:
        return send_error(message=str(ex))

    json_data["city_id"] = float(json_data["city_id"])
    json_data["property_type_id"] = float(json_data["property_type_id"])

    x = np.array([[
        json_data["acreage"], json_data["bed_type"],
        json_data["distance_from_center"], json_data["is_near_beach"],
        json_data["rank"], json_data["meal"], json_data["city_id"],
        json_data["property_type_id"]
    ]])

    # standardized data
    x = scaler_x.transform(x)

    price = linear.predict(x)[0]

    price = scaler_y.revert(price)
    return send_result(data=round(price, 2))
Beispiel #10
0
def update_password():
    """
    Update user password
    :return:
    """
    params = {
        '_id': FieldString(),
        'password': FieldString(),
    }

    try:
        json_data = parse_req(params)
        _id = json_data.get('_id')
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    user = client.db.user.find_one({'_id': ObjectId(_id)})
    if user is None:
        return send_error(message='Không tìm thấy người dùng, tải lại trang.')

    if user['username'] != 'Administrator':
        return send_error(
            message='Bạn không thể đổi mật khẩu, chỉ admin mới có quyền đổi.')

    client.db.user.update({'_id': ObjectId(_id)}, user)
    return send_result(message='Thay đổi mật khẩu thành công.')
def get():
    try:
        setting = SecurityPolicy.query.first()
    except Exception as ex:
        return send_error(message=str(ex))
    results = security_policy_schema.dump(setting).data
    return send_result(data=results)
def update_multiple():
    params = {
        'login_failed_attempts': fields.Number(),
        'logout_after_inactivate': fields.Number(),
        'password_expiration': fields.Number(),
        'password_password_min_length': fields.Number(),
        'password_min_length': fields.Number(),
        'password_include_symbol': fields.Bool(),
        'password_include_number': fields.Bool(),
        'password_include_lower_case': fields.Bool(),
        'password_include_upper_case': fields.Bool(),
    }
    try:
        json_data = parse_req(params)
        # Check valid params
        validate(instance=json_data, schema=schema_security_policy)

        login_failed_attempts = json_data.get('login_failed_attempts', None)
        logout_after_inactivate = json_data.get('logout_after_inactivate', None)
        password_expiration = json_data.get('password_expiration', None)
        password_min_length = json_data.get('password_min_length', None)
        password_include_symbol = json_data.get('password_include_symbol', None)
        password_include_number = json_data.get('password_include_number', None)
        password_include_lower_case = json_data.get('password_include_lower_case', None)
        password_include_upper_case = json_data.get('password_include_upper_case', None)

    except Exception as ex:
        return send_error(message=str(ex))

    modified_by = get_jwt_identity()
    modified_date = get_datetime_now_s()

    try:
        db.session.query(SecurityPolicy).update(
            {SecurityPolicy.login_failed_attempts: login_failed_attempts,
             SecurityPolicy.logout_after_inactivate: logout_after_inactivate,
             SecurityPolicy.password_expiration: password_expiration,
             SecurityPolicy.password_min_length: password_min_length,
             SecurityPolicy.password_include_symbol: password_include_symbol,
             SecurityPolicy.password_include_number: password_include_number,
             SecurityPolicy.password_include_lower_case: password_include_lower_case,
             SecurityPolicy.password_include_upper_case: password_include_upper_case,
             SecurityPolicy.modified_by: modified_by, SecurityPolicy.modified_date: modified_date},
            synchronize_session=False)
        db.session.commit()
    except Exception as ex:
        return send_error(message=str(ex))

    data = {
        'login_failed_attempts': login_failed_attempts,
        'logout_after_inactivate': logout_after_inactivate,
        'password_expiration': password_expiration,
        'password_min_length': password_min_length,
        'password_include_symbol': password_include_symbol,
        'password_include_number': password_include_number,
        'password_include_lower_case': password_include_lower_case,
        'password_include_upper_case': password_include_upper_case,
    }

    return send_result(data=data, message="Update security policy successfully!")
Beispiel #13
0
def refresh():
    """This api use for refresh expire time of the access token. Please inject the refresh token in Authorization header

    Requests Body:

        refresh_token: string,require
        The refresh token return in the login API

    Returns:

        access_token: string
        A new access_token

    Examples::

    """

    current_user_id = get_jwt_identity()
    access_token = create_access_token(identity=current_user_id, expires_delta=ACCESS_EXPIRES)

    # Store the tokens in our store with a status of not currently revoked.
    add_token_to_database(access_token, current_user_id)

    ret = {
        'access_token': access_token
    }
    return send_result(data=ret)
Beispiel #14
0
def update_info():
    """ This is api for all user edit their profile.

        Request Body:

        Returns:


        Examples::

    """

    try:
        json_data = request.get_json()
        # Check valid params
        validate(instance=json_data, schema=user_validator)
    except Exception as ex:
        return send_error(message=str(ex))

    keys = ["name", "gender", "phone", "email"]

    data = {}
    for key in keys:
        if key in json_data:
            data[key] = json_data.get(key)
    new_values = {
        "$set": data
    }

    try:
        client.db.users.update_many({"_id": get_jwt_identity()}, new_values)
    except Exception as ex:
        return send_error(message="Database error: " + str(ex))

    return send_result(data=data, message="Update user successfully!")
Beispiel #15
0
def update_strategy():
    """
    Update email data
    :return:
    """
    params = {
        '_id': FieldString(),
        'name': FieldString(),
        'issue': FieldString(),
        'sub_issue': FieldString(),
        'note': FieldString()
    }

    try:
        json_data = parse_req(params)
        _id = json_data.get('_id')
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    strategy = client.db.strategy.find_one({'_id': ObjectId(_id)})
    if strategy is None:
        return send_error(message='Not found')

    keys = ('name', 'issue', 'sub_issue', 'note')

    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            strategy[k] = v

    client.db.strategy.update({'_id': ObjectId(_id)}, strategy)
    return send_result(message='Cập nhật chiến dịch thành công.')
Beispiel #16
0
def post():
    params = {
        'name': FieldString(requirement=True),
        'descriptions': FieldString()
    }

    try:
        json_data = parse_req(params)
        # Check regex params
        validate(instance=json_data, schema=schema_permission)

        name = json_data.get('name', None)
        descriptions = json_data.get('descriptions', None)
    except Exception as ex:
        return send_error(message="Parameters error:" + str(ex))

    row = PermissionDetail.query.filter_by(name=name).first()
    if row is not None:
        return send_error(message='The permission name has existed!')

    create_date = get_datetime_now_s()
    _id = str(uuid.uuid1())

    new_values = PermissionDetail(id=_id,
                                  descriptions=descriptions,
                                  name=name,
                                  create_date=create_date)
    try:
        db.session.add(new_values)
        db.session.commit()
    except Exception as ex:
        return send_error(message=str(ex))

    return send_result(message="Create permission successfully!")
Beispiel #17
0
def get_permission_by_id(permission_id):
    try:
        row = PermissionDetail.query.get(permission_id)
    except Exception as ex:
        return send_error(message=str(ex))
    rs = permission_schema.dump(row).data
    return send_result(data=rs)
Beispiel #18
0
def update_channel():
    """
    Update email data
    :return:
    """
    params = {
        '_id': FieldString(),
        'name': FieldString(),
        'channel': FieldString(),
        'strategy': FieldString(),
        'status': FieldString(),
    }

    try:
        json_data = parse_req(params)
        _id = json_data.get('_id')
    except Exception as ex:
        return send_error(message='Json parser error', code=442)

    channel = client.db.channel.find_one({'_id': ObjectId(_id)})
    if channel is None:
        return send_error(message='Not found')

    keys = ('name', 'channel', 'strategy', 'status')

    for k in keys:
        v = json_data.get(k, None)
        if v is not None or v != '':
            channel[k] = v

    client.db.channel.update({'_id': ObjectId(_id)}, channel)
    return send_result(message='Cập nhật kênh thành công.')
Beispiel #19
0
def available_rooms_by_date():
    """ This api get information of a booking.

        Returns:

        Examples::

    """

    datetime = request.args.get('datetime', get_timestamp_now(), type=int)
    all_rooms = client.db.rooms.find({})
    query = {
        "$and": [{
            "date_check_out": {
                "$gte": datetime
            }
        }, {
            "date_check_in": {
                "$lte": datetime
            }
        }]
    }
    bookings = client.db.bookings.find(query)
    booking_rooms_id = [b["room_id"] for b in bookings]
    available_rooms = [
        room for room in all_rooms if room["_id"] not in booking_rooms_id
    ]
    return send_result(data=available_rooms)
Beispiel #20
0
def get_all():
    try:
        list_items = PermissionDetail.query.all()
    except Exception as ex:
        return send_error(message=str(ex))
    results = permissions_schema.dump(list_items).data
    return send_result(data=results)
Beispiel #21
0
def get_data():
    """
    get data questions
    url: /api/questions
    :return: data questions
    """
    try:
        list_data = []
        conn = sqlite3.connect('./test.db')
        c = conn.execute('SELECT * FROM qa;')
        data = c.fetchall()
        for item in data:
            list_data.append({
                'id': item[0],
                'questions': item[1],
                'a': item[2],
                'b': item[3],
                'c': item[4],
                'd': item[5],
                'description': item[7]
            })
    except Exception as e:
        return send_error(message='DB error')
    finally:
        conn.close()
    return send_result(data=list_data)
Beispiel #22
0
def check_answer():
    """
    check answer
    url: /api/questions
    :return: data answer
    """

    params = {'answer': fields.List(fields.Dict())}
    try:
        json_data = parse_req(params)
        data = json_data.get('answer')
    except Exception as ex:
        return send_error(message='{}'.format(str(ex)), code=442)

    try:
        list_data = []
        conn = sqlite3.connect('./test.db')
        conn.row_factory = lambda c, r: dict(
            zip([col[0] for col in c.description], r))
        c = conn.execute('SELECT qa.id, qa.answer FROM qa;')
        list_answer = c.fetchall()
        for item in list_answer:
            a = False
            for dic in data:
                if dic['id'] == item['id']:
                    if dic['value'] == int(item['answer']):
                        a = True
                    break
            list_data.append({'id': item['id'], 'answer': a})
    except Exception as e:
        return send_error(message='DB error')
    finally:
        conn.close()
    return send_result(data=list_data)
Beispiel #23
0
def create_booking():
    """ This is api for the booking management create booking.

        Request Body:

        Returns:

        Examples::
    """

    try:
        json_data = request.get_json()
        # Check valid params
        validate(instance=json_data, schema=booking_validator)
    except Exception as ex:
        return send_error(message=str(ex))

    room_id = json_data.get("room_id", None)
    date_check_in = json_data.get("date_check_in", 0)
    date_check_out = json_data.get("date_check_out", 0)

    room = client.db.rooms.find_one({"_id": room_id})
    if not room:
        return send_error(message="Not found the room")

    if date_check_in >= date_check_out:
        return send_error(message="Date check in and date check out invalid")

    query = {"$and": [
        {"room_id": room_id},
        {"$nor": [
            {"date_check_out": {"$lt": date_check_in}},
            {"date_check_in": {"$gt": date_check_out}}
        ]}
    ]}
    booking = client.db.bookings.find_one(query)
    if booking:
        return send_error(message="The reservation conflicted")

    if not room:
        return send_error(message="Not found the room")

    keys = ["room_id", "date_check_in", "date_check_out", "service", "note", "total"]
    booking_id = str(ObjectId())
    new_booking = {
        "_id": booking_id,
        "user_id": get_jwt_identity(),
        "date_reservation": get_timestamp_now()
    }

    for key in keys:
        if key in json_data:
            new_booking[key] = json_data.get(key)

    try:
        client.db.bookings.insert_one(new_booking)
    except Exception as ex:
        return send_error(message="Insert to database error: " + str(ex))

    return send_result(data=new_booking, message="Create booking successfully!")
Beispiel #24
0
def get_channel():
    """
    Using for get all data of emails
    :return:
    """
    try:
        page = int(request.args.get('page', 0))
        page_size = int(request.args.get('size', 10))
        search = request.args.get('search', '')
    except Exception as ex:
        return send_error(message='Parser params error')
    query = dict()
    if search and search != '':
        query['name'] = {"$regex": search}

    data = client.db.channel.find(query).skip(page_size *
                                              page).limit(page_size)
    totals = client.db.channel.count(query)
    data = list(data)
    for item in data:
        item['_id'] = str(item['_id'])
        strategy = client.db.strategy.find_one(
            {'_id': ObjectId(item['strategy'])})
        if strategy is not None:
            strategy['_id'] = str(strategy['_id'])
            item['strategy'] = strategy

    return_data = dict(rows=data, totals=totals)
    return send_result(data=return_data)
def get_group_by_id(group_id):
    try:
        item = Group.query.get(group_id)
    except Exception as ex:
        return send_error(message=str(ex))

    group = user_group_schema.dump(item).data

    return send_result(data=group)
def get_all_groups():
    try:
        list_items = Group.query.all()
    except Exception as ex:
        return send_error(message="Get all error: " + str(ex))

    results = user_groups_schema.dump(list_items).data

    return send_result(data=results)
def logout():
    """
    Add token to blacklist
    :return:
    """
    jti = get_raw_jwt()['jti']
    revoked_store.set(jti, 'true', ACCESS_EXPIRES * 1.2)
    logout_user()

    return send_result(message='logout successfully')
Beispiel #28
0
def logout():
    """
    Add token to blacklist
    :return:
    """
    jti = get_raw_jwt()['jti']

    Tokens.revoke_token(jti)
    logger.info("Logout Successfully")
    return send_result(message='Logout Successfully')
Beispiel #29
0
def put():
    claims = get_jwt_claims()
    if not claims['is_admin']:
        return send_error(
            message="Bạn không đủ quyền để thực hiện thao tác này")

    user_id = request.args.get('user_id')
    user = client.db.user.find_one({'_id': user_id})
    if user is None:
        return send_error(message='Không tìm thấy người dùng.')

    params = {
        'user_name': FieldString(requirement=True),
        'password': FieldString(requirement=True),
        'email': FieldString(requirement=True),
        'full_name': FieldString(requirement=True),
        'group_role_id': fields.Number(),
        'status': fields.Number()
    }

    try:
        json_data = parse_req(params)
        full_name = json_data.get('full_name', None)
        email = json_data.get('email', None).lower()
        user_name = json_data.get('user_name', None)
        password = json_data.get('password', None)
        group_role_id = json_data.get('group_role_id', 0)
        status = json_data.get('status', 0)

    except Exception:
        return send_error(message='Lỗi dữ liệu đầu vào')
    '''Check '''
    if status == USER_ACTIVATED:
        status = USER_ACTIVATED
    elif status == USER_DEACTIVATED:
        status = USER_DEACTIVATED
    else:
        return send_error(message="Bạn chưa nhập trạng thái")
    '''End check'''
    _id = str(ObjectId())
    new_user = {
        '$set': {
            'full_name': full_name,
            'user_name': user_name,
            'password': hash_password(password),
            'email': email,
            'group_role_id': int(group_role_id),
            'status': int(status),
        }
    }
    try:
        client.db.user.update_one({'_id': user_id}, new_user)
    except Exception:
        return send_error(message='có lỗi ngoại lệ sảy ra')
    return send_result(message="Cập nhật thành công", data=user)
Beispiel #30
0
def get_strategies():
    """
    Using for get all data of emails
    :return:
    """
    data = client.db.strategy.find()
    data = list(data)
    for item in data:
        item['_id'] = str(item['_id'])

    return send_result(data=data)