2013-11-04 245 views
0

我想實現一個裝飾器,在授予對函數的訪問權限之前對用戶的令牌進行身份驗證。我目前的實現有點奇怪,我需要做兩個查詢,因爲我無法在裝飾器中獲取當地人。有一個更好的方法嗎?自定義身份驗證裝飾器

def require_auth(func): 
    print 'require_auth' 
    @wraps(func) 
    def inner(): 
     if 'token' in request.json: 
      token = request.json['token'] 
      session = Session() 
      for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==token): 
       auth_user = instance.username 
      try: 
       auth_user 
       print 'authenticated!' 
      except NameError: 
       abort(401) 
     else: 
      abort(401) 
     return func() 
    return inner 

@app.route('/st/projects', methods=['POST']) 
@require_auth 
def post_project(): 

    session = Session() 

    for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==request.json['token']): 
     auth_user = instance.username 

    # do something with auth_user 

    session.close() 
+0

什麼版本的Python? – dawg

+0

使用python 2.7 – proteneer

回答

1

您可以將身份驗證的用戶存儲在flask.g

from flask import g 

# ... 

def require_auth(func): 

    # ... 

    for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==token): 
     g.auth_user = instance.username 
    try: 
     g.auth_user 
     print 'authenticated!' 
    except AttributeError: 
     abort(401) 

    # ... 

然後在您的視圖功能,您可以訪問用戶爲g.auth_user