• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python web.unauthorized函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了unauthorized函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:riskatlas,项目名称:layman,代码行数:32,代码来源:__init__.py


示例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()
开发者ID:tnanakou,项目名称:chestfreezer,代码行数:7,代码来源:chestfreezer_api.py


示例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
开发者ID:jakebarnwell,项目名称:PythonGenerator,代码行数:25,代码来源:main.py


示例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
开发者ID:AndyCCChang,项目名称:Create_RAID,代码行数:35,代码来源:index.py


示例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
开发者ID:5n1p,项目名称:webpy-example,代码行数:25,代码来源:wpauth.py


示例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()
开发者ID:goura,项目名称:karesansui,代码行数:35,代码来源:rest.py


示例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
开发者ID:gabelerner,项目名称:finkin,代码行数:25,代码来源:api.py


示例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()
开发者ID:nabeken,项目名称:karesansui,代码行数:52,代码来源:rest.py


示例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!
开发者ID:mrkd,项目名称:opensprinkler,代码行数:52,代码来源:ospi.py


示例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()
开发者ID:Alexis-D,项目名称:DFS,代码行数:51,代码来源:lockserver.py


示例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
开发者ID:Rimco,项目名称:OSPy,代码行数:25,代码来源:helpers.py


示例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)
开发者ID:msutter,项目名称:pulp_puppet,代码行数:34,代码来源:api.py


示例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
开发者ID:Bigben83,项目名称:opensprinkler,代码行数:34,代码来源:ospi.py


示例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()
开发者ID:nnoori,项目名称:amoeba_fn,代码行数:7,代码来源:admin.py


示例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
开发者ID:cwalv,项目名称:OSPi,代码行数:7,代码来源:ospi.py


示例16: GET

    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        validate_remote(ddict) # may raise unauthorized

        subj = ''
        body = ''
        try:
            subj = ddict['subject']
            body = ddict['body']
            if gv.sd['master']:
                email(subj, body)
                ret_str = json.dumps({'status':0})
            else:
                gv.logger.error('mail not sent by slave body: ' + body)
                ret_str = json.dumps({'status':1})
        except:
            gv.logger.exception('could not send email. subject: ' + subj + ' body: ' + body)
            ret_str = json.dumps({'status':2})
        web.header('Content-Type', 'application/json')
        return ret_str
开发者ID:bkoblenz,项目名称:HVAC,代码行数:25,代码来源:text_email.py


示例17: check_login

def check_login(redirect=False):
    """
    Check login.
    """
    qdict = web.input()

    try:
        if gv.sd['ipas'] == 1:
            return True

        if web.config._session.user == 'admin':
            return True
    except KeyError:
        pass

    if 'pw' in qdict:
        if gv.sd['password'] == password_hash(qdict['pw'], gv.sd['salt']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login')
    return False
开发者ID:aocana,项目名称:SIP,代码行数:25,代码来源:helpers.py


示例18: GET

 def GET(self):
     qdict = web.input()
     global rovals, sd
     try:
         if sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     if not sd['en']: return # check operation status
     sd['rsn'] = 0
     sd['bsy'] = 1
     rovals = json.loads(qdict['t'])
     rovals.pop()
     gv.ps = []
     for i in range(sd['nst']):
         gv.ps.append([0,0])
     for i, t in enumerate(rovals):
         if t != 0:
             gv.ps[i][0] = 98
             gv.ps[i][1] = t
             gv.rs[i][1] = time.time() + t
     thread.start_new_thread(self.run, ())
     raise web.seeother('/')
     return
开发者ID:horacimacias,项目名称:opensprinkler,代码行数:25,代码来源:ospi.py


示例19: GET

    def GET(self, tenant_id):
        auth_token = web.ctx.get("environ").get("HTTP_X_AUTH_TOKEN", None)
        auth_tenant_id = web.ctx.get("environ").get("HTTP_X_AUTH_TENANT_ID", None)

        keystone = identity.auth(
            token_id=auth_token,
            tenant_id=auth_tenant_id,
            url=_endpoint,
            api="NATIVE",
            admin=True,
            admin_url="http://10.100.32.36:35357/v2.0",
        )
        keystone.management_url = _admin_endpoint

        if len(tenant_id) <= 0:
            tenant = identity.list_tenants(keystone, "NATIVE")
        else:
            tenant = identity.get_tenant(keystone, tenant_id, "NATIVE")

        if tenant is None:
            return web.unauthorized()

        body = json.dumps(tenant, indent=4)
        web.header("Content-Type", "application/json")
        return body
开发者ID:lixmgl,项目名称:Intern_OpenStack_Swift,代码行数:25,代码来源:tenantWeb.py


示例20: GET

    def GET(self):
        qdict = web.input()

        #ensure request is from localhost and we trust it
        remote = web.ctx.env['REMOTE_ADDR']
        if remote != '127.0.0.1':
            gv.logger.info('receive_remote_sensor_data invalid remote: ' + remote)
            raise web.unauthorized()

        remote_sensor_name = ''
        try:
            remote_sensor_name = qdict['name']
            del qdict['name']
            if remote_sensor_name in gv.remote_sensors:
                sensor_data = gv.remote_sensors[remote_sensor_name]
            else:
                sensor_data = {}
            for key in qdict:
                sensor_data[key] = int(qdict[key], 0)
            sensor_data['time'] = gv.now
            gv.remote_sensors[remote_sensor_name] = sensor_data
        except:
            gv.logger.exception('receive_remote_sensor_data name: ' + remote_sensor_name + ' qdict: ' + str(qdict))

        zone_list = []
        for z in gv.remote_zones:
            zone_list.append(z)
        web.header('Content-Type', 'application/json')
        return json.dumps(zone_list)
开发者ID:bkoblenz,项目名称:Irricloud,代码行数:29,代码来源:substations.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python web.unloadhook函数代码示例发布时间:2022-05-26
下一篇:
Python web.storage函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap