栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Google AppEngine:自定义身份验证

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Google AppEngine:自定义身份验证

您可以使用cookie来做到这一点……其实并不难。您可以使用cookie跟踪用户的身份验证,并将会话密钥存储在gae数据存储区中。

有一个例子(它只是说明基本思想,我不保证代码可以直接使用)

基本用户表:

# simply add an property to store the session keyclass User(db.Model):        username = db.StringProperty()    password = db.StringProperty()    session = db.StringProperty()

登录功能

# Do the following step:# 1. make sure user provide correct username and password# 2. generate a random session key # 3. store the session key to datastore# 4. set the session key and user name in cookieclass LoginAPI( Webapp.RequestHandler ):       def get(self):        username = self.getVar( 'username', username )        password = self.getVar( 'password', password )        user = User.all().filter("username = ", username).get()        password = encrypted_the_password(password) # encrypted your password with your own method!        if user.password == password:  # User login successfually  session = generate_random_session_key() # generate your session key here  user.session = session  user.put()  expires_time = decide_your_expires_time() # decide how long the login session is alive.  cookie_time_format = "%a, %d-%b-%Y %H:%M:%S GMT"  expires_datetime = datetime.datetime.fromtimestamp(expires_time)  # set cookie as session  self.response.headers.add_header( "Set-cookie", "user=%s; expires=%s; path=/" % ( user.username,expires_datetime.strftime( cookie_time_format ) ) )  self.response.headers.add_header( "Set-cookie", "session=%s; expires=%s; path=/" % ( user.session, expires_datetime.strftime( cookie_time_format ) ) )        else:  #User login failed  pass

登出功能

# Remove the previous cookie info class LoginAPI( Webapp.RequestHandler ):        def get(self): # remove the cookie self.response.headers.add_header( "Set-cookie", "user=%s; expires=%s; path=/" % ( "",expires_datetime.strftime( cookie_time_format ) ) ) self.response.headers.add_header( "Set-cookie", "session=%s; expires=%s; path=/" % ( "", expires_datetime.strftime( cookie_time_format ) ) )

当您需要用户登录时

# Get the session info from cookie. If the session info match the info stored in datastore# Then user authenticate successfully.class SomePage(Webapp.RequestHandler):    def get(self):        # get cookie info        username_from_cookie = self.request.cookies.get("user", "")        session_from_cookie = self.request.cookies.get("session", "")        if username_from_cookie and session_from_cookie: user = User.all().filter("username = ", username_from_cookie).get() if user.session == session_from_cookie:     # the user is login correctly     pass else:     # the user is not login     pass        else: # the user is not login pass


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号