2015-03-31 35 views
0

我正在開發一個需要用戶登錄的應用程序。這是一個終端瀏覽器,用於瀏覽和使用流行的電子郵件客戶端。我該如何處理HTTP登錄流程/邏輯

我很努力的實際登錄用戶的邏輯流程沒有東西變得凌亂。我將嘗試解釋我想要在psedueo代碼中實現的內容,然後演示我目前完成的工作。

username = '[email protected]' 
password = 'itsasecret' 

# User has logged in before using our application. Instead of 
# logging in via HTTP, just inject the cookies into the session. 
if userExistsInDatabase: 
    session.addCookies(db.getCookies(username)) 

    # Check the session is still valid. Just because we load 
    # the cookie from the database doesn't mean it's valid as 
    # the account could be blocked, or session could have expired 
    if session.checkIfSessionIsValid(): 
     print 'Logged In' 
    else: 
     # Login failed, now we need to do a HTTP request 
     # incase the session has died 
     if session.login(username, password): 
      # Login success 
     else: 
      # Login Failed 
else: 
    # No session exists in DB, try to log in and add user to db 
    if session.login(username, password): 
     # Login success 
    else: 
     # Login Failed 

我希望代碼能夠解釋得比我能說的更好。但是,我遇到的問題是一切都變得混亂和快速,並且無論何時需要使用它,都必須重複此代碼是一種痛苦。

這是我在很多項目中經常做的事情,因爲大多數HTTP站點,至少大型站點,都有類似的登錄流。

有什麼建議嗎?如果您需要更多信息,請詢問。

回答

1

假設支持的代碼正確地使用異常,可以用更少的代碼複製解決這個問題:

class Session(): 
    def reconnect(self, username): 
     try: 
      cookie = db.getCookies(username) 
     except LookupError: 
      raise UserDoesNotExist 
     else: 
      self.addCookies(cookie) 
      if not self.checkIfSessionIsValid(): 
       raise InvalidSession 

    def login(self, ...): 
     if not do_the_login(...): 
      raise LoginError 

try: 
    try: 
     session.reconnect(...) 
    except (InvalidSession, UserDoesNotExist): 
     session.login(...) 
except LoginError: 
    # failed 


# at this point, either an unhandled exception terminated 
# this code path or we are logged in.