检查Bottle中每个请求的身份验证

时间:2012-12-30 01:08:19

标签: python authorization bottle

对于Bottle中的每个请求,我想通过HTTP身份验证检查请求是否合格。我的想法是使用一个函数,该函数在每个@route函数的开头调用。

def check_authentificaiton(requests):
    auth = request.headers.get('Authorization')
    credentials = parse_auth(auth)
    if credentials[0] is not 'user' or credentials[1] is not 'password':
        raise Exception('Request is not authorized')

这似乎有点多余,因为我想保护每个请求,如果我忘记调用它可能会失败。还有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

我认为你正在寻找一个装饰器,它要求只有在用户登录时才能访问路径。与下面的示例中一样,@require_uid是一个装饰器,您可以在需要用户登录的任何功能周围使用.Flask有一个login_required decorator

Using decorators to require sign in with bottle.py

def require_uid(fn):
    def check_uid(**kwargs):   
        cookie_uid = request.get_cookie('cookieName', secret='cookieSignature')

        if cookie_uid:
            # do stuff with a user object
            return fn(**kwargs)
        else:
            redirect("/loginagain")

    return check_uid



@route('/userstuff', method='GET')
@require_uid
@view('app')
def app_userstuff():
    # doing things is what i like to do
    return dict(foo="bar")
相关问题