当前位置: 首页>>代码示例>>Python>>正文


Python accessControl.AccessWrapper类代码示例

本文整理汇总了Python中MaKaC.accessControl.AccessWrapper的典型用法代码示例。如果您正苦于以下问题:Python AccessWrapper类的具体用法?Python AccessWrapper怎么用?Python AccessWrapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AccessWrapper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _setMailText

 def _setMailText(self):
     text = self.text
     if self.note:
         text = text + "Note: %s" % self.note
     if self.confSumary:
         #try:
             from MaKaC.common.output import outputGenerator
             from MaKaC.accessControl import AdminList, AccessWrapper
             import MaKaC.webinterface.urlHandlers as urlHandlers
             admin = AdminList().getInstance().getList()[0]
             aw = AccessWrapper()
             aw.setUser(admin)
             path = Config.getInstance().getStylesheetsDir()
             if os.path.exists("%s/text.xsl" % path):
                 stylepath = "%s/text.xsl" % path
             outGen = outputGenerator(aw)
             vars = { \
                     "modifyURL": urlHandlers.UHConferenceModification.getURL( self.conf ), \
                     "sessionModifyURLGen": urlHandlers.UHSessionModification.getURL, \
                     "contribModifyURLGen": urlHandlers.UHContributionModification.getURL, \
                     "subContribModifyURLGen":  urlHandlers.UHSubContribModification.getURL, \
                     "materialURLGen": urlHandlers.UHMaterialDisplay.getURL, \
                     "resourceURLGen": urlHandlers.UHFileAccess.getURL }
             confText = outGen.getOutput(self.conf,stylepath,vars)
             text += "\n\n\n" + confText
         #except:
         #    text += "\n\n\nSorry could not embed text version of the agenda..."
     self.mail.setText(text)
开发者ID:bubbas,项目名称:indico,代码行数:28,代码来源:timerExec.py

示例2: iter_interesting_events

def iter_interesting_events(avatar, data):
    idx = IndexesHolder().getById('categoryDateAll')
    now_local = utc2server(nowutc(), False)
    aw = AccessWrapper()
    aw.setUser(avatar)
    for event in _unique_events(idx.iterateObjectsIn('0', now_local, now_local + timedelta(weeks=24))):
        if _is_event_interesting(avatar, event, data) and event.canAccess(aw):
            yield event
开发者ID:marcosmolla,项目名称:indico,代码行数:8,代码来源:suggestions.py

示例3: __init__

 def __init__(self):
     self.closed = False
     self.xml_generator = XMLGen()
     self.xml_generator.initXml()
     self.xml_generator.openTag(b'collection', [[b'xmlns', b'http://www.loc.gov/MARC21/slim']])
     # This is horrible. but refactoring all the code in the indico core would be just as bad.
     aw = AccessWrapper()
     aw.setUser(User.find_first(is_admin=True).as_avatar)
     self.output_generator = outputGenerator(aw, self.xml_generator)
开发者ID:florv,项目名称:indico-plugins,代码行数:9,代码来源:marcxml.py

示例4: buildAW

def buildAW(ak, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not request.is_secure and api_settings.get('require_https') and request.user_agent.browser != 'google':
            raise HTTPAPIError('HTTPS is required', 403)
        aw.setUser(ak.user.as_avatar)
    return aw
开发者ID:k3njiy,项目名称:indico,代码行数:10,代码来源:handlers.py

示例5: buildAW

def buildAW(ak, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not request.is_secure and minfo.isAPIHTTPSRequired() and request.user_agent.browser != 'google':
            raise HTTPAPIError('HTTPS is required', 403)
        aw.setUser(ak.getUser())
    return aw
开发者ID:jbenito3,项目名称:indico,代码行数:11,代码来源:handlers.py

示例6: buildAW

def buildAW(ak, req, onlyPublic=False):
    aw = AccessWrapper()
    if ak and not onlyPublic:
        # If we have an authenticated request, require HTTPS
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        # Dirty hack: Google calendar converts HTTP API requests from https to http
        # Therefore, not working with Indico setup (requiring https for HTTP API authenticated)
        if not req.is_https() and minfo.isAPIHTTPSRequired() and req.get_user_agent().find("Googlebot") == -1:
            raise HTTPAPIError('HTTPS is required', apache.HTTP_FORBIDDEN)
        aw.setUser(ak.getUser())
    return aw
开发者ID:jt1,项目名称:indico,代码行数:11,代码来源:handlers.py

示例7: __init__

 def __init__(self):
     self._responseUtil = ResponseUtil()
     self._requestStarted = False
     self._aw = AccessWrapper()  # Fill in the aw instance with the current information
     self._target = None
     self._reqParams = {}
     self._startTime = None
     self._endTime = None
     self._tempFilesToDelete = []
     self._redisPipeline = None
     self._doProcess = True  # Flag which indicates whether the RH process
开发者ID:NIIF,项目名称:indico,代码行数:11,代码来源:base.py

示例8: __init__

 def __init__(self, params):
     RequestHandlerBase.__init__(self)
     self._reqParams = self._params = params
     self._requestStarted = False
     # Fill in the aw instance with the current information
     self._aw = AccessWrapper()
     self._aw.setIP(request.remote_addr)
     self._aw.setUser(session.user)
     self._target = None
     self._startTime = None
     self._tohttps = request.is_secure
     self._endTime = None
     self._doProcess = True  #Flag which indicates whether the RH process
                             #   must be carried out; this is useful for
                             #   the checkProtection methods
     self._tempFilesToDelete = []
     self._redisPipeline = None
开发者ID:jbenito3,项目名称:indico,代码行数:17,代码来源:base.py

示例9: __init__

 def __init__(self, params):
     if not self.UNICODE_PARAMS:
         params = unicode_struct_to_utf8(params)
     self._reqParams = self._params = params
     self._requestStarted = False
     # Fill in the aw instance with the current information
     self._aw = AccessWrapper()
     self._aw.setUser(session.avatar)
     self._target = None
     self._startTime = None
     self._tohttps = request.is_secure
     self._endTime = None
     self._doProcess = True  #Flag which indicates whether the RH process
                             #   must be carried out; this is useful for
                             #   the checkProtection methods
     self._tempFilesToDelete = []
     self._redisPipeline = None
开发者ID:MichelCordeiro,项目名称:indico,代码行数:17,代码来源:base.py

示例10: __init__

    def __init__(self, req=None):
        """Constructor. Initialises the rh setting up basic attributes so it is
            able to process the request.

            Parameters:
                req - OBSOLETE, MUST BE NONE
        """
        RequestHandlerBase.__init__(self, req)
        self._responseUtil = ResponseUtil()
        self._requestStarted = False
        self._aw = AccessWrapper()  #Fill in the aw instance with the current information
        self._target = None
        self._reqParams = {}
        self._startTime = None
        self._endTime = None
        self._tempFilesToDelete = []
        self._redisPipeline = None
        self._doProcess = True  #Flag which indicates whether the RH process
开发者ID:jbenito3,项目名称:indico,代码行数:18,代码来源:base.py

示例11: __init__

    def __init__( self, req ):
        """Constructor. Initialises the rh setting up basic attributes so it is
            able to process the request.

            Parameters:
                req - (mod_python.Request) mod_python request received for the
                    current rh.
        """
        RequestHandlerBase.__init__(self, req)
        self._requestStarted = False
        self._websession = None
        self._aw = AccessWrapper()  #Fill in the aw instance with the current information
        self._target = None
        self._reqParams = {}
        self._startTime = None
        self._endTime = None
        self._tempFilesToDelete = []
        self._doProcess = True  #Flag which indicates whether the RH process
开发者ID:vstitches,项目名称:indico,代码行数:18,代码来源:base.py

示例12: __init__

 def __init__(self, params, remoteHost, session):
     """
     Constructor.  Initializes provate variables
     @param req: HTTP Request provided by the previous layer
     """
     self._params = params
     self._requestStarted = False
     self._websession = session
     # Fill in the aw instance with the current information
     self._aw = AccessWrapper()
     self._aw.setIP(remoteHost)
     self._aw.setSession(session)
     self._aw.setUser(session.getUser())
     self._target = None
     self._startTime = None
     self._endTime = None
     self._doProcess = True  #Flag which indicates whether the RH process
                             #   must be carried out; this is useful for
                             #   the checkProtection methods
     self._tempFilesToDelete = []
开发者ID:davidmorrison,项目名称:indico,代码行数:20,代码来源:base.py

示例13: ServiceBase

class ServiceBase(RequestHandlerBase):
    """
    The ServiceBase class is the basic class for services.
    """

    def __init__(self, params, session, req):
        """
        Constructor.  Initializes provate variables
        @param req: HTTP Request provided by the previous layer
        """
        RequestHandlerBase.__init__(self, req)
        self._reqParams = self._params = params
        self._requestStarted = False
        self._websession = session
        # Fill in the aw instance with the current information
        self._aw = AccessWrapper()
        self._aw.setIP(self.getHostIP())
        self._aw.setSession(session)
        self._aw.setUser(session.getUser())
        self._target = None
        self._startTime = None
        self._tohttps = self._req.is_https()
        self._endTime = None
        self._doProcess = True  #Flag which indicates whether the RH process
                                #   must be carried out; this is useful for
                                #   the checkProtection methods
        self._tempFilesToDelete = []

    # Methods =============================================================

    def _getSession( self ):
        """
        Returns the web session associated to the received mod_python
        request.
        """
        return self._websession

    def _checkParams(self):
        """
        Checks the request parameters (normally overloaded)
        """
        pass

    def _checkProtection( self ):
        """
        Checks protection when accessing resources (normally overloaded)
        """
        pass

    def _processError(self):
        """
        Treats errors occured during the process of a RH, returning an error string.
        @param e: the exception
        @type e: An Exception-derived type
        """

        trace = traceback.format_exception(*sys.exc_info())

        return ''.join(trace)

    def _deleteTempFiles( self ):
        if len(self._tempFilesToDelete) > 0:
            for file in self._tempFilesToDelete:
                os.remove(file)

    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._setLang()
        self._checkParams()
        self._checkProtection()

        try:
            security.Sanitization.sanitizationCheck(self._target,
                                   self._params,
                                   self._aw)
        except (HtmlScriptError, HtmlForbiddenTag), e:
            raise HTMLSecurityError('ERR-X0','HTML Security problem. %s ' % str(e))

        if self._doProcess:
            if Config.getInstance().getProfile():
                import profile, pstats, random
                proffilename = os.path.join(Config.getInstance().getTempDir(), "service%s.prof" % random.random())
                result = [None]
                profile.runctx("result[0] = self._getAnswer()", globals(), locals(), proffilename)
                answer = result[0]
                rep = Config.getInstance().getTempDir()
                stats = pstats.Stats(proffilename)
                stats.strip_dirs()
                stats.sort_stats('cumulative', 'time', 'calls')
                stats.dump_stats(os.path.join(rep, "IndicoServiceRequestProfile.log"))
                os.remove(proffilename)
            else:
                answer = self._getAnswer()
            self._deleteTempFiles()
#.........这里部分代码省略.........
开发者ID:bubbas,项目名称:indico,代码行数:101,代码来源:base.py

示例14: RH

class RH(RequestHandlerBase):
    """This class is the base for request handlers of the application. A request
        handler will be instantiated when a web request arrives to mod_python;
        the mp layer will forward the request to the corresponding request
        handler which will know which action has to be performed (displaying a
        web page or performing some operation and redirecting to another page).
        Request handlers will be responsible for parsing the parameters coming
        from a mod_python request, handle the errors which occurred during the
        action to perform, managing the sessions, checking security for each
        operation (thus they implement the access control system of the web
        interface).
        It is important to encapsulate all this here as in case of changing
        the web application framework we'll just need to adapt this layer (the
        rest of the system wouldn't need any change).

        Attributes:
            _uh - (URLHandler) Associated URLHandler which points to the
                current rh.
            _req - (mod_python.Request) mod_python request received for the
                current rh.
            _requestStarted - (bool) Flag which tells whether a DB transaction
                has been started or not.
            _websession - ( webinterface.session.sessionManagement.PSession )
                Web session associated to the HTTP request.
            _aw - (AccessWrapper) Current access information for the rh.
            _target - (Locable) Reference to an object which is the destination
                of the operations needed to carry out the rh. If set it must
                provide (through the standard Locable interface) the methods
                to get the url parameters in order to reproduce the access to
                the rh.
            _reqParams - (dict) Dictionary containing the received HTTP
                 parameters (independently of the method) transformed into
                 python data types. The key is the parameter name while the
                 value should be the received paramter value (or values).
    """
    _tohttps = False # set this value to True for the RH that must be HTTPS when there is a BaseSecureURL
    _doNotSanitizeFields = []

    def __init__( self, req ):
        """Constructor. Initialises the rh setting up basic attributes so it is
            able to process the request.

            Parameters:
                req - (mod_python.Request) mod_python request received for the
                    current rh.
        """
        RequestHandlerBase.__init__(self, req)
        self._requestStarted = False
        self._websession = None
        self._aw = AccessWrapper()  #Fill in the aw instance with the current information
        self._target = None
        self._reqParams = {}
        self._startTime = None
        self._endTime = None
        self._tempFilesToDelete = []
        self._doProcess = True  #Flag which indicates whether the RH process
                                #   must be carried out; this is useful for
                                #   the checkProtection methods when they
                                #   detect that an inmediate redirection is
                                #   needed

    # Methods =============================================================

    def getTarget( self ):
        return self._target

    def _setSession( self ):
        """Sets up a reference to the corresponding web session. It uses the
            session manager to retrieve the session corresponding to the
            received request and makes sure it is a valid one. In case of having
            an invalid session it reset client settings and creates a new one.
       """
        if not self._websession:
            sm = session.getSessionManager()
            try:
                self._websession = sm.get_session( self._req )
            except session.SessionError:
                sm.revoke_session_cookie( self._req )
                self._websession = sm.get_session( self._req )

    def _getSession( self ):
        """Returns the web session associated to the received mod_python
            request.
        """
        if not self._websession:
            self._setSession()
        return self._websession

    def _setSessionUser( self ):
        """
        """
        self._aw.setUser( self._getSession().getUser() )

    def _getRequestParams( self ):
        return self._reqParams

    def getRequestParams( self ):
        return self._getRequestParams()

    def _disableCaching(self):
#.........这里部分代码省略.........
开发者ID:vstitches,项目名称:indico,代码行数:101,代码来源:base.py

示例15: handler

def handler(req, **params):
    ContextManager.destroy()
    logger = Logger.get('httpapi')
    path, query = req.URLFields['PATH_INFO'], req.URLFields['QUERY_STRING']
    if req.method == 'POST':
        # Convert POST data to a query string
        queryParams = dict(req.form)
        for key, value in queryParams.iteritems():
            queryParams[key] = [str(value)]
        query = urllib.urlencode(remove_lists(queryParams))
    else:
        # Parse the actual query string
        queryParams = parse_qs(query)

    dbi = DBMgr.getInstance()
    dbi.startRequest()
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.getRoomBookingModuleActive():
        Factory.getDALManager().connect()

    apiKey = get_query_parameter(queryParams, ['ak', 'apikey'], None)
    cookieAuth = get_query_parameter(queryParams, ['ca', 'cookieauth'], 'no') == 'yes'
    signature = get_query_parameter(queryParams, ['signature'])
    timestamp = get_query_parameter(queryParams, ['timestamp'], 0, integer=True)
    noCache = get_query_parameter(queryParams, ['nc', 'nocache'], 'no') == 'yes'
    pretty = get_query_parameter(queryParams, ['p', 'pretty'], 'no') == 'yes'
    onlyPublic = get_query_parameter(queryParams, ['op', 'onlypublic'], 'no') == 'yes'
    onlyAuthed = get_query_parameter(queryParams, ['oa', 'onlyauthed'], 'no') == 'yes'

    # Get our handler function and its argument and response type
    hook, dformat = HTTPAPIHook.parseRequest(path, queryParams)
    if hook is None or dformat is None:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    # Disable caching if we are not just retrieving data (or the hook requires it)
    if req.method == 'POST' or hook.NO_CACHE:
        noCache = True

    ak = error = result = None
    ts = int(time.time())
    typeMap = {}
    try:
        session = None
        if cookieAuth:
            session = getSessionForReq(req)
            if not session.getUser():  # ignore guest sessions
                session = None

        if apiKey or not session:
            # Validate the API key (and its signature)
            ak, enforceOnlyPublic = checkAK(apiKey, signature, timestamp, path, query)
            if enforceOnlyPublic:
                onlyPublic = True
            # Create an access wrapper for the API key's user
            aw = buildAW(ak, req, onlyPublic)
            # Get rid of API key in cache key if we did not impersonate a user
            if ak and aw.getUser() is None:
                cacheKey = normalizeQuery(path, query,
                                          remove=('ak', 'apiKey', 'signature', 'timestamp', 'nc', 'nocache',
                                                  'oa', 'onlyauthed'))
            else:
                cacheKey = normalizeQuery(path, query,
                                          remove=('signature', 'timestamp', 'nc', 'nocache', 'oa', 'onlyauthed'))
                if signature:
                    # in case the request was signed, store the result under a different key
                    cacheKey = 'signed_' + cacheKey
        else:
            # We authenticated using a session cookie.
            if Config.getInstance().getCSRFLevel() >= 2:
                token = req.headers_in.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
                if session.csrf_token != token:
                    raise HTTPAPIError('Invalid CSRF token', apache.HTTP_FORBIDDEN)
            aw = AccessWrapper()
            if not onlyPublic:
                aw.setUser(session.getUser())
            userPrefix = 'user-' + session.getUser().getId() + '_'
            cacheKey = userPrefix + normalizeQuery(path, query,
                                                   remove=('nc', 'nocache', 'ca', 'cookieauth', 'oa', 'onlyauthed',
                                                           'csrftoken'))

        # Bail out if the user requires authentication but is not authenticated
        if onlyAuthed and not aw.getUser():
            raise HTTPAPIError('Not authenticated', apache.HTTP_FORBIDDEN)

        obj = None
        addToCache = not hook.NO_CACHE
        cache = GenericCache('HTTPAPI')
        cacheKey = RE_REMOVE_EXTENSION.sub('', cacheKey)
        if not noCache:
            obj = cache.get(cacheKey)
            if obj is not None:
                result, extra, ts, complete, typeMap = obj
                addToCache = False
        if result is None:
            # Perform the actual exporting
            res = hook(aw, req)
            if isinstance(res, tuple) and len(res) == 4:
                result, extra, complete, typeMap = res
            else:
                result, extra, complete, typeMap = res, {}, True, {}
#.........这里部分代码省略.........
开发者ID:jt1,项目名称:indico,代码行数:101,代码来源:handlers.py


注:本文中的MaKaC.accessControl.AccessWrapper类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。