Exemplo n.º 1
0
 def open_session(self, sid="", create=False):
     if sid is None:
         raise APIException(
             SystemErrorCode.SessionIdCannotNone,
             "Session Id Cannot be None!If you want to create a Session Please not pass args!"
         )
     if sid == "" and not os.path.exists(self.directory + '/' + sid):
         return None
     if sid == "":
         sid = str(uuid4())
     rv = SqliteSession(self.directory, sid)
     if 'EXPTIME' not in rv:
         if create:
             rv['EXPTIME'] = datetime.datetime.now()
         else:
             self.close_session(rv)
             raise APIException(SystemErrorCode.SessionIdInvalid,
                                "Session Invalid!")
     else:
         exp_date = rv['EXPTIME']
         if datetime.datetime.now() - exp_date > datetime.timedelta(
                 days=30):
             self.close_session(rv)
             rv = None
             rv = self.open_session()
     return rv
Exemplo n.º 2
0
def sharedPermissionValidate(PermissionRequired=Permission.PermissionRead,
                             prefix=u'',
                             param=None):
    if param is None:
        param = request.json_param

    permissions = None
    domainid = prefix + u'DomainId'
    shareid = prefix + u'ShareId'
    rootObject = None
    # 带有domainId,object属于某域用户
    if domainid in param:
        domainId = request.session["DomainId"]
        # 如果当前用户和object所属owner所在域相同,则获取object的userid
        if int(param[domainid]) == domainId:
            UserId = db.session.query(
                Domain.OwnerUserId).filter_by(Id=domainId).one()[0]
        else:
            raise APIException(SystemErrorCode.UnkonwnError, u'无权限执行操作')
    # 带有shardeId,说明object是某个共享对象
    elif shareid in param:
        ShareId = param[shareid]
        shareusercacheall = ShareUserCache.query.filter(
            or_(ShareUserCache.UserId == request.session['UserId'],
                ShareUserCache.UserId == 0),  #判断是否同事共享给所有用户
            ShareUserCache.ShareObjectId == ShareId).all()
        for permission in permissions:
            try:
                shareusercache = shareusercacheall[0]
                raise APIException(SystemErrorCode.UnkonwnError, u'无权限执行操作')
            except IndexError:
                if len(shareusercacheall) == 2:  #如果共享给所有用户 计算合并后权限
                    shareusercache = shareusercacheall[0]
                for i in range(1, len(shareusercacheall)):
                    for permission in permissions:
                        if shareusercache.__dict__['User' +
                                                   permission.name[10:]] != 1:
                            shareusercache.__dict__[
                                'User' +
                                permission.name[10:]] = shareusercacheall[
                                    i].__dict__['User' + permission.name[10:]]
            if permission == Permission.PermissionShare or shareusercache.__dict__[
                    'User' + permission.name[10:]] != 1:
                raise APIException(SystemErrorCode.UnkonwnError, u'无权限执行操作')
        UserId = shareusercache.ShareObject.CreatorUserId
        rootObject = shareusercache.ShareObject.Object
    else:
        UserId = request.session["UserId"]
    if rootObject is None:
        rootObject = Object.query.filter_by(ParentId=None,
                                            OwnerUserId=UserId).one()
    if int(param[prefix + u'Id']) != 0 and Object.query.filter(
            Object.Id == param[prefix + u'Id'],
            Object._Left_ >= rootObject._Left_,
            Object._Right_ <= rootObject._Right_, Object.OwnerUserId
            == UserId).count() == 0:
        raise APIException(SystemErrorCode.UnkonwnError, u'无权限执行操作')
    return UserId
Exemplo n.º 3
0
 def decorated_view(*args, **kwargs):
     if current_app.config.get("SSL"):
         if request.is_secure:
             return fn(*args, **kwargs)
         else:
             return JSONEncoder(ensure_ascii=False).encode(
                 APIException(SystemErrorCode.OnlySupportHttps,
                              u"仅支持Https方式访问该接口"))
     return fn(*args, **kwargs)
Exemplo n.º 4
0
 def wrapper(*args, **kwargs):
     SessionId = GetSessionId()
     exception = JSONEncoder(ensure_ascii=False).encode(
         APIException(SystemErrorCode.SessionIdInvalid, u'DBToken无效',
                      request.path))
     if SessionId is None:
         return exception
     request.session = None
     try:
         request.session = ManualSession().open_session(sid=SessionId)
     except:
         pass
     if request.session is None:
         return exception
     if Permission is not None:
         pass  #TODO:权限认证
     return resource(*args, **kwargs)
Exemplo n.º 5
0
 def wrapper(*args, **kwargs):
     if request.method == 'GET':
         return APIException(40400, u'API提交方式错误', request.path)
     return resource(*args, **kwargs)
Exemplo n.º 6
0
    def wrapper(*args, **kwargs):
        request.json_param = get_json_param()
        e = None
        try:
            resp = resource(*args, **kwargs)
        except APIException as e:
            resp = e
        except KeyError as e:
            resp = APIException(SystemErrorCode.ArgumentError, u'参数错误',
                                request.path)
        except ValueError as e:
            resp = APIException(SystemErrorCode.ArgumentError, u'参数错误',
                                request.path)
        except MultipleResultsFound as e:
            resp = APIException(SystemErrorCode.DataError, u'数据不唯一',
                                request.path)
        except NoResultFound as e:
            resp = APIException(SystemErrorCode.DataError, u'数据不存在',
                                request.path)
        except Exception as e:
            resp = APIException(SystemErrorCode.UnkonwnError, u'未知错误',
                                request.path)

        if isinstance(resp, Response):  # There may be a better way to test
            return resp
        if isinstance(resp, APIException):
            print((resp.to_str()))
            if (e is not None):
                print get_error_log_str()
        if 'jsonpCallback' in request.values:
            jsonpCallback = request.values['jsonpCallback']
            resp.data = str(jsonpCallback) + '(' + resp.data + ');'
        return resp
Exemplo n.º 7
0
    def wrapper(*args, **kwargs):
        request.json_param = get_json_param()
        e = None
        try:
            resp = resource(*args, **kwargs)
        except APIException as e:
            resp = e
        except KeyError as e:
            resp = APIException(SystemErrorCode.ArgumentError, u'参数错误',
                                request.path)
        except ValueError as e:
            resp = APIException(SystemErrorCode.ArgumentError, u'参数错误',
                                request.path)
        except MultipleResultsFound as e:
            resp = APIException(SystemErrorCode.DataError, u'数据不唯一',
                                request.path)
        except NoResultFound as e:
            resp = APIException(SystemErrorCode.DataError, u'数据不存在',
                                request.path)
        except Exception as e:
            resp = APIException(SystemErrorCode.UnkonwnError, u'未知错误',
                                request.path)

        if isinstance(resp, Response):  # There may be a better way to test
            return resp
        if isinstance(resp, APIException):
            print((resp.to_str()))
            if (e is not None):
                print get_error_log_str()
        data, code, headers = unpack(resp)
        from Main import api
        resp = api.make_response(data, code, headers=headers)
        if 'jsonpCallback' in request.values:
            jsonpCallback = request.values['jsonpCallback']
            resp.data = str(jsonpCallback) + '(' + resp.data + ');'
        try:
            request.session.close()  # 关闭Session
        except AttributeError:
            pass
        return resp
Exemplo n.º 8
0
def objectOperatePermission(object_id, user_id, context, operation):
    bWrite = True
    bDownload = True
    bRead = True
    try:
        obj = Object.query.filter_by(Id=object_id).one()
    except NoResultFound:
        raise APIException(DataErrorCode.NoRecord, '无该访问资源')
    if context == 'contractAttachment':
        ca = ContractAttachment.query.filter_by(ObjectId=object_id).all()
        if len(ca) == 0:
            raise APIException(DataErrorCode.NoRecord, '无该访问合同附件')
        for a in ca:
            if a.Type == ContractAttachmentType.Exchange \
                    or a.Type == ContractAttachmentType.Clip \
                    or a.Type == ContractAttachmentType.CutVideo \
                    or a.Type == ContractAttachmentType.RenderVideo \
                    or a.Type == ContractAttachmentType.SoundVideo \
                    or a.Type == ContractAttachmentType.FinalVideo:
                bDownload = True
                bWrite = True
            elif a.Type == ContractAttachmentType.End:
                bDownload = True
                bWrite = False
        try:
            ContractUserGroup.query.filter_by(ContractId=ca[0].ContractId,
                                              UserId=user_id).one()
        except NoResultFound:
            raise APIException(DataErrorCode.NoRecord, '无该合同用户')
    elif context == 'requirementAttachment':
        user = User.query.filter_by(Id=user_id).one()
        ra = RequirementAttachment.query.filter_by(ObjectId=object_id).all()
        if len(ra) == 0:
            raise APIException(DataErrorCode.NoRecord, '无该需求附件')
        rs = ResourceShare.query.filter_by(ResourceId=ra[0].RequirementId,
                                           ResourceType='r').all()
        for r in rs:
            if r.ShareDomainId == 0 or r.ShareDomainId == user.DomainId:
                bWrite = True
                bDownload = True
                break
    elif context == 'storage':
        owner = User.query.filter_by(Id=obj.OwnerUserId).one()
        user = User.query.filter_by(Id=user_id).one()
        if owner.DomainId != user.DomainId:
            try:
                StorageShare.query.filter_by(ObjectId=obj.Id,
                                             DomainId=user.DomainId).one()
            except NoResultFound:
                raise APIException(SystemErrorCode.NonPermissionHandle,
                                   '无权限访问该资源')
    if operation == 'download':
        if not bDownload:
            raise APIException(SystemErrorCode.NonPermissionHandle, '无权限访问该资源')
    elif operation == 'delete' or operation == 'move' or operation == 'write':
        if not bWrite:
            raise APIException(SystemErrorCode.NonPermissionHandle, '无权限访问该资源')
    elif operation == 'read':
        if not bRead:
            raise APIException(SystemErrorCode.NonPermissionHandle, '无权限访问该资源')
    return obj.OwnerUserId