Commits

hideki nara committed 24043b6

UrlBasedSessionMiddlewareを分離

  • Participants
  • Parent commits 27d0d77

Comments (0)

Files changed (2)

bpmobile/middleware.py

 from django.core.cache import cache
 from django.http import HttpResponseRedirect, HttpResponseForbidden
 
-from bpmobile import utils
 from django.conf import global_settings #HDKNR
+from django.utils.importlib import import_module
+
+from django.utils.functional import SimpleLazyObject
+from django.contrib.auth import get_user
+from django.contrib.auth.middleware import AuthenticationMiddleware
 
 import logging,traceback
 log = logging.getLogger(__name__)
 
+#
+from bpmobile import utils
+
 class BPMobileMiddleware(object):
     def process_request(self, request):
         request.agent = uamobile.detect(request.META)
         if agent.is_docomo() or agent.is_ezweb():
             log.debug("process_request:session in URL " + str(request.agent ) )
             #: DoCoMo & EZweb    
-            #: CSRF for DoCoMo without cookie header
-            if request.COOKIES.has_key(global_settings.CSRF_COOKIE_NAME ) ==False:
-                request.COOKIES[global_settings.CSRF_COOKIE_NAME ] = request.POST.get('csrfmiddlewaretoken','')
 
             #: restore the sesstion key embedded in url 
             m = utils.from_url(request.path_info,request.path)
                 request.path_info = m['path_info']  #:rewrite
                 request.path =  m['path']           #:rewrite
                 request.session = engine.SessionStore(session_key)
-                if utils.is_valid_session(request) == False:
-                    request.session= None
+#                if utils.is_valid_session(request) == False:
+#                    request.session= None
+                if request.META.get(global_settings.CSRF_COOKIE_NAME ,None) == None:
+                    request.META['CSRF_COOKIE'] =  request.session.get('last_csrf_cookie','')
+                    request.COOKIES[global_settings.CSRF_COOKIE_NAME ] =  request.session.get('last_csrf_cookie','')
+                    pass
                 return 
 
             #: otherwise work in the original bpmobile way
         if agent.is_nonmobile() or agent.is_bogus():
             return HttpResponseForbidden('403 Access Forbidden.')
 
+####################################################################
 
+class UrlBasedMoobileSessionMiddleware(object):
+    cache_key_name = 'session_key_%s'
+
+    def get_agent(self, request):
+        agent= getattr(request, 'agent', uamobile.detect(request.META))
+        if agent:
+            setattr(agent,'device_class', 'pc' if agent.is_nonmobile() else 'fp' ) 
+        return agent
+
+    def get_cache_key(self, guid):
+        return self.cache_key_name % guid
+
+    def process_request(self, request):
+        agent= self.get_agent(request )                 #:agentは先に取得する
+
+        if all([ getattr(request,'user',None),
+                  getattr(request.user,'session',None) ]):
+            #:すでにセッションが復元されていたら何もしない
+            return 
+
+        engine = import_module(settings.SESSION_ENGINE)
+        params = utils.from_url(request.path_info,request.path)
+        session_key=None
+        if params :
+            session_key = params['session_key']   
+            request.path_info = params['path_info']  #:rewrite
+            request.path =  params['path']           #:rewrite
+            request.session = engine.SessionStore(session_key)
+            request.COOKIES[global_settings.CSRF_COOKIE_NAME ] =  request.session.get('last_csrf_cookie','')
+            request.session.save() 
+
+        elif  agent.is_docomo() or agent.is_ezweb() : 
+            #:セッションがないはず
+            request.session = engine.SessionStore()
+            request.session.save() 
+
+        delattr( request, '_cached_user' ) #:ログインユーザーをチャラパーにする
+        AuthenticationMiddleware().process_request(request)     #:request.user が用意されます
+
+    def process_response(self, request, response):
+        agent = self.get_agent(request)
+
+        if ( agent.is_docomo() or agent.is_ezweb() ) and request.session != None:
+            #: あとで強制的にセッション変数からCSRFトークンを戻すため
+            request.session['last_csrf_cookie'] = request.META.get("CSRF_COOKIE",'')
+
+        return response

bpmobile/utils.py

 from django.contrib.auth import login as auth_login
 from django.core.urlresolvers import reverse as default_reverse
 def login(request,user):    
+    ''' loginの際に、匿名ユーザーからログインユーザーに昇格するとセッションキーがあたらしくなるので注意 '''
     auth_login(request,user)        #:Default
     request.session['session_embedded'] = True
-    request.session['login_address'] = request.META.get('REMOTE_ADDR','')
+    request.session['login_address'] = request.META.get('REMOTE_ADDR','')   #: TODO: AuとかはIPアドレスがリクエスト毎に変わるので使えない
+    request.session.save()
 
 def reverse(viewname, request=None,urlconf=None, args=None, kwargs=None, prefix=None, current_app=None,
             session="auto"):