我开始编写一个应用程序,移动应用程序 (Android/iPhone) 将通过一系列使用 JSON 的 Web API 调用与 GAE 后端 (Python) 进行通信。
我无法使用 Google 帐户进行身份验证,因此我需要实现自己的身份验证。我知道如何执行此操作,但我不确定是否有更好的方法。
谁能帮忙提供一些代码示例/关于如何实现以下目标的建议?
方法
- 移动应用程序在服务器上调用登录方法,该方法在商店中进行身份验证并创建 session key 并将其返回给应用程序 - 不确定如何生成 key / session 或它应该在请求/响应中的什么位置是。
- 在每次调用时,应用都会将此 key 传递给服务器以进行身份验证,如果通过则允许执行操作。
- 除非明确注销或丢失 key ,否则用户不必再次登录移动设备。
登录方法 - 不生成 key
class Login(webapp.RequestHandler):
def post(self):
args = json.loads(self.request.body)
email = args['e']
pwd = args['p']
ret = {}
user = User.gql('WHERE email = :1', email).get()
if user and helpers.check_password(pwd, user.password):
ret['ret_code'] = 0
ret['dn'] = user.display_name
else:
ret['ret_code'] = 1
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(ret))
最佳答案
我认为您应该使用 webapp2 提供的功能来实现您的自定义注册。
from webapp2_extras import auth
from google.appengine.api import users
class RegisterHandler(webapp2.RequestHandler):
def post(self):
email=self.request.POST['email']
password=self.request.POST['password']
#Let webapp2 handle register and manage session
user = auth.get_auth().store.user_model.create_user('own:'+str(email), password_raw=password,email=email)
#user (True, User(key=Key('User', 80001), auth_ids=[u'own:useremail@mail.com'],email='useremail@mail.com',password=u'hashed_password',...))
if not user[0]: #user is a tuple
self.response.write(user[1]) # Error message
else:
#You can extend your User Model e.g UserProfile(User): or have a UserProperty in your profile model as the example.
profile=UserProfile(user=users.User(user[1].email)).put()
self.response.write(str(profile.key()))
class LoginHandler(webapp2.RequestHandler):
def post(self):
email = self.request.POST.get('email')
email = self.request.POST.get('password')
# Try to login user with password
# Raises InvalidAuthIdError if user is not found
# Raises InvalidPasswordError if provided password doesn't match with specified user
try:
auth.get_auth().get_user_by_password('own:'+email, password)
#Return user_session with User id,
except InvalidPasswordError, InvalidAuthIdError:
#Error
您可以检查通过以下方式登录的用户:
if auth.get_user_by_session():
#Logged in
else:
#Not logged in
在您的客户端应用程序(Android、IOS)上。您只需存储响应 cookie 并为每个子序列请求发送它。
祝你好运:)
关于android - 使用 Android/iPhone 处理 Google App Engine 上的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179014/