Python Google App Engine: Webapp2: Authentication

I use user accounts for one of my projects and use the user model and authentication provided by webapp2. Everything works fine, but I'm stuck in the part where authentication failed.

Example:

#imports
from webapp2_extras.appengine.auth.models import User

class LoginHandler(SomeBaseRequestHandler):
  def get(self):
  '''self code goes in here'''

  def post(self):
    auth_id = 'authentication:id'
    password = 'somepassword'

    user = User.get_by_auth_password(authid, password)
    if user:
      # code to set a session and redirect to homepage
    else:
      # append error list and render a template

I can log in, but the problem occurs if the user enters an incorrect username or password. if the user provides any incorrect credentials, it causes an error on the server side.

Traceback (most recent call last):
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/home/tigerstyle/orbit/orbit/orbit/handlers.py", line 36, in dispatch
webapp2.RequestHandler.dispatch(self)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/tigerstyle/orbit/orbit/orbit/handlers.py", line 239, in post
user = User.get_by_auth_password(auth_id, password)
File "/opt/google_appengine_1.6.4/lib/webapp2/webapp2_extras/appengine/auth/models.py",    line 301, in get_by_auth_password
raise auth.InvalidPasswordError()
InvalidPasswordError
+3
source share
1 answer

You can use try / except to control the input stream:

def post(self):
  """
  username: Get the username from POST dict
  password: Get the password from POST dict
  """
  username = self.request.POST.get('username')
  password = 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:
    self.auth.get_user_by_password(username, password)
    self.redirect('/secure')
  except (InvalidAuthIdError, InvalidPasswordError), e:
    # Returns error message to self.response.write in the BaseHandler.dispatcher
    # Currently no message is attached to the exceptions
    return e
+4
source

All Articles