本文整理汇总了Python中MaKaC.accessControl.AccessWrapper.setUser方法的典型用法代码示例。如果您正苦于以下问题:Python AccessWrapper.setUser方法的具体用法?Python AccessWrapper.setUser怎么用?Python AccessWrapper.setUser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MaKaC.accessControl.AccessWrapper
的用法示例。
在下文中一共展示了AccessWrapper.setUser方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setMailText
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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)
示例2: iter_interesting_events
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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
示例3: __init__
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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)
示例4: buildAW
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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
示例5: buildAW
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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
示例6: buildAW
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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
示例7: RH
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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):
#.........这里部分代码省略.........
示例8: RH
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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 - UNUSED/OBSOLETE, always None
_requestStarted - (bool) Flag which tells whether a DB transaction
has been started or not.
_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 = []
_isMobile = True # this value means that the generated web page can be mobile
HTTP_VERBS = frozenset(('GET', 'POST', 'PUT', 'DELETE'))
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
# must be carried out; this is useful for
# the checkProtection methods when they
# detect that an immediate redirection is
# needed
# Methods =============================================================
def getTarget(self):
return self._target
def isMobile(self):
return self._isMobile
def _setSessionUser(self):
self._aw.setUser(session.user)
@property
def csrf_token(self):
return session.csrf_token
def _getRequestParams(self):
return self._reqParams
def getRequestParams(self):
return self._getRequestParams()
def _disableCaching(self):
"""Disables caching"""
# IE doesn't seem to like 'no-cache' Cache-Control headers...
if request.user_agent.browser == 'msie':
# actually, the only way to safely disable caching seems to be this one
self._responseUtil.headers["Cache-Control"] = "private"
self._responseUtil.headers["Expires"] = "-1"
else:
self._responseUtil.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
self._responseUtil.headers["Pragma"] = "no-cache"
def _redirect(self, targetURL, status=303):
targetURL = str(targetURL)
if "\r" in targetURL or "\n" in targetURL:
raise MaKaCError(_("http header CRLF injection detected"))
self._responseUtil.redirect = (targetURL, status)
def _changeRH(self, rh, params):
"""Calls the specified RH after processing this one"""
self._responseUtil.call = lambda: rh().process(params)
def _checkHttpsRedirect(self):
"""If HTTPS must be used but it is not, redirect!"""
if self.use_https() and not request.is_secure:
#.........这里部分代码省略.........
示例9: handler
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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, {}
#.........这里部分代码省略.........
示例10: handler
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
def handler(prefix, path):
path = posixpath.join('/', prefix, path)
ContextManager.destroy()
clearCache() # init fossil cache
logger = Logger.get('httpapi')
if request.method == 'POST':
# Convert POST data to a query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.form.iteritems())
query = urllib.urlencode(queryParams)
else:
# Parse the actual query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.args.iteritems())
query = request.query_string
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'
oauthToken = 'oauth_token' in queryParams
# 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 NotFound
# Disable caching if we are not just retrieving data (or the hook requires it)
if request.method == 'POST' or hook.NO_CACHE:
noCache = True
ak = error = result = None
ts = int(time.time())
typeMap = {}
responseUtil = ResponseUtil()
try:
used_session = None
if cookieAuth:
used_session = session
if not used_session.user: # ignore guest sessions
used_session = None
if apiKey or oauthToken or not used_session:
if not oauthToken:
# 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, onlyPublic)
else: # Access Token (OAuth)
at = OAuthUtils.OAuthCheckAccessResource()
aw = buildAW(at, 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 = request.headers.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
if used_session.csrf_protected and used_session.csrf_token != token:
raise HTTPAPIError('Invalid CSRF token', 403)
aw = AccessWrapper()
if not onlyPublic:
aw.setUser(used_session.user)
userPrefix = 'user-' + used_session.user.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', 403)
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
#.........这里部分代码省略.........
示例11: handler
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
def handler(prefix, path):
path = posixpath.join('/', prefix, path)
ContextManager.destroy()
clearCache() # init fossil cache
logger = Logger.get('httpapi')
if request.method == 'POST':
# Convert POST data to a query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.form.iteritems())
query = urllib.urlencode(queryParams)
else:
# Parse the actual query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.args.iteritems())
query = request.query_string
dbi = DBMgr.getInstance()
dbi.startRequest()
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'
scope = 'read:legacy_api' if request.method == 'GET' else 'write:legacy_api'
try:
oauth_valid, oauth_request = oauth.verify_request([scope])
if not oauth_valid and oauth_request and oauth_request.error_message != 'Bearer token not found.':
raise BadRequest('OAuth error: {}'.format(oauth_request.error_message))
elif g.get('received_oauth_token') and oauth_request.error_message == 'Bearer token not found.':
raise BadRequest('OAuth error: Invalid token')
except ValueError:
# XXX: Dirty hack to workaround a bug in flask-oauthlib that causes it
# not to properly urlencode request query strings
# Related issue (https://github.com/lepture/flask-oauthlib/issues/213)
oauth_valid = False
# 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 NotFound
# Disable caching if we are not just retrieving data (or the hook requires it)
if request.method == 'POST' or hook.NO_CACHE:
noCache = True
ak = error = result = None
ts = int(time.time())
typeMap = {}
responseUtil = ResponseUtil()
try:
used_session = None
if cookieAuth:
used_session = session
if not used_session.user: # ignore guest sessions
used_session = None
if apiKey or oauth_valid or not used_session:
if not oauth_valid:
# 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, onlyPublic)
else: # Access Token (OAuth)
at = load_token(oauth_request.access_token.access_token)
aw = buildAW(at, 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 = request.headers.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
if used_session.csrf_protected and used_session.csrf_token != token:
raise HTTPAPIError('Invalid CSRF token', 403)
aw = AccessWrapper()
if not onlyPublic:
aw.setUser(used_session.avatar)
userPrefix = 'user-{}_'.format(used_session.user.id)
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', 403)
addToCache = not hook.NO_CACHE
cache = GenericCache('HTTPAPI')
#.........这里部分代码省略.........
示例12: ServiceBase
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
class ServiceBase(RequestHandlerBase):
"""
The ServiceBase class is the basic class for services.
"""
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 = []
# 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 _sendEmails( self ):
if hasattr( self, "_emailsToBeSent" ):
for email in self._emailsToBeSent:
GenericMailer.send(GenericNotification(email))
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)
"""
self._setLang()
self._checkParams()
self._checkProtection()
try:
security.sanitizationCheck(self._target,
self._params,
self._aw)
except (htmlScriptError, htmlForbiddenTag), e:
raise HTMLSecurityError('ERR-X0','HTML Security problem - you might be using forbidden tags: %s ' % str(e))
if self._doProcess:
answer = self._getAnswer()
self._sendEmails()
self._deleteTempFiles()
return answer
示例13: ServiceBase
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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()
#.........这里部分代码省略.........
示例14: ServiceBase
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
class ServiceBase(RequestHandlerBase):
"""
The ServiceBase class is the basic class for services.
"""
UNICODE_PARAMS = False
CHECK_HTML = True
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
# Methods =============================================================
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._checkParams()
self._checkProtection()
if self.CHECK_HTML:
try:
security.Sanitization.sanitizationCheck(self._target, self._params, self._aw, ['requestInfo'])
except HtmlForbiddenTag as e:
raise HTMLSecurityError('ERR-X0', 'HTML Security problem. {}'.format(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()
return answer
def _getAnswer(self):
"""
To be overloaded. It should contain the code that does the actual
business logic and returns a result (python JSON-serializable object).
If this method is not overloaded, an exception will occur.
If you don't want to return an answer, you should still implement this method with 'pass'.
"""
# This exception will happen if the _getAnswer method is not implemented in a derived class
#.........这里部分代码省略.........
示例15: handler
# 需要导入模块: from MaKaC.accessControl import AccessWrapper [as 别名]
# 或者: from MaKaC.accessControl.AccessWrapper import setUser [as 别名]
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:
sessionUser = getSessionForReq(req).getUser() if cookieAuth else None
if apiKey or not sessionUser:
# 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.
# Reject POST for security reasons (CSRF)
if req.method == "POST":
raise HTTPAPIError("Cannot POST when using cookie authentication", apache.HTTP_FORBIDDEN)
aw = AccessWrapper()
if not onlyPublic:
aw.setUser(sessionUser)
userPrefix = "user-" + sessionUser.getId() + "_"
cacheKey = userPrefix + normalizeQuery(
path, query, remove=("nc", "nocache", "ca", "cookieauth", "oa", "onlyauthed")
)
# 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, {}
if result is not None and addToCache:
ttl = HelperMaKaCInfo.getMaKaCInfoInstance().getAPICacheTTL()
cache.set(cacheKey, (result, extra, ts, complete, typeMap), ttl)
except HTTPAPIError, e:
error = e
#.........这里部分代码省略.........