本文整理汇总了Python中web.unauthorized函数的典型用法代码示例。如果您正苦于以下问题:Python unauthorized函数的具体用法?Python unauthorized怎么用?Python unauthorized使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unauthorized函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setReturnCode
def _setReturnCode(self, code):
"""Set the return code
:param: code
:type code: integer or string
returns success: [True|False]
"""
success = False
if code in (200, "200", "ok"):
web.ok()
success = True
elif code in (201, "201", "created"):
web.created()
success = True
elif code in (400, "400", "badrequest"):
web.badrequest()
elif code in (401, "401", "unauthorized"):
web.unauthorized()
elif code in (404, "404", "notfound"):
web.notfound()
elif code in (409, "409", "conflict"):
web.conflict()
elif code in (500, "500", "internalerror"):
web.internalerror()
if success:
logging.debug("[LayMan][_setReturnCode] Code: '%s'" % code)
else:
logging.error("[LayMan][_setReturnCode] Code: '%s'" % code)
return success
示例2: _auth_check
def _auth_check():
""" checks if user is authenticated and throws exception if he isn't """
try:
if not _is_authenticated():
raise web.unauthorized()
except:
raise web.unauthorized()
示例3: myProcessor
def myProcessor(handler):
web.ctx.veerezoDB = model.getDBConnection()
try:
username = checkUserAuth()
web.ctx.username = username
except ValueError:
web.header('WWW-Authenticate', 'Basic realm="Veerezo"')
web.unauthorized()
return 'Access denied'
web.ctx.beanstalk = pybsc.BeanstalkClient()
def postBackendJob(method, *args, **kwargs):
d = {}
d['method'] = method
d['args'] = args
d['kwargs'] = kwargs
jobID = web.ctx.beanstalk.put(json.dumps(d), ttr=60, tube='veerezo-backend')
model.addJob(web.ctx.veerezoDB, jobID)
return jobID
web.ctx.postBackendJob = postBackendJob
result = handler()
return result
示例4: processor
def processor(handler):
api_name = web.ctx.path.split("/")[-1]
if web.ctx.path not in anonymous_urls:
if api_name != 'login' and api_name != 'logout' and not session.get('logged_in', False):
if Ezs3CephConfig().get_cluster_name():
raise web.unauthorized()
else:
# customize message to hint user login with root account
raise web.unauthorized('need root')
if api_name != 'login':
# make login_id and login_type accessible by handlers
web.ctx.login_id = session.get('login_id')
web.ctx.login_type = session.get('login_type')
if not check_url_permission():
raise web.unauthorized()
if api_name in binary_api:
web.header('Content-type', 'application/octet-stream')
return handler()
else:
result = handler()
if isinstance(result, int):
resp = response(api_name, result)
elif isinstance(result, tuple):
if len(result) == 2:
resp = extra_response(api_name, result[0], result[1])
else:
logger.error("Invalid API response: {}".format(result))
resp = response(api_name, errors.GENERAL.GENERAL_ERROR)
else:
logger.error("Invalid API response: {}".format(result))
resp = response(api_name, errors.GENERAL.GENERAL_ERROR)
return resp
示例5: validate_basic_auth
def validate_basic_auth():
"""
Authenticates against the database user accounts using HTTP Basic authentication
"""
log.loggit( 'validate_basic_auth()' )
auth_header = web.ctx.env.get('HTTP_AUTHORIZATION')
username = ""
password = ""
if auth_header is None:
raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )
elif not auth_header.startswith('Basic '):
raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )
else:
auth = re.sub('^Basic ','',auth_header)
username, password = base64.decodestring( auth ).split(':')
adb = accountdb.AccountDB()
account = adb.login( username, password, False )
if account is None:
raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )
return True
示例6: wrapper
def wrapper(self, *args, **kwargs):
if web.ctx.env.has_key("HTTP_AUTHORIZATION"):
(user, email) = login()
if user:
self.me = user
# Logout
fname = "%s%s" % (LOGOUT_FILE_PREFIX, self.me.email)
if os.access(fname, os.F_OK):
os.unlink(fname)
return web.unauthorized()
# Login: Success
if user.languages in self.languages:
x = self.languages.index(user.languages)
self.languages.pop(x)
self.languages.insert(0, user.languages)
self.logger.info(
"user_id=%s,lang=%s : Method=%s - Basic Authentication=Success"
% (self.me.id, ",".join(self.languages), self.__method__)
)
# __init__#self._ update!!
self._ = mako_translation(languages=self.languages)
return func(self, *args, **kwargs)
else:
# Login: Failure
self.logger.info("user=%s : Method=%s - Basic Authentication=Failure" % (email, self.__method__))
return web.unauthorized()
else:
# Login: Anonymous
self.logger.info("user=anonymous : Method=%s - Basic Authentication=Anonymous" % (self.__method__))
return web.unauthorized()
示例7: _getParamsOrError
def _getParamsOrError(self):
params = {}
try:
body = xml.dom.minidom.parseString(web.data())
request = body.getElementsByTagName("Request")[0]
for param in request.childNodes:
if (param.nodeType == param.ELEMENT_NODE):
params[param.tagName] = param.childNodes[0].data
except:
raise web.badrequest()
if (not web.ctx.environ.has_key('HTTP_X_FINKIN_AUTH')):
raise web.unauthorized()
if (web.ctx.environ.has_key('HTTP_X_FINKIN_DEBUG')):
params['debug'] = True
fda = finkin.FinkinDA(False)
userID = fda.Auth(web.ctx.environ['HTTP_X_FINKIN_AUTH'])
if (userID == 0):
raise web.unauthorized()
params['log-user'] = userID
return params
示例8: wrapper
def wrapper(self, *args, **kwargs):
if web.ctx.path[0:6] == '/data/':
languages = unicode(karesansui.config['application.default.locale'])
if web.ctx.env.has_key('HTTP_AUTHORIZATION'):
_http_auth = web.ctx.env['HTTP_AUTHORIZATION'].strip()
if _http_auth[:5] == 'Basic':
email, password = b64decode(_http_auth[6:].strip()).split(':')
session = web.ctx.orm
user = findby1email(session, email)
languages = user.languages
self._ = mako_translation(languages=[ unicode(languages), ])
return func(self, *args, **kwargs)
if karesansui_database_exists() is False:
return web.tempredirect(web.ctx.path + "init", absolute=False)
if web.ctx.env.has_key('HTTP_AUTHORIZATION'):
(user, email) = login()
if user:
self.me = user
# Logout
fname = '%s%s' % (LOGOUT_FILE_PREFIX, self.me.email,)
if os.access(fname, os.F_OK):
os.unlink(fname)
return web.unauthorized()
# Login: Success
if user.languages in self.languages:
x = self.languages.index(user.languages)
self.languages.pop(x)
self.languages.insert(0, user.languages)
self.logger.info('user_id=%s,lang=%s : Method=%s - Basic Authentication=Success' %
(self.me.id, ','.join(self.languages), self.__method__))
# __init__#self._ update!!
self._ = mako_translation(languages=self.languages)
return func(self, *args, **kwargs)
else:
# Login: Failure
self.logger.info('user=%s : Method=%s - Basic Authentication=Failure' %
(email, self.__method__))
return web.unauthorized()
else:
# Login: Anonymous
self.logger.info('user=anonymous : Method=%s - Basic Authentication=Anonymous' %
(self.__method__))
return web.unauthorized()
示例9: GET
def GET(self):
qdict = web.input()
try:
if not qdict.has_key('o25') and qdict['pw'] != base64.b64decode(gv.sd['pwd']):
raise web.unauthorized()
return
elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict['pw'] != base64.b64decode(gv.sd['pwd']):
raise web.unauthorized()
return
elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict['pw'] == base64.b64decode(gv.sd['pwd']):
gv.sd['ipas'] = 1
except KeyError:
pass
try:
if qdict['cpw'] !='' and qdict['cpw'] == qdict['npw']:
gv.sd['pwd'] = base64.b64encode(qdict['npw'])
except KeyError:
pass
vstr = data('options')
ops = vstr.index('[')+1
ope = vstr.index(']')
optstr = vstr[ops:ope]
optlst = optstr.split(',')
onumlst = []
i=3
while i < len(optlst):
onumlst.append(optlst[i].replace(' ', ''))
if optlst[i-2] == '1': #clear check box items
optlst[i-1]= '0'
try:
sdref[optlst[i]];
gv.sd[sdref[optlst[i]]]=0
except KeyError:
pass
i+=4
for key in qdict.keys():
if key[:1] == 'o':
oidx = onumlst.index(key[1:])
if qdict[key] == 'on' or '':
qdict[key] = '1'
optlst[(oidx*4)+2] = qdict[key]
optstr = ','.join(optlst)
optstr = optstr.replace(', ', ',')
vstr = vstr.replace(vstr[ops:ope], optstr)
save('options', vstr)
if int(qdict['o15'])+1 != gv.sd['nbrd']: self.update_scount(qdict)
if int(qdict['o18']) != gv.sd['mas']:
clear_mm()
self.update_sd(qdict)
raise web.seeother('/')
#alert = '<script>alert("Options values saved.");window.location="/";</script>'
return #alert # ---- Alerts are not considered good interface progrmming. Use sparingly!
示例10: POST
def POST(self, filepath):
"""If filepath == / (useless for now, but allow easy addition
of transactions: try to get a lock for all filepaths in the
request data (each one is separated from the next one
by a newline). If it's possible return a list of
filepath/lock_id like this:
/data/sample.in=12345
/src/linux/kernel.h=42
If at least one file can't be locked, then no lock is granted
and a '401 Unauthorized' response is send.
Else, if there's no lock on filepath, or an old lock,
grant a new one (and revoke the older one if needed).
Return a 200 OK, with the lock id.
If a client want mutliples locks it should request them in one
query (/) because if it ask in one request for each lock, it may
create dead locks.
"""
web.header('Content-Type', 'text/plain; charset=UTF-8')
filepath = str(filepath)
if filepath == '/':
granted_locks = {}
for filepath in web.data().split('\n'):
if not filepath:
# to allow an empty line at the end of the request data
continue
try:
granted_locks[filepath] = _grant_new_lock(filepath)
except Exception as e:
logging.exception(e)
# revoking all previoulsy allocated locks
for filepath in granted_locks:
_revoke_lock(filepath)
raise web.unauthorized()
# list of filename=lock_id
return '\n'.join('%s=%d' % (filepath, lock_id,)\
for filepath, lock_id in granted_locks.items())
try:
return _grant_new_lock(filepath)
except Exception as e:
logging.exception(e)
raise web.unauthorized()
示例11: check_login
def check_login(redirect=False):
from ospy import server
import web
from ospy.options import options
qdict = web.input()
try:
if options.no_password:
return True
if server.session.validated:
return True
except KeyError:
pass
if 'pw' in qdict:
if test_password(qdict['pw']):
return True
if redirect:
raise web.unauthorized()
return False
if redirect:
raise web.seeother('/login', True)
return False
示例12: GET
def GET(self, resource_type=None, resource=None):
"""
Credentials here are not actually used for authorization, but instead
are used to identify:
consumer ID in the username field
repository ID in the password field
This is to work around the fact that the "puppet module install"
command has hard-coded absolute paths, so we cannot put consumer or
repository IDs in the URL's path.
"""
if resource_type is not None:
if resource_type == self.REPO_RESOURCE:
credentials = ('.', resource)
elif resource_type == self.CONSUMER_RESOURCE:
credentials = (resource, '.')
else:
return web.notfound()
else:
credentials = self._get_credentials()
if not credentials:
return web.unauthorized()
module_name = self._get_module_name()
if not module_name:
# apparently our version of web.py, 0.36, doesn't take a message
# parameter for error handlers like this one. Ugh.
return web.badrequest()
version = web.input().get('version')
data = self.get_releases(*credentials, module_name=module_name, version=version)
return self.format_results(data)
示例13: GET
def GET(self):
qdict = web.input()
try:
if gv.sd["ipas"] != 1 and qdict["pw"] != base64.b64decode(gv.sd["pwd"]):
raise web.unauthorized()
return
except KeyError:
pass
pnum = int(qdict["pid"]) + 1 # program number
cp = json.loads(qdict["v"])
if cp[0] == 0 and pnum == gv.pon: # if disabled and program is running
for i in range(len(gv.ps)):
if gv.ps[i][0] == pnum:
gv.ps[i] = [0, 0]
if gv.srvals[i]:
gv.srvals[i] = 0
for i in range(len(gv.rs)):
if gv.rs[i][3] == pnum:
gv.rs[i] = [0, 0, 0, 0]
if cp[1] >= 128 and cp[2] > 1:
dse = int((time.time() - time.timezone) / 86400)
ref = dse + cp[1] - 128
cp[1] = (ref % cp[2]) + 128
if int(qdict["pid"]) > gv.sd["mnp"]:
alert = '<script>alert("Maximum number of programs\n has been reached.");window.location="/";</script>'
return alert
elif qdict["pid"] == "-1": # add new program
gv.pd.append(cp)
else:
gv.pd[int(qdict["pid"])] = cp # replace program
jsave(gv.pd, "programs")
gv.sd["nprogs"] = len(gv.pd)
raise web.seeother("/vp")
return
示例14: GET
def GET(self):
#check if the user is Admin
if web.ctx.session.is_admin():
render = get_render('admin')
return render.add_user()
else:
return web.unauthorized()
示例15: approve_pwd
def approve_pwd(qdict):
"""Password checking"""
try:
if not gv.sd['ipas'] and not qdict['pw'] == base64.b64decode(gv.sd['pwd']):
raise web.unauthorized()
except KeyError:
pass