나는 내 웹 핸들러 나는 장식라는 세션 하나라는 권한 부여를 연결합니다 들어 내 자신의 사용자 및 세션 manangement
를 사용하는 경향이있다. 세션 데코레이터는 모든 요청에 세션을 첨부하고 권한 부여 데코레이터는 사용자가 권한이 있는지 확인합니다.
(신중한 말로 권한 부여 데코레이터는 내 응용 프로그램을 개발하는 방법과 관련이 있습니다. 대부분의 요청에 매개 변수)
그래서 예를 들어 웹 핸들러처럼 보일 수 있습니다 : 위의 코드에서
class UserProfile(webapp.RequestHandler):
@session
@authorize
def get(self, user):
# Do some funky stuff
# The session is attached to the self object.
someObjectAttachedToSession = self.SessionObj.SomeStuff
self.response.out.write("hello %s" % user)
는 세션 장식 내가에 존재하는 쿠키를 기반으로 할 몇 가지 세션 물건을 첨부 의뢰. 권한 부여 헤더는 세션이 올바른 경우에만 사용자가 페이지에 액세스 할 수 있는지 확인합니다.
데코레이터 코드는 다음과 같습니다 :
import functools
from model import Session
import logging
def authorize(redirectTo = "/"):
def factory(method):
'Ensures that when an auth cookie is presented to the request that is is valid'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
self.redirect(redirectTo)
return
else:
if session.settings is None:
self.redirect(redirectTo)
return
username = session.settings.key().name()
if len(args) > 0:
if username != args[0]:
# The user is allowed to view this page.
self.redirect(redirectTo)
return
result = method(self, *args, **kwargs)
return result
return wrapper
return factory
def session(method):
'Ensures that the sessions object (if it exists) is attached to the request.'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
session = Session()
session.session_id = Session.MakeId()
session.auth_token = Session.MakeId()
session.put()
# Attach the session to the method
self.SessionObj = session
#Call the handler.
result = method(self, *args, **kwargs)
self.response.headers.add_header('Set-Cookie', 'auth_id=%s; path=/; HttpOnly' % str(session.auth_token))
self.response.headers.add_header('Set-Cookie', 'session_id=%s; path=/; HttpOnly' % str(session.session_id))
return result
return wrapper
def redirect(method, redirect = "/user/"):
'When a known user is logged in redirect them to their home page'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
if self.SessionObj is not None:
if self.SessionObj.settings is not None:
# Check that the session is correct
username = self.SessionObj.settings.key().name()
self.redirect(redirect + username)
return
except:
pass
return method(self, *args, **kwargs)
return wrapper
쿠키는 좋은 대안입니다. 앱 클래스에 사용자 클래스의 속성과 같이 직접 말해 줄 수있는 무언가가 있었으면 좋겠습니까? – MathOldTimer
쿠키는 나쁜 생각입니다. 새 브라우저를 사용하거나 쿠키를 삭제 한 기존 사용자가 새 사용자로 표시됩니다. –