Exemple #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')
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.')
Exemple #3
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.')
Exemple #4
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')
Exemple #5
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!")
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.')
Exemple #7
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.')
Exemple #8
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')
Exemple #9
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)
Exemple #10
0
def login():
    """
    :response: {"messages": "success"}
    """
    params = {'username': FieldString(), 'password': FieldString()}
    try:
        json_data = parse_req(params)
        username = json_data.get('username', None).strip()
        password = json_data.get('password')
    except Exception as ex:
        # logger_auth.error(ex.__str__())
        return send_error(message='json_parser_error')
    try:
        # log input fields
        logger_auth.info(f"INPUT api login: {json_data}")

        if len(username) > 50:
            # logger_auth.info("Username can be up to 50 characters")
            return send_error(message="Username can be up to 50 characters")

        if len(password) > 50:
            # logger_auth.info("Password can be up to 50 characters")
            return send_error(message="Password can be up to 50 characters")
        user = Users.query.filter_by(username=username).first()
        if user is None:
            return send_error(
                message='Invalid username or password. Please try again')

        # Check password
        if not check_password_hash(user.password_hash, password):
            return send_error(
                message='Invalid username or password. Please try again')

        access_token = create_access_token(identity=user.id,
                                           expires_delta=ACCESS_EXPIRES)
        refresh_token = create_refresh_token(identity=user.id,
                                             expires_delta=REFRESH_EXPIRES)
        Tokens.save_to_db(access_token)
        Tokens.save_to_db(refresh_token)
        data = {
            'access_token': access_token,
            'refresh_token': refresh_token,
            'username': user.username,
            'user_id': user.id
        }
        # logger_auth.info(data)
        return send_result(data=data, message='Logged in successfully!')
    except Exception as ex:
        # logger_auth.error(ex.__str__())
        return send_error(message='login failed')
Exemple #11
0
def login():
    """ This is controller of the login api

    Requests Body:

    Returns:

    Examples::

    """

    params = {
        'username': FieldString(),
        'password': FieldString()
    }
    try:
        json_data = parse_req(params)

        username = json_data.get('username', None).strip()
        password = json_data.get('password')
    except Exception as ex:
        logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex))
        return send_error(message='Invalid username or password.\nPlease try again')

    user = client.db.users.find_one({'username': username})
    if user is None:
        return send_error(message='Invalid username or password.\nPlease try again')

    if not check_password_hash(user["password_hash"], password):
        return send_error(message='Invalid username or password.\nPlease try again')

    access_token = create_access_token(identity=user["_id"], expires_delta=ACCESS_EXPIRES)
    refresh_token = create_refresh_token(identity=user["_id"], expires_delta=REFRESH_EXPIRES)

    # Store the tokens in our store with a status of not currently revoked.
    add_token_to_database(access_token, user["_id"])
    add_token_to_database(refresh_token, user["_id"])

    data = {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'username': user["username"],
        'is_admin': user["is_admin"],
        'user_id': user["_id"],
        'name': user["name"],
    }

    return send_result(data=data, message="Logged in successfully!")
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!")
Exemple #13
0
def put(permission_id):
    try:
        permission = PermissionDetail.query.get(permission_id)
    except Exception as ex:
        return send_error(message="Database error: " + str(ex))

    if permission is None:
        return send_error(message='Not found the permission to update!')

    params = {'name': FieldString(), 'descriptions': FieldString()}
    try:
        json_data = parse_req(params)
        # Check regex params
        validate(instance=json_data, schema=schema_permission)

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

    try:
        row = PermissionDetail.query.filter(
            PermissionDetail.name == name,
            PermissionDetail.id != permission_id).first()
    except Exception as ex:
        return send_error(message=str(ex))
    if row is not None:
        return send_error(message='The permission name has existed!')

    modified_by = get_jwt_identity()
    edit_date = get_datetime_now_s()

    try:
        if descriptions:
            permission.descriptions = descriptions
        if name:
            permission.name = name
        permission.modified_by = modified_by
        permission.edit_date = edit_date
        db.session.commit()
    except Exception as ex:
        return send_error(message=str(ex))

    return send_result(message="Update permission successfully!")
Exemple #14
0
def post():

    params = {
        'user_name': FieldString(requirement=True),
        'password': FieldString(requirement=True),
        'email': FieldString(requirement=True),
        'full_name': FieldString(requirement=True),
        'group_role_id': 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)

    except Exception:
        return send_error(message='Lỗi dữ liệu đầu vào')
    '''check conditions'''
    '''end check'''
    '''create MNV auto'''
    '''end create MNv'''
    _id = str(ObjectId())
    user = {
        '_id': _id,
        'full_name': full_name,
        'user_name': user_name,
        'password': hash_password(password),
        'email': email,
        'group_role_id': int(group_role_id),
        'status': USER_ACTIVATED,
        'MaNV': set_auto_MaNV()
    }
    try:
        client.db.user.insert_one(user)
    except Exception:
        return send_error(message='có lỗi ngoại lệ sảy ra')

    return send_result(message="Tạo user thành công ", data=user)
Exemple #15
0
def login():
    """
    :response: {"messages": "success"}
    """
    params = {'email': FieldString(), 'password': FieldString()}

    try:
        json_data = parse_req(params)
        email = json_data.get('email', None).lower()
        password = json_data.get('password')
    except Exception as ex:
        return send_error(message='json_parser_error')

    user = client.db.user.find_one({'email': email})
    if user is None:
        return send_error(message='Email không tồn tại')

    # if not check_password_hash(user['password'], password):
    #     return send_error(message='Bạn đã nhập sai mật khẩu vui lòng nhập lại')

    access_token = create_access_token(identity=user['_id'],
                                       expires_delta=ACCESS_EXPIRES)
    refresh_token = create_refresh_token(identity=user['_id'],
                                         expires_delta=REFRESH_EXPIRES)
    access_jti = get_jti(encoded_token=access_token)
    refresh_jti = get_jti(encoded_token=refresh_token)
    revoked_store.set(access_jti, 'false', ACCESS_EXPIRES * 1.2)
    revoked_store.set(refresh_jti, 'false', REFRESH_EXPIRES * 1.2)
    user_token = dict(_id=str(ObjectId()),
                      user_id=user['_id'],
                      access_jti=access_jti,
                      refresh_jti=refresh_jti)
    client.db.token.insert_one(user_token)
    return send_result(data={
        'access_token': access_token,
        'refresh_token': refresh_token,
        'email': user['email'],
        'full_name': user['full_name'],
    },
                       message='Đăng nhập thành công')
Exemple #16
0
def create_channel():
    """
    Create email
    :return:
    """
    params = {
        'name': FieldString(),
        'channel': FieldString(),
        'strategy': FieldString(),
        'status': 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)

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

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

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

    channel['create_date'] = int(time.time())
    channel['status'] = 'active'
    channel['reporting'] = False
    channel['count_success'] = 0
    channel['count_fail'] = 0
    client.db.channel.insert_one(channel)
    return send_result(message='Tạo kênh mới thành công.')
def put(group_id):
    try:
        group = Group.query.get(group_id)
    except Exception as ex:
        return send_error(message="Database error:" + str(ex))
    if group is None:
        return send_error(message='Not found group to update!')

    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))

    try:
        row = Group.query.filter(Group.name == name,
                                 Group.id != group_id).first()
    except Exception as ex:
        return send_error(message=str(ex))
    if row is not None:
        return send_error(message='The group name has existed!')

    modified_by = get_jwt_identity()
    modified_date = get_datetime_now_s()

    try:
        group.name = name
        group.modified_by = modified_by
        group.modified_date = modified_date
        db.session.commit()
    except Exception as ex:
        return send_error(message=str(ex))

    data = {'new name': name}

    return send_result(data=data, message="Update group successfully!")
Exemple #18
0
def predict():
    """predict text
    :return:
    """
    params = {'data': FieldString()}
    try:
        json_data = parse_req(params)
        data = json_data.get('data', None).lower()
    except Exception as ex:
        return send_error(message='json_parser_error')
    result = predicting(data)
    history = PredictHistory(
        data=data,
        label=None if 'score' not in result.keys() else result["label"],
        score=None if 'score' not in result.keys() else result["score"],
        description="Not in classes!"
        if 'score' not in result.keys() else "Predict successfully!")
    history.save_to_db()
    # db.session.commit()
    return send_result(data=result)
Exemple #19
0
def create_user():
    """
    Create user
    :return:
    """
    params = {
        'username': FieldString(),
        'password': FieldString(),
        'address': FieldString(),
        'phone': FieldString(),
        'fullname': FieldString(),
        'role': FieldString(),
    }

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

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

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

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

    user['password'] = generate_password_hash(password)
    user['create_date'] = int(time.time())
    client.db.user.insert_one(user)
    return send_result(message='Create user successfully')
def login():
    """ This is controller of the login api.

    Request Body:
        username: string, require
            The username of the user. Max length accepted is 50 and minimum length is 1

        password: string, require
            The password of the user wanted to log in. Max length accepted is 50 and minimum length is 1

    Returns:

        access_token: string
            your access token. you needed to save this to access to backend services. Please put
            access_token to Header Authorization: Bearer <accees_token>

        force_change_password: boolean
            When true. The user have force change password after login.

        group: string
            Current group of the user

        list_permissions: list[string,]
            Mapping action and resource user can access. For example create_user or get_users

        login_failed_attempts: number
            Number login failed of the current user.

        logout_after_inactivate: number
            Number in seconds. If user do not have any action in the period time. Use will be logged out

        refresh_token: string
            Token use to refresh expire time of the access token. Please put
            refresh_token to Header Authorization: Bearer <refresh_token>

    Examples::

        curl --location --request GET 'http://<sv_address>:5012/api/v1/users/4658df34-8630-11ea-b850-588a5a158009' --header 'Authorization: Bearer <refresh_token>'

    """
    params = {'username': FieldString(), 'password': FieldString()}

    try:
        json_data = parse_req(params)
        username = json_data.get('username', None).lower()
        password = json_data.get('password')
    except Exception as ex:
        return send_error(message='json_parser_error' + str(ex))

    row = User.query.filter_by(username=username).first()
    if row is None:
        return send_error(message='Username or password incorrect!')

    user = user_include_pass_schema.dump(row).data

    if not check_password_hash(user['password_hash'], password):
        return send_error(message='Username or password incorrect!')

    if not login_user(row):
        return send_error(message="User is not activate!")

    access_token = create_access_token(identity=user['id'],
                                       expires_delta=ACCESS_EXPIRES)
    refresh_token = create_refresh_token(identity=user['id'],
                                         expires_delta=REFRESH_EXPIRES)
    access_jti = get_jti(encoded_token=access_token)
    refresh_jti = get_jti(encoded_token=refresh_token)
    revoked_store.set(access_jti, 'false', ACCESS_EXPIRES * 1.2)
    revoked_store.set(refresh_jti, 'false', REFRESH_EXPIRES * 1.2)

    # get group name of this user
    try:
        group = Group.query.get(user['group_id'])
    except Exception as ex:
        return send_error(message="Database error:" + str(ex))

    group_json = user_group_schema.dump(group).data
    group_name = ''
    if group:
        group_name = group_json['name']

    try:
        setting = SecurityPolicy.query.first()
    except Exception as ex:
        return send_error(message=str(ex))
    security_policy = security_policy_schema.dump(setting).data
    """
    Find list permissions of current group
    """
    try:
        list_items = PermissionDetail.query.all()
    except Exception as ex:
        return send_error(message=str(ex))
    list_permissions = list_permissions_schema.dump(list_items).data

    data = {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'logout_after_inactivate': security_policy['logout_after_inactivate'],
        'login_failed_attempts': security_policy['login_failed_attempts'],
        'username': user['username'],
        'force_change_password': user['force_change_password'],
        'group': group_name,
        'list_permissions': list_permissions
    }

    return send_result(data=data, message='Logged in successfully!')
Exemple #21
0
def create_user():
    """ This is api for the user management registers user.

        Request Body:
            username: string, require
                The username of the user. Max length accepted is 50 and minimum length is 1.

            password: string, require
                The password of the user wanted to log in. Max length accepted is 50 and minimum length is 1.

        Returns:

            username: string
                username of newly registered user.

            group_id: string
                group id of this new user.

        Examples::

            curl --location --request POST 'http://<sv_address>:5013/api/v1/users' --header 'Authorization: Bearer <access_token>'
    """

    params = {
        'username': FieldString(requirement=True),
        'password': FieldString(requirement=True),
        'first_name': FieldString(requirement=True),
        'last_name': FieldString(requirement=True),
        'company': FieldString(),
        'address': FieldString(),
        'mobile': FieldString()
    }

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

        username = json_data.get('username', None).lower().strip()
        password = json_data.get('password', None)
        first_name = json_data.get('first_name', None)
        last_name = json_data.get('last_name', None)
        company = json_data.get('company', None)
        address = json_data.get('address', None)
        mobile = json_data.get('mobile', None)
    except Exception as ex:
        logger.error('{} Parameters error: '.format(
            datetime.datetime.utcnow().strftime('%Y-%b-%d %H:%M:%S')) +
                     str(ex))
        return send_error(message="Registers user fail!")

    # log input fields
    # logger.debug(f"INPUT api create user: {json_data}")

    user = Users.find_by_user_name(user_name=username)
    if user:
        return send_error(message="User exist")

    if is_password_contain_space(password):
        return send_error(message='Password cannot contain spaces')

    create_date = datetime.datetime.utcnow().timestamp()
    _id = str(uuid.uuid1())
    user = Users(id=_id,
                 username=username,
                 password_hash=hash_password(password),
                 force_change_password=False,
                 create_date=create_date,
                 modified_date=create_date,
                 is_active=True,
                 firstname=first_name,
                 lastname=last_name,
                 company=company,
                 address=address,
                 mobile=mobile,
                 modified_date_password=create_date)
    user.save_to_db()
    data = {
        'id': _id,
        'username': username,
        'first_name': first_name,
        'last_name': last_name,
        'create_date': create_date
    }
    return send_result(data=data, message="Registers user successfully!")