
[英]How can I do my logic in `http://127.0.0.1:8000/rest-auth/login/` of `django-rest-auth`?
[英]How can I handle HTTP login flow/logic
我正在开发一个要求用户登录的应用程序。 它是用于浏览和使用流行电子邮件客户端的终端浏览器。
我正在努力使用户真正登录而不会感到混乱。 我将尝试解释我要在psedueo代码中实现的目标,然后演示我目前已完成的工作。
username = 'joe@example.com'
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站点,至少是大型HTTP站点,都具有类似的登录流程。
有什么建议吗? 如果您需要更多信息,请询问。
假设支持代码正确地使用了异常,则可以通过减少重复代码来解决此问题:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.