Google AppEngine: пользовательская аутентификация - PullRequest
8 голосов
/ 15 июля 2011

Способ аутентификации моих пользователей в AppEngine с использованием учетных записей Google просто замечательный.

Однако мне нужно использовать мою систему аутентификации и авторизации .

.У меня будет таблица AppUsers с именами пользователей и зашифрованными паролями.

Я читаю кое-что о сеансах на gae, но мне нужна помощь по запуску безопасности моего приложения.

Как я могу отслеживать свои аутентифицированныесеанс пользователя?Установка файла cookie?

Начинающий.

1 Ответ

6 голосов
/ 16 июля 2011

Вы можете использовать cookie для этого ... Это действительно не так сложно.Вы можете использовать cookie для отслеживания аутентификации пользователя и сохранения сеансового ключа в хранилище данных gae.

Есть пример (он просто показывает основную идею, я не гарантирую, что код можно использовать напрямую)

Таблица основных пользователей:

# simply add an property to store the session key
class 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 cookie
class 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...