Example #1
0
def get_auth_token():
    """
    用户登录验证
    :return: json
    """
    usr = request.user
    roles = set()
    permissions = set()
    token_roles = usr.get('roles')

    for role in token_roles:
        roles.add(role.get('code'))
        for permission in role.get('permissions'):
            code = permission.get('code')
            permissions.add(code)

    data = {
        'id': usr.get('id'),
        'username': usr.get('account'),
        'roles': list(roles),
        'permissions': list(permissions),
        'level': usr.get('level')
    }
    access_token = create_access_token(identity=data)
    refresh_token = create_refresh_token(identity=data)
    data['access_token'] = access_token
    data['refresh_token'] = refresh_token
    data['user'] = usr
    return HttpHelper.normal_handler(data)
Example #2
0
def get_task_result(task_id):
    task = celery.AsyncResult(task_id)
    if task.state == 'PENDING':
        # job did not start yet
        response = {
            'state': task.state,
            'current': 0,
            'total': 1,
            'status': 'Pending...'
        }
    elif task.state != 'FAILURE':
        response = {
            'state': task.state,
            'current': task.info.get('current', 0),
            'total': task.info.get('total', 1),
            'status': task.info.get('status', '')
        }
        if 'result' in task.info:
            response['result'] = task.info['result']
    else:
        # something went wrong in the background job
        response = {
            'state': task.state,
            'current': 1,
            'total': 1,
            'status': str(task.info),  # this is the exception raised
        }
    return HttpHelper.normal_handler(response)
Example #3
0
def get_permission_by_id(permission_id):
    permissions = {}

    if permission_id:
        permissions = AuthPermission.get_by_status_or_404(permission_id)

    permissions_dict = model_to_dict(permissions, handle_relationship_flag=True)
    return HttpHelper.normal_handler(permissions_dict)
Example #4
0
def get_permission():
    permissions = {}
    jwt_data = get_jwt_identity()
    user_id = jwt_data.get('id')
    if user_id:
        from app.models.AuthRole import AuthRole
        permissions = AuthRole.get_permission_by_user_id(user_id)

    return HttpHelper.normal_handler(permissions)
Example #5
0
def refresh():
    """
    Refresh the token
    :return:
    """
    current_user = get_jwt_identity()
    token = create_access_token(identity=current_user)

    return HttpHelper.normal_handler({"access_token": token})
Example #6
0
def get_all_permission():
    query_data = g.json_data
    start, pagesize = HttpHelper.get_page_info()

    if query_data:
        paginated_obj = AuthPermission.get_pagination(start, pagesize, **query_data)
    else:
        paginated_obj = AuthPermission.get_pagination(start, pagesize)
    return HttpHelper.normal_handler(pagination_to_dict(paginated_obj))
Example #7
0
def disable_role(role_id):
    role_data = g.json_data
    if role_data.get('id') != role_id:
        raise APIException(ResultEnum.ROLE_INVALID_ID)

    role = AuthRole.get_by_status(role_id)
    try:
        role.toggle_disable()
        return HttpHelper.normal_handler(role)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
Example #8
0
def get_user(user_id):
    """
    获取用户信息
    :return: json
    """

    u = User.get_by_status(user_id)
    logger.debug(jsonpickle.encode(u, unpicklable=False))
    user_dict = u.as_dict(handle_relationship_flag=True)
    avatar_img = user_dict.get('avatar_img').get('file_url')
    user_dict['avatar_img'] = BASE_URL + avatar_img
    return HttpHelper.normal_handler(user_dict)
Example #9
0
def get_role(role_id):
    """
    获取Role详情信息
    :param role_id:
    :return:
    """
    role = AuthRole.get_by_status(role_id)
    if not role:
        return HttpHelper.error_handler(ResultEnum.NOT_FOUND_ERROR)

    return HttpHelper.normal_handler(
        model_to_dict(role, handle_relationship_flag=True))
Example #10
0
def get_user_roles(user_id):
    """
    获取用户信息
    :return: json
    """

    u = User.get_by_status_or_404(user_id)
    usr_dict = u.as_dict()
    usr_dict['roles'] = [role.as_dict() for role in u.roles]

    logger.debug(jsonpickle.encode(usr_dict, unpicklable=False))
    return HttpHelper.normal_handler(usr_dict)
Example #11
0
def disable_permission(permission_id):
    permission_data = g.json_data
    if permission_data.get('id') != permission_id:
        raise APIException(ResultEnum.PERMISSION_INVALID_ID)

    permission = AuthPermission.get_or_404(permission_id)
    try:
        permission.toggle_disable()
        return HttpHelper.normal_handler(permission)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
Example #12
0
def get_all_roles():
    """
    获取Role全部列表,因为内容不多,不进行分页展示
    :return:
    """
    query_data = g.json_data
    start, pagesize = HttpHelper.get_page_info()

    if query_data:
        paginated_obj = AuthRole.get_pagination(start, pagesize, **query_data)
    else:
        paginated_obj = AuthRole.get_pagination(start, pagesize)
    return HttpHelper.normal_handler(pagination_to_dict(paginated_obj))
Example #13
0
def register_client():
    reg_info = ClientRegisterValidator.validator(request.json)

    promise = {
        ClientTypeEnum.USER_EMAIL.code: __register_by_email,
        ClientTypeEnum.USER_MOBILE.code: __register_by_mobile,
        ClientTypeEnum.USER_MINA.code: __register_by_mina,
        ClientTypeEnum.USER_WECHAT.code: __register_by_wechat
    }

    reg_type = reg_info.get('clientType')
    client = promise[reg_type](reg_info.get('account'),
                               reg_info.get('password'))
    return HttpHelper.normal_handler(client)
Example #14
0
def get_all_permission_by_role_id(role_id):
    permissions = AuthPermission.get_by_parent_id(id=None)
    checked_permissions = AuthRolePermissions.get_by_role_id(role_id)
    checked_permission_ids = [
        checked_permission.permission_id
        for checked_permission in checked_permissions
    ]

    permissions_dict = get_permission_checked_dict([
        model_to_dict(permission, handle_relationship_flag=True)
        for permission in permissions
    ], checked_permission_ids)

    return HttpHelper.normal_handler(permissions_dict)
Example #15
0
def file_upload():
    """
    文件上传,支持单文件和多文件
    1、 单文件上传,body中必须以file指定文件
    2、 多文件上传,body中必须以files指定文件列表
    :return:  成功、错误 json文件
    """

    # 如果是通过file关键字进行的文件上传,即使多个也只处理最后一个
    if 'file' in request.files:

        file = request.files.get('file')
        if file:
            succ, data = process_single_file(file)
            if succ:
                return HttpHelper.normal_handler(data)
            else:
                return HttpHelper.error_handler(data)

    else:
        errors = {}
        success = {}
        files = request.files.getlist('files')

        # 不是file,也不是files参数,抛异常退出
        if not files:
            raise APIException(ResultEnum.FILE_UPLOAD_METHOD_ERROR)

        for file in files:
            succ, data = process_single_file(file)
            if succ:
                success[file.filename] = data
            else:
                errors[file.filename] = data.msg

        data = {'success': success, 'errors': errors}
        return HttpHelper.normal_handler(data)
Example #16
0
def get_users():
    """
    获取用户列表,分页返回
    :return: json
    """
    query_data = g.json_data

    start, pagesize = HttpHelper.get_page_info()

    if query_data:
        paginated_user = User.get_pagination_user(start, pagesize,
                                                  **query_data)
    else:
        paginated_user = User.get_pagination_user(start, pagesize)
    return HttpHelper.normal_handler(pagination_to_dict(paginated_user))
Example #17
0
def change_password(user_id):
    usr = User.get_by_status_or_404(user_id)

    password = g.json_data.get('password', None)
    if not password:
        raise APIException(ResultEnum.USER_OR_PASS_EMPTY_ERROR)

    usr.password = generate_password_hash(password)

    try:
        usr.update()
        return HttpHelper.normal_handler(usr)
    except Exception as e:
        logger.error(e)
        return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR)
Example #18
0
def bind_user_roles(user_id):
    json_data = g.json_data
    if user_id != json_data.get('user_id'):
        raise APIException(ResultEnum.USER_INVALID_ID)

    role_ids = json_data.get('roles')

    if not role_ids:
        raise APIException(ResultEnum.INVALID_PARAMETER)

    try:
        user = User.get_by_status_or_404(user_id)
        user.refresh_roles(role_ids)
        return HttpHelper.normal_handler()
    except Exception as e:
        logger.error(e)
        return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR)
Example #19
0
def bind_role_permissions(role_id):
    json_data = g.json_data
    if role_id != json_data.get('role_id'):
        raise APIException(ResultEnum.ROLE_INVALID_ID)

    permission_ids = json_data.get('permissions')

    if not permission_ids:
        raise APIException(ResultEnum.INVALID_PARAMETER)

    try:
        role = AuthRole.get_by_status_or_404(role_id)
        role.refresh_permissions(permission_ids)
        return HttpHelper.normal_handler()
    except Exception as e:
        logger.error(e)
        return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR, e.args)
Example #20
0
def edit_role(role_id):
    role_data = g.json_data
    if role_data.get('id') != role_id:
        raise APIException(ResultEnum.ROLE_INVALID_ID)

    role = AuthRole.get_by_status_or_404(role_id)

    if 'code' in role_data:
        role_by_code = AuthRole.get_by_code(role_data.get('code'))
        if role.id != role_by_code.id:
            raise APIException(ResultEnum.ROLE_CODE_EXIST)
    try:
        role.update(**role_data)
        return HttpHelper.normal_handler(role)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
Example #21
0
def edit_permission(permission_id):
    permission_data = g.json_data
    if permission_data.get('id') != permission_id:
        raise APIException(ResultEnum.PERMISSION_INVALID_ID)

    permission = AuthPermission.get_by_status_or_404(permission_id)

    if 'code' in permission_data:
        permission_by_code = AuthPermission.get_by_code(permission_data.get('code'))
        if permission.id != permission_by_code.id:
            raise APIException(ResultEnum.PERMISSION_CODE_EXISTS)

    try:
        permission.update(**permission_data)
        return HttpHelper.normal_handler(permission)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def upload():
    if 'avatar' not in request.files:
        raise APIException(ResultEnum.FILE_UPLOAD_METHOD_ERROR)

    file = request.files['avatar']
    org_name = file.filename

    # 调用Flask-uploads进行存储
    # 1、目标路径不存在自动创建
    # 2、重名自动加自增的数字后缀
    # 3、根据配置的允许后缀或者拒绝后缀进行过滤
    filename = avatar.save(file)
    url = avatar.url(filename)

    # 入库
    current_user = get_jwt_identity()
    _avatar = SysFile(file_name=filename,
                      org_name=org_name,
                      operator_id=current_user.get('id'),
                      file_url=url)
    _avatar.save()

    return HttpHelper.normal_handler(_avatar)
Example #23
0
def add_role():
    role_data = g.json_data

    if 'name' not in role_data or 'code' not in role_data:
        raise APIException(ResultEnum.INVALID_PARAMETER)

    role_code = role_data.get('code')
    role_name = role_data.get('name')
    role = AuthRole.get_by_code(role_code)
    if role:
        raise APIException(ResultEnum.ROLE_CODE_EXIST)

    role = AuthRole(code=role_code, name=role_name)
    try:

        if 'id' in role_data:
            del role_data['id']

        role.save(**role_data)
        return HttpHelper.normal_handler(role)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
Example #24
0
def add_permission():
    permission_data = g.json_data

    # Permission code cannot be empty
    code = permission_data.get('code', None)
    if not code:
        raise APIException(ResultEnum.PERMISSION_EMPTY_CODE)

    # Always existing permission with same code
    permission = AuthPermission.get_by_code(code)
    if permission:
        raise APIException(ResultEnum.PERMISSION_CODE_EXISTS)

    permission = AuthPermission()
    try:

        if 'id' in permission_data:
            del permission_data['id']

        permission.save(**permission_data)
        return HttpHelper.normal_handler(permission)
    except Exception as e:
        logger.error(e)
        raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
Example #25
0
def send_mail(user_id):
    task = send_welcome_email.delay('Hello', user_id, 'http://localhost:9000/')

    return HttpHelper.normal_handler({'task_id': task.id})
Example #26
0
def disable_user(user_id):
    usr = User.get_by_status_or_404(user_id)

    usr.toggle_disable()
    return HttpHelper.normal_handler()
Example #27
0
def delete_user(user_id):
    usr = User.get_by_status_or_404(user_id)
    usr.delete()
    return HttpHelper.normal_handler()