2016-02-15 73 views
0

今天我正在用python和flask創建一個小的RESTfull服務。看來,我似乎無法解決auth問題。如何爲flask-httpauth創建自定義登錄驗證方法?

這裏是我的代碼:

# Extensions 
auth = HTTPBasicAuth() 

def login_user(username,password): 
    # If the username can be decoded as a JWT & the password is empty, return true 
    if jwt.decode(username, SERVER_PAYLOARD_SECRET, algorithms=['HS256']) == '{"some":"payload"}' and password == "": 
     return username and password 
    else: 
     # Otherwise, make the classic username/password verification 
     # Get the password corresponding to the username. 
     connection = sqlite3.connect(database_name) 
     cursor = connection.cursor() 
     cursor.execute("SELECT Username AND Password FROM Users WHERE Username = ?", (username)) 
     returned_data = cursor.fetchall() 
     # Do the verification 
     if returned_data[0] == username and pwd_context.verify(password,returned_data[1]): 
      return username and password 
     else: 
      abort(401) 

@auth.get_password 
def verify_password(username,password): 
    return login_user(username,password) 
    # Look if the token used is in memory 

@app.route('/api/user/delete_user', methods=['GET','POST']) 
@auth.login_required 
def delete_user(): 
    # Validate the login token, and then delete the user from the 
    # database and all the streams or information he has. 
    return "Hello World" 

我不知道我能回報什麼,如果我的login_user()函數是正確的。

感謝您的幫助,

乾杯

編輯:當我運行的代碼,我有這樣的錯誤:

Traceback (most recent call last): 
    [...] 
    File "/home/n07070/FarDrive/Code/OpenPhotoStream/lib/python3.4/site-packages/flask_httpauth.py", line 57, in decorated 
    password = self.get_password_callback(auth.username) 
TypeError: verify_password() missing 1 required positional argument: 'password' 

回答

0

小錯誤。更改此:

@auth.get_password 
def verify_password(username,password): 
    return login_user(username,password) 
    # Look if the token used is in memory 

這樣:

@auth.verify_password 
def verify_password(username,password): 
    return login_user(username,password) 
    # Look if the token used is in memory 

燒瓶HTTPAuth提供了幾種不同的方法,使您可以驗證客戶端的憑據。 @auth.get_password是一個非常簡單的函數,你的裝飾函數需要用戶名,你需要返回與該賬戶相對應的密碼。 @auth.verify_password是一個更靈活的選項,它可以爲您提供客戶端提供的憑據,您可以實現自己的驗證邏輯。聽起來像最後一個選項是你想要的。

+0

哇,謝謝你的回答! 它的工作原理!令人敬畏的工作,保持它! – N07070