實作登入機制
def get_current_user(h):
from db.models import User
_id = h.request.cookies.get('id')
session = h.request.cookies.get('session')
try:
_id = int(_id)
except:
_id = None
if _id and session:
user = User.get_by_id(int(_id))
if user and user.session == session:
return user
return None
很明顯, 是從cookies 中的id 和 session 去和 DB 中的比對, 若match 則判定他有登入
讓user 登入則是:
def login_user(h, email, password):
from db.models import User
user = User.login(email, password)
if user:
h.response.set_cookie("id", str(user.key.id()), path='/')
h.response.set_cookie("session", user.session, path='/')
return user
else:
return None
當中利用到的 User class 中的method 則定義如下:
class User(ndb.Model):
email = ndb.StringProperty()
password = ndb.StringProperty()
session = ndb.StringProperty()
@classmethod
def hash(cls, email, string):
import hashlib
return hashlib.md5(email + string).hexdigest()
@classmethod
def create(cls, email, password):
user = User.query(User.email == email).get()
if user:
return None
user = User(email=email,
password=User.hash(email, password))
user.put()
return user
@classmethod
def login(cls, email, password):
import random
user = User.query(User.email == email).get()
if not user or user.password != User.hash(email, password):
return None
# update session of user
user.session = User.hash(email, str(random.random()))
user.put()
return user
留言
張貼留言