예제 #1
0
파일: emoji.py 프로젝트: subc/anchovy
    def encode_emoji(self, text):
        """
        絵文字をエンコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        \ue000 -> &#xe000 に変換

        引数
         text

        返り値
         エンコードした絵文字を返す
        """
        if self.emoji_re is None:
            self.emoji_re = re.compile(u"[\ue000-\uf0fc]")

        Log.debug("encode_emoji before: %r" % text)

        def emoji_open(m):
            """
            emoji_open
            """
            return "&#x%x" % ord(m.group(0))

        encoded = self.emoji_re.sub(emoji_open, text)
        Log.debug("encode_emoji after: %r" % encoded)
        return encoded
예제 #2
0
    def encode_emoji(self, text):
        """
        Encode "Emoji" and return it.
        For Gree`s InspectionAPI 
        eg.  \ue000 -> &#xe000 
        
        argument:
         text
        return value:
         encoded "emoji" 
         
        絵文字をエンコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        \ue000 -> &#xe000 に変換

        引数
         text

        返り値
         エンコードした絵文字を返す
        """
        Log.debug('encode_emoji before: %r' % text)

        if self.emoji_re is None:
            self.emoji_re = re.compile(u'[\ue000-\uf0fc]')

        def emoji_open(m):
            return '&#x%x' % ord(m.group(0))

        encoded = self.emoji_re.sub(emoji_open, text)
        Log.debug('encode_emoji after: %r' % encoded)
        return encoded
예제 #3
0
    def get_normalized_parameters(self):
        """
        Return a string that contains the parameters that must be signed.
        """
        Log.debug("[Method] get_normalized_parameters")
        params = self.parameters
        try:
            # Exclude the signature if it exists.
            del params['oauth_signature']
        except:
            pass

        # Escape key values before sorting.
        key_values = []
        for key, value in params.iteritems():
            if isinstance(key, basestring) and not _is_post_values_key(key):
                key_values.append(
                    (escape(_utf8_str(key)), escape(_utf8_str(value))))
            else:
                try:
                    value = list(value)
                except TypeError, e:
                    assert 'is not iterable' in str(e)
                    key_values.append(
                        (escape(_utf8_str(key)), escape(_utf8_str(value))))
                else:
                    if _is_post_values_key(key):
                        key = _remove_post_values_key(key)
                    key_values.extend(
                        (escape(_utf8_str(key)),
                         escape(_utf8_str(item)
                                ) if isinstance(item, basestring) else item)
                        for item in value)
예제 #4
0
def _security_check(request, session_id):
    """
    Security check using cookie
    cookieによるセキュリティチェック
    """

    #リクエストサービスのコールバックにcookieチェックは不要
    if settings.GREE_REQUEST_API and request.path == reverse(settings.GREE_REQUEST_API_HEADER):
        return True

    from mobilejp.middleware.mobile import get_current_device
    device = get_current_device()
    Log.debug("_security_check device.is_webview %s" % device.is_webview)
    if device.is_webview:
        Log.debug("[Method] _security_check webview Pass")
        return True

    Log.debug("[Method] _security_check ")

    ua = request.META.get('HTTP_USER_AGENT', None)
    if ua is None:
        return False

    security_name = request.COOKIES.get(_get_security_name(), u'')
    m = hashlib.md5()
    m.update(ua)
    m.update(str(session_id))

    Log.debug("[Method] _security_check security_name: %s", security_name)
    Log.debug("[Method] _security_check m.hexdigest: %s", m.hexdigest())

    return m.hexdigest() == security_name
예제 #5
0
    def _create_endpoint_url(self, path, secure=False, url_tail=None):
        """
        FP/SP/WEBVIEW判定し対応したendpoint_urlを返す
        """

        protocol = 'https' if secure else 'http'

        from mobilejp.middleware.mobile import get_current_device
        device = get_current_device()

        if device:
            if device.is_webview:
                endpoint = self.container['endpoint_webview']
            elif device.is_smartphone:
                endpoint = self.container['endpoint_sp']
            else:
                endpoint = self.container['endpoint_fp']
        else:
            endpoint = self.container['endpoint_fp']

        Log.debug("url_tail %s " % url_tail)

        if url_tail or url_tail == '':
            url = '%s://%s%s%s' % (protocol, endpoint, url_tail, path)
        else:
            url = '%s://%s%s%s' % (protocol, endpoint,
                                   self.container['api_url_tail'], path)

        return url
예제 #6
0
    def encode_emoji(self, text):
        """
        絵文字をエンコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        \ue000 -> &#xe000 に変換

        引数
         text

        返り値
         エンコードした絵文字を返す
        """
        if self.emoji_re is None:
            self.emoji_re = re.compile(u'[\ue000-\uf0fc]')

        Log.debug('encode_emoji before: %r' % text)

        def emoji_open(m):
            """
            emoji_open
            """
            return '&#x%x' % ord(m.group(0))

        encoded = self.emoji_re.sub(emoji_open, text)
        Log.debug('encode_emoji after: %r' % encoded)
        return encoded
예제 #7
0
 def test_debug(self):
     """
     関数が問題なく通るかのみ確認
     """
     msg = 'Simplejson Error1.'
     obj = 'hoge'
     Log.debug(msg, obj)
예제 #8
0
파일: emoji.py 프로젝트: subc/anchovy
    def decode_emoji(self, text):
        """
        絵文字をデコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        &#xe000 -> \ue000に変換
        絵文字じゃない &#xXXXX は空文字にする

        引数
         text

        返り値
         デコードした絵文字を返す
        """
        if self.emoji_re is None:
            self.emoji_re = re.compile(u"[\ue000-\uf0fc]")
        if self.emoji_decode_re is None:
            self.emoji_decode_re = re.compile(r"&#x(\w{4})")

        Log.debug("decode_emoji before: %r" % text)

        def emoji_close(m):
            """
            emoji_close
            """
            c = unichr(int(m.group(1), 16))
            if self.emoji_re.search(c):
                return c
            else:
                return ""

        decoded = self.emoji_decode_re.sub(emoji_close, text)
        Log.debug("decode_emoji after: %r" % decoded)
        return decoded
예제 #9
0
    def post(self, userid, message):
        '''
        POST(新規登録)
        戻したJSONのtextIdを用いることで再度このテキストにアクセスすることができる
        
        POST(Newly register)
        You can access to this text using the textId of returned JSON.
        '''
        # ローカルではリクエストできない
        # You can`t request on local.
        if settings.OPENSOCIAL_DEBUG:
            return None

        message = self.container.encode_emoji(message)
        data = simplejson.dumps({'data': message})
        text_id = None
        json = None
        response = self._api_request('POST', userid, data = data)
        Log.debug('Inspection POST. response: %s' % (response))
        json = simplejson.loads(response)

        if 'entry' in json:
            entry = json['entry'][0]
            if 'textId' in entry:
                text_id = entry['textId']
        Log.debug('Inspection: post: textId:%s' % text_id)

        if not json:
            error = self.container.ResponseError('post', 'Inspection POST')
            raise error
        return text_id
예제 #10
0
 def test_warn(self):
     """
     関数が問題なく通るかのみ確認
     """
     msg = 'Simplejson Error4.'
     obj = 'hoge'
     Log.info(msg, obj)
예제 #11
0
    def _create_endpoint_url(self, path, secure=False, url_tail=None):
        """
        FP/SP/WEBVIEW判定し対応したendpoint_urlを返す
        """

        protocol = "https" if secure else "http"

        from mobilejp.middleware.mobile import get_current_device

        device = get_current_device()

        if device:
            if device.is_webview:
                endpoint = self.container["endpoint_webview"]
            elif device.is_smartphone:
                endpoint = self.container["endpoint_sp"]
            else:
                endpoint = self.container["endpoint_fp"]
        else:
            endpoint = self.container["endpoint_fp"]

        Log.debug("url_tail %s " % url_tail)

        if url_tail or url_tail == "":
            url = "%s://%s%s%s" % (protocol, endpoint, url_tail, path)
        else:
            url = "%s://%s%s%s" % (protocol, endpoint, self.container["api_url_tail"], path)

        return url
예제 #12
0
파일: mixin.py 프로젝트: subc/anchovy
    def get_or_cache_thumbnail_list(self):
        """
        cacheがなければAPIgetする
        """
        url_list = {}
        path = self.thumbnail_path_key()
        try:
            data = cache.get(path, None)
            if data:
                Log.debug("data %s" % data)
                url_list = msgpack.unpackb(data)
                Log.debug("data url_list %s" % url_list)
            else:
                request = get_current_request()
                request_params = [value for key,value in self.THUMBNAIL_MAPS.items()]
                request_params = (',').join(request_params)
                profile = People(request).get_myself(self.id, request_params, caching=False)
                for key, value in self.THUMBNAIL_MAPS.items():
                    url_list[value] = profile[value]
                Log.debug("new data url_list %s" % url_list)

                pack_data = msgpack.packb(url_list)
                Log.debug("pack_data url_list %s" % pack_data)
                cache.set(path, pack_data, timeout=self.CACHE_TIME)
        except:
            url_list = {}
        Log.debug("return url_list %s" % url_list)

        return url_list
예제 #13
0
    def encode_emoji(self, text):
        """
        Encode "Emoji" and return it.
        For Gree`s InspectionAPI 
        eg.  \ue000 -> &#xe000 
        
        argument:
         text
        return value:
         encoded "emoji" 
         
        絵文字をエンコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        \ue000 -> &#xe000 に変換

        引数
         text

        返り値
         エンコードした絵文字を返す
        """
        Log.debug("encode_emoji before: %r" % text)

        if self.emoji_re is None:
            self.emoji_re = re.compile(u"[\ue000-\uf0fc]")

        def emoji_open(m):
            return "&#x%x" % ord(m.group(0))

        encoded = self.emoji_re.sub(emoji_open, text)
        Log.debug("encode_emoji after: %r" % encoded)
        return encoded
예제 #14
0
def _security_check(request, session_id):
    """
    Security check using cookie
    cookieによるセキュリティチェック
    """

    #リクエストサービスのコールバックにcookieチェックは不要
    if settings.GREE_REQUEST_API and request.path == reverse(
            settings.GREE_REQUEST_API_HEADER):
        return True

    from mobilejp.middleware.mobile import get_current_device
    device = get_current_device()
    Log.debug("_security_check device.is_webview %s" % device.is_webview)
    if device.is_webview:
        Log.debug("[Method] _security_check webview Pass")
        return True

    Log.debug("[Method] _security_check ")

    ua = request.META.get('HTTP_USER_AGENT', None)
    if ua is None:
        return False

    security_name = request.COOKIES.get(_get_security_name(), u'')
    m = hashlib.md5()
    m.update(ua)
    m.update(str(session_id))

    Log.debug("[Method] _security_check security_name: %s", security_name)
    Log.debug("[Method] _security_check m.hexdigest: %s", m.hexdigest())

    return m.hexdigest() == security_name
예제 #15
0
파일: test_log.py 프로젝트: subc/anchovy
 def test_warn(self):
     """
     関数が問題なく通るかのみ確認
     """
     msg = 'Simplejson Error4.'
     obj = 'hoge'
     Log.info(msg, obj)
예제 #16
0
파일: test_log.py 프로젝트: subc/anchovy
 def test_debug(self):
     """
     関数が問題なく通るかのみ確認
     """
     msg = 'Simplejson Error1.'
     obj = 'hoge'
     Log.debug(msg, obj)
예제 #17
0
    def get_or_cache_thumbnail_list(self):
        """
        cacheがなければAPIgetする
        """
        url_list = {}
        path = self.thumbnail_path_key()
        try:
            data = cache.get(path, None)
            if data:
                Log.debug("data %s" % data)
                url_list = msgpack.unpackb(data)
                Log.debug("data url_list %s" % url_list)
            else:
                request = get_current_request()
                request_params = [
                    value for key, value in self.THUMBNAIL_MAPS.items()
                ]
                request_params = (',').join(request_params)
                profile = People(request).get_myself(self.id,
                                                     request_params,
                                                     caching=False)
                for key, value in self.THUMBNAIL_MAPS.items():
                    url_list[value] = profile[value]
                Log.debug("new data url_list %s" % url_list)

                pack_data = msgpack.packb(url_list)
                Log.debug("pack_data url_list %s" % pack_data)
                cache.set(path, pack_data, timeout=self.CACHE_TIME)
        except:
            url_list = {}
        Log.debug("return url_list %s" % url_list)

        return url_list
예제 #18
0
    def decode_emoji(self, text):
        """
        絵文字をデコードして返す
        GREEのInspectionAPI、モバゲーのTextDataAPI用
        &#xe000 -> \ue000に変換
        絵文字じゃない &#xXXXX は空文字にする

        引数
         text

        返り値
         デコードした絵文字を返す
        """
        if self.emoji_re is None:
            self.emoji_re = re.compile(u'[\ue000-\uf0fc]')
        if self.emoji_decode_re is None:
            self.emoji_decode_re = re.compile(r'&#x(\w{4})')

        Log.debug('decode_emoji before: %r' % text)

        def emoji_close(m):
            """
            emoji_close
            """
            c = unichr(int(m.group(1), 16))
            if self.emoji_re.search(c):
                return c
            else:
                return ''

        decoded = self.emoji_decode_re.sub(emoji_close, text)
        Log.debug('decode_emoji after: %r' % decoded)
        return decoded
예제 #19
0
    def get_normalized_parameters(self):
        """
        Return a string that contains the parameters that must be signed.
        """
        Log.debug("[Method] get_normalized_parameters")
        params = self.parameters
        try:
            # Exclude the signature if it exists.
            del params['oauth_signature']
        except:
            pass

        # Escape key values before sorting.
        key_values = []
        for key, value in params.iteritems():
            if isinstance(key, basestring) and not _is_post_values_key(key):
                key_values.append((escape(_utf8_str(key)), escape(_utf8_str(value))))
            else:
                try:
                    value = list(value)
                except TypeError, e:
                    assert 'is not iterable' in str(e)
                    key_values.append((escape(_utf8_str(key)), escape(_utf8_str(value))))
                else:
                    if _is_post_values_key(key):
                        key = _remove_post_values_key(key)
                    key_values.extend((escape(_utf8_str(key)), escape(_utf8_str(item)) if isinstance(item, basestring) else item) for item in value)
예제 #20
0
def create_rsa_hash(request, params):
    """
    create_rsa_hash
    """
    Log.debug("[Method] create_rsa_hash")

    message = create_message(request, params)
    return hashlib.sha1(message).digest()
예제 #21
0
def create_rsa_hash(request, params):
    """
    create_rsa_hash
    """
    Log.debug("[Method] create_rsa_hash")

    message = create_message(request, params)
    return hashlib.sha1(message).digest()
예제 #22
0
    def get_friends_page(self,
                         userid,
                         has_app=True,
                         fields=None,
                         page=1,
                         limit=10):
        """
        アプリを利用しているユーザーの友達情報を指定件数分返す
        件数指定がない場合は10件

        キャッシュはしない
        
        Return specified amount of the user`s friend information.By default,it will return 10 friends information.
        
        No caching.
        """
        path = '/people/%s/@friends' % userid
        params = {'format': 'json'}
        params['count'] = limit
        params['startIndex'] = 1 + limit * (page - 1)
        data = None

        if fields:
            params['fields'] = fields
        if has_app:
            params['filterBy'] = 'hasApp'
            params['filterOp'] = 'equals'
            params['filterValue'] = 'true'

        res = self.get_response(userid, path, params=params)

        if res:
            try:
                data = simplejson.loads(res)
            except TypeError:
                Log.error(LOG_MSG2, [userid, path, res])
                try:
                    data = simplejson.loads(unicode(res, "utf-8", "ignore"))
                except TypeError:
                    Log.error(LOG_MSG3, [userid, path, res])
                except Exception:
                    Log.error(LOG_MSG1, [userid, path, res])
            except Exception:
                Log.error(LOG_MSG1, [userid, path, res])
        else:
            Log.error(LOG_MSG4, [userid, path, res])

        if data == None:
            data = {
                'error': True,
                'entry': [],
                'totalResults': '0',
                'itemsPerPage': '0',
                'startIndex': '1'
            }

        return data
예제 #23
0
def get_osuser(opensocial_user_id, request=None):
    """
    osuser を opensocial_user_id から取得。該当者がいない場合は None
    24時間で自動的にキャッシュがきれる筈なので、その間隔で更新する
    """
    #リクエストキャッシュ 1リクエスト内で同じget_osuser を複数回実行しない
    if request is not None:
        Log.debug('[OPENSOCIAL] get_osuser: call. useid=%s' %
                  opensocial_user_id)
        request_cache = getattr(request, '_get_osuser_cache', {})
        if opensocial_user_id in request_cache:
            Log.debug('[OPENSOCIAL] get_osuser: request_cache hit. useid=%s' %
                      opensocial_user_id)
            return request_cache[opensocial_user_id]
    osuser = cache.get(OpenSocialUser.get_cache_key(opensocial_user_id))
    if osuser is None or (hasattr(osuser, 'friend_cache')
                          and osuser.friend_cache):
        # キャッシュに存在しないか存在してもfriendの場合
        # キャッシュに存在しない場合、タイムアウトしたならPeople APIを再度呼び出してキャッシュする
        # モデルに存在しない場合は新規作成
        update_profile_result = False
        try:
            # 存在確認だけ
            osuser = OpenSocialUser.objects.partition(opensocial_user_id).get(
                userid=opensocial_user_id)
            update_profile_result = osuser.update_profile(
                request)  # GET でPeople APIを呼び出して更新する
        except OpenSocialUser.DoesNotExist:
            # 初作成の筈(set_cacheは内部で行われない)
            try:
                osuser = OpenSocialUser.objects.partition(
                    opensocial_user_id).create(userid=opensocial_user_id)
                update_profile_result = osuser.update_profile(
                    request)  # GET でPeople APIを呼び出して更新する
            except IntegrityError:
                # duplicateすることがある
                return osuser
        if update_profile_result:
            osuser.set_cache()
    if request is not None:
        request_cache[opensocial_user_id] = osuser
        request._get_osuser_cache = request_cache
    return osuser

    # 以前の実装
    path = OpenSocialUser.get_cache_key(opensocial_user_id)
    osuser = cache.get(path, None)
    if osuser is None:  # キャッシュに存在しない
        try:
            osuser = OpenSocialUser.objects.partition(opensocial_user_id).get(
                userid=opensocial_user_id)
            osuser.set_cache()
        except OpenSocialUser.DoesNotExist:
            osuser = None
    return osuser
예제 #24
0
파일: base.py 프로젝트: arpsabbir/anchovy
 def create_record(self, auth_id, is_authorized = False, user_grade=None):
     """
     認証レコード作成
     作成したAuthDeviceモデルインスタンスを返す
     """
     Log.debug('Check is_authorized.', is_authorized)
     auth = AuthDevice.objects.partition(self.user_id).create(
             osuser_id=self.user_id, auth_id=auth_id,
             user_grade=user_grade, is_authorized=is_authorized)
     GsocialCache.set_cache(self.cache_key, None, 1) # キャッシュ削除
     return auth
예제 #25
0
def create_hmac_hash(request, params, oauth_token_secret):
    """
    create_hmac_hash
    """
    Log.debug("[Method] create_hmac_hash")

    message = create_message(request, params)
    shared_key = '%s&%s' % (oauth.escape(
        settings.CONSUMER_SECRET), oauth.escape(oauth_token_secret))
    hashed = hmac.new(shared_key, message, hashlib.sha1)
    return hashed.digest()
예제 #26
0
def create_hmac_hash(request, params, oauth_token_secret):
    """
    create_hmac_hash
    """
    Log.debug("[Method] create_hmac_hash")

    message = create_message(request, params)
    shared_key = '%s&%s' % (oauth.escape(settings.CONSUMER_SECRET),
                            oauth.escape(oauth_token_secret))
    hashed = hmac.new(shared_key, message, hashlib.sha1)
    return hashed.digest()
예제 #27
0
def _get_security_name():
    """
       Creates a key which wil be used in Cookie-security-check
       If there is no  "SECURITY_COOKIE_NAME" in settings.py,this will
       be option.
       cokkieによるセキュリティチェックのkey生成
       settings.pyに「SECURITY_COOKIE_NAME」がなければoptionになる
    """
    Log.debug("[Method] _get_security_name")

    return getattr(settings, 'SECURITY_COOKIE_NAME', 'option')
예제 #28
0
def _get_security_name():
    """
       Creates a key which wil be used in Cookie-security-check
       If there is no  "SECURITY_COOKIE_NAME" in settings.py,this will
       be option.
       cokkieによるセキュリティチェックのkey生成
       settings.pyに「SECURITY_COOKIE_NAME」がなければoptionになる
    """
    Log.debug("[Method] _get_security_name")

    return getattr(settings, 'SECURITY_COOKIE_NAME', 'option')
예제 #29
0
파일: gree.py 프로젝트: subc/anchovy
 def _get_id_from_result(self, result_json):
     """
     保存結果jsonから登録IDを取得
     """
     if result_json:
         try:
             result_dict = simplejson.loads(result_json)
         except simplejson.JSONDecodeError, e:
             Log.warn(e)
             return None
         else:
             return result_dict['entry'][0]['id']
예제 #30
0
파일: gree.py 프로젝트: arpsabbir/anchovy
 def _get_id_from_result(self, result_json):
     """
     保存結果jsonから登録IDを取得
     """
     if result_json:
         try:
             result_dict = simplejson.loads(result_json)
         except simplejson.JSONDecodeError, e:
             Log.warn(e)
             return None
         else:
             return result_dict['entry'][0]['id']
예제 #31
0
파일: gree.py 프로젝트: subc/anchovy
    def get_friends_page(self, userid, has_app=True, fields=None, page=1,
                         limit=10):
        """
        アプリを利用しているユーザーの友達情報を指定件数分返す
        件数指定がない場合は10件

        キャッシュはしない
        
        Return specified amount of the user`s friend information.By default,it will return 10 friends information.
        
        No caching.
        """
        path = '/people/%s/@friends' % userid
        params = {'format': 'json'}
        params['count'] = limit
        params['startIndex'] = 1 + limit * (page - 1)
        data = None

        if fields:
            params['fields'] = fields
        if has_app:
            params['filterBy'] = 'hasApp'
            params['filterOp'] = 'equals'
            params['filterValue'] = 'true'

        res = self.get_response(userid, path, params=params)

        if res:
            try:
                data = simplejson.loads(res)
            except TypeError:
                Log.error(LOG_MSG2, [userid, path, res])
                try:
                    data = simplejson.loads(unicode(res, "utf-8", "ignore"))
                except TypeError:
                    Log.error(LOG_MSG3, [userid, path, res])
                except Exception:
                    Log.error(LOG_MSG1, [userid, path, res])
            except Exception:
                Log.error(LOG_MSG1, [userid, path, res])
        else:
            Log.error(LOG_MSG4, [userid, path, res])

        if data == None:
            data = {'error': True,
                    'entry': [],
                    'totalResults': '0',
                    'itemsPerPage': '0',
                    'startIndex': '1'
            }

        return data
예제 #32
0
파일: admin.py 프로젝트: subc/anchovy
 def send_action(self, request, queryset):
     if len(queryset) == 1:
         # 送信?
         message_info = queryset[0]
         Log.debug(queryset[0])
         message_info.send_message(request)
         url = message_info.url
         if not url:
             url = '/m/'
         self.message_user(request, u'メッセージ[%s:%s](%s)は送信されました。' % (message_info.title, message_info.body, url))
     else:
         self.message_user(request, u'メッセージは一つだけ選択してください。')
     pass
예제 #33
0
def oauth_timeout_response(request):
    """
    For Gree
    """
    request.session.flush()
    ctxt = _oauth_reauth_context(request)
    if request.device.is_ios and re.search(r'^6', request.device.version):
        Log.debug("[Method] oauth_timeout_response ios6 ")
        return HttpResponseForbidden(
            render_to_string('root/auth_redirect.html', ctxt))
    else:
        Log.debug("[Method] oauth_timeout_response ")
        return HttpResponseForbidden(
            render_to_string(settings.SMARTPHONE_ERROR_TEMPLATE, ctxt))
예제 #34
0
def oauth_timeout_response(request):
    """
    For Gree
    """
    request.session.flush()
    ctxt = _oauth_reauth_context(request)
    if request.device.is_ios and re.search(r'^6', request.device.version):
        Log.debug("[Method] oauth_timeout_response ios6 ")
        return HttpResponseForbidden(
                render_to_string('root/auth_redirect.html', ctxt))
    else:
        Log.debug("[Method] oauth_timeout_response ")
        return HttpResponseForbidden(
                render_to_string(settings.SMARTPHONE_ERROR_TEMPLATE, ctxt))
예제 #35
0
def set_thread_local_session_id(session_id):
    """
    Set Session ID  on thread local.
    セッションIDをスレッドローカルにセットする
    """
    Log.debug("""
    ##########################################################################
    # set_thread_local_session_id
    ##########################################################################
    """)

    global thread_local
    if thread_local is None:
        thread_local = threading.local()
    thread_local.session_id = session_id
예제 #36
0
 def send_action(self, request, queryset):
     if len(queryset) == 1:
         # 送信?
         message_info = queryset[0]
         Log.debug(queryset[0])
         message_info.send_message(request)
         url = message_info.url
         if not url:
             url = '/m/'
         self.message_user(
             request, u'メッセージ[%s:%s](%s)は送信されました。' %
             (message_info.title, message_info.body, url))
     else:
         self.message_user(request, u'メッセージは一つだけ選択してください。')
     pass
예제 #37
0
def _set_webview_session(request):
    Log.debug("_set_webview_session start")
    Log.debug("session_items before: %s" % request.session.items())
    request.session['is_webview'] = True
    request.session.save()
    Log.debug("session_items after: %s" % request.session.items())
    Log.debug("_set_webview_session end")
    return True
예제 #38
0
def set_thread_local_session_id(session_id):
    """
    Set Session ID  on thread local.
    セッションIDをスレッドローカルにセットする
    """
    Log.debug("""
    ##########################################################################
    # set_thread_local_session_id
    ##########################################################################
    """)

    global thread_local
    if thread_local is None:
        thread_local = threading.local()
    thread_local.session_id = session_id
예제 #39
0
def get_thread_local_session_id():
    """
    Get Session ID of thread local.
    セッションIDをスレッドローカルを取得
    """
    Log.debug("""
    ##########################################################################
    # get_thread_local_session_id
    ##########################################################################
    """)

    global thread_local
    if thread_local:
        return thread_local.session_id
    return None
예제 #40
0
def get_thread_local_session_id():
    """
    Get Session ID of thread local.
    セッションIDをスレッドローカルを取得
    """
    Log.debug("""
    ##########################################################################
    # get_thread_local_session_id
    ##########################################################################
    """)

    global thread_local
    if thread_local:
        return thread_local.session_id
    return None
예제 #41
0
def _set_webview_session(request):
    Log.debug("_set_webview_session start")
    Log.debug("session_items before: %s" % request.session.items())
    request.session['is_webview'] = True
    request.session.save()
    Log.debug("session_items after: %s" % request.session.items())
    Log.debug("_set_webview_session end")
    return True
예제 #42
0
def _oauth_reauth_context(request):
    """
    再認証誘導ページヘリダイレクト
    """
    Log.debug("[Method] _oauth_reauth_context")

    if settings.OPENSOCIAL_SANDBOX:
        domain = 'pf-sb.gree.jp'
    else:
        domain = 'pf.gree.jp'
    app_url = 'http://{}{}'.format(settings.SITE_DOMAIN, request.path)
    provider_url = 'http://{}/{}?url={}'.format(domain, settings.APP_ID, urllib.quote(app_url, '~'))
    return RequestContext(request, {
        'message': u'ユーザー認証が失敗しました。もう一度ログインしてください。',
        'back_url': provider_url,
    })
예제 #43
0
def _oauth_rekey(request, webview_flag=False):
    """
    Reconfigure the keys for Oauth
    oauth周りのキーを再設定
    """

    Log.debug("[Method] _oauth_rekey")

    Log.debug("[Method] _oauth_rekey webview_flag:%s" % webview_flag)

    if request.REQUEST.get('opensocial_viewer_id', None):
        Log.debug("[Method] _oauth_rekey flush session")
        request.session.flush()
        request.session['opensocial_userid'] = request.REQUEST[
            'opensocial_viewer_id']
        request.session['oauth_token'] = request.REQUEST['oauth_token']
        request.session['oauth_token_secret'] = request.REQUEST[
            'oauth_token_secret']
        request.session.set_expiry(60 * 30)
    if webview_flag:
        Log.debug("[Method] _oauth_rekey _set_webview_session")
        _set_webview_session(request)

    # Send information about WebView application to app_usr_agent
    # WebViewアプリ情報をapp_user_agentに
    # app_user_agent = request.REQUEST.get('X-GREE-User-Agent', '')


#いらない
#    request.session['app_user_agent'] = request.device.name
#    if request.device.is_webview:
#        request.session['is_webview'] = True

    request.session_id = request.session.session_key
    request.session.save()
    # display "the authorization success screen"
    # 認証成功画面を表示
    ctx = RequestContext(
        request, {
            'scid': request.session_id,
            'next_path': request.path,
            'is_webview': request.device.is_webview,
            'get_dict': request.GET,
            'post_dict': request.POST,
        })

    device = get_current_device()

    if device.is_webview:
        return None

    res = render_to_response(settings.SMARTPHONE_AUTH_SUCCESS_TEMPLATE, ctx)
    res.set_cookie(settings.SESSION_COOKIE_NAME, request.session_id)
    # check again
    # 心配なのでもう一つチェック
    _security_set(request, res)
    return res
예제 #44
0
파일: models.py 프로젝트: subc/anchovy
def get_osuser(opensocial_user_id, request=None):
    """
    osuser を opensocial_user_id から取得。該当者がいない場合は None
    24時間で自動的にキャッシュがきれる筈なので、その間隔で更新する
    """
    #リクエストキャッシュ 1リクエスト内で同じget_osuser を複数回実行しない
    if request is not None:
        Log.debug('[OPENSOCIAL] get_osuser: call. useid=%s' % opensocial_user_id)
        request_cache = getattr(request, '_get_osuser_cache', {})
        if opensocial_user_id in request_cache:
            Log.debug('[OPENSOCIAL] get_osuser: request_cache hit. useid=%s' % opensocial_user_id)
            return request_cache[opensocial_user_id]
    osuser = cache.get(OpenSocialUser.get_cache_key(opensocial_user_id))
    if osuser is None or (hasattr(osuser, 'friend_cache') and osuser.friend_cache):
        # キャッシュに存在しないか存在してもfriendの場合
        # キャッシュに存在しない場合、タイムアウトしたならPeople APIを再度呼び出してキャッシュする
        # モデルに存在しない場合は新規作成
        update_profile_result = False
        try:
            # 存在確認だけ
            osuser = OpenSocialUser.objects.partition(opensocial_user_id).get(userid=opensocial_user_id)
            update_profile_result = osuser.update_profile(request) # GET でPeople APIを呼び出して更新する
        except OpenSocialUser.DoesNotExist:
            # 初作成の筈(set_cacheは内部で行われない)
            try:
                osuser = OpenSocialUser.objects.partition(opensocial_user_id).create(userid=opensocial_user_id)
                update_profile_result = osuser.update_profile(request) # GET でPeople APIを呼び出して更新する
            except IntegrityError:
                # duplicateすることがある
                return osuser
        if update_profile_result:
            osuser.set_cache()
    if request is not None:
        request_cache[opensocial_user_id] = osuser
        request._get_osuser_cache = request_cache
    return osuser

    # 以前の実装
    path = OpenSocialUser.get_cache_key(opensocial_user_id)
    osuser = cache.get(path, None)
    if osuser is None:  # キャッシュに存在しない
        try:
            osuser = OpenSocialUser.objects.partition(opensocial_user_id).get(userid=opensocial_user_id)
            osuser.set_cache()
        except OpenSocialUser.DoesNotExist:
            osuser = None
    return osuser
예제 #45
0
    def get_gree_thumbnail_url(self, size_type=IMG_NORMAL):
        """
        指定したSIZE TYPEのイメージURLを返す
        """
        #self.delete_cache_thumbnail_list()
        if settings.OPENSOCIAL_DEBUG:
            url = self.LOCAL_THMBNAIL_MAPS[size_type]
        else:
            size = self.THUMBNAIL_MAPS[size_type]
            url_list = self.get_or_cache_thumbnail_list()

            try:
                url = url_list[size]
            except:
                url = None
            Log.debug("thumbnail_url(%s): %s" % (size, url))
        return url
예제 #46
0
def create_hashed_debug_user_id(request):
    """
    Creates User-id randomly from request.
    Combining HTTP_USER_AGENT and REMOTE_ADDR will create unique id.
    *This is not the decorator.oauth_signature_required will call it.

    requestから、ランダムなユーザーIDを作成する。
    HTTP_USER_AGENTと、REMOTE_ADDRから一意なIDを生成。
    ※デコレータでは無い。oauth_signature_required から呼ばれる。
    """
    Log.debug("[Method] create_hashed_debug_user_id")

    bulk_user_id = request.META.get('HTTP_USER_AGENT')
    hashed_debug_osuser_number = int(hashlib.sha1(bulk_user_id).hexdigest()[5:11], 16)
    hashed_debug_osuser_number %= 100000000
    opensocial_debug_user_id = hashed_debug_osuser_number  + 9900000000
    return str(opensocial_debug_user_id)
예제 #47
0
파일: views.py 프로젝트: arpsabbir/anchovy
 def _get_opensocial_viewer(self, request):
     """
     requestから「opensocial_viewer_id」を取得する
     """
     if hasattr(request, 'opensocial_viewer_id'):
         opensocial_viewer_id = request.opensocial_viewer_id
     else:
         opensocial_viewer_id = request.REQUEST.get('opensocial_viewer_id',
                                                    None)
         if not opensocial_viewer_id:
             if 'opensocial_userid' in request.session:
                 opensocial_viewer_id = request.session['opensocial_userid']
             else:
                 raise SessionError('opensocial_userid is not in session.')
     Log.debug("_get_opensocial_viewer id: %s" % opensocial_viewer_id)
     Log.debug("_get_opensocial_viewer session: %s" % request.session)
     return opensocial_viewer_id
예제 #48
0
파일: mixin.py 프로젝트: subc/anchovy
    def get_gree_thumbnail_url(self, size_type=IMG_NORMAL):
        """
        指定したSIZE TYPEのイメージURLを返す
        """
        #self.delete_cache_thumbnail_list()
        if settings.OPENSOCIAL_DEBUG:
            url = self.LOCAL_THMBNAIL_MAPS[size_type]
        else:
            size = self.THUMBNAIL_MAPS[size_type]
            url_list = self.get_or_cache_thumbnail_list()

            try:
                url = url_list[size]
            except:
                url = None
            Log.debug("thumbnail_url(%s): %s" % (size, url))
        return url
예제 #49
0
def _is_need_oauth_check_query(request):
    """
    oauth_check_queryが必要かを判定

    output
        True: 必要
        False: 不必要
    """
    Log.debug("[Method] _is_need_oauth_check_query")

    must_path_list = getattr(settings, 'OAUTH_MUST_PATH_QUERY', [])
    path = request.path
    for p in must_path_list:
        if path.startswith(p):
            return True

    return False
예제 #50
0
    def set_cache(cls, cache_key, cache_value, timeout=None):
        """
        キャッシュにセットする

        アプリ側のsettingsのtimeoutがあれば使う
        なければgsocialのsettingのtimeoutを使う
        """
        if timeout == None:
            # ここは普通のif文に変更した方がよいかも
            try:
                timeout = settings.GSOCIAL_CACHE_TIMEOUT
            except AttributeError:
                Log.info('GSOCIAL_CACHE_TIMEOUT isn\'t in settings.', timeout)
                timeout = DEFALT_CACHE_TIMEOUT

        Log.debug('Check timeout.', timeout)
        cache.set(cache_key, cache_value, timeout)
예제 #51
0
def create_message(request, params):
    """
    create_message
    """
    Log.debug("[Method] create_message")

    host = request.get_host()
    host = host.split(',')[0]
    base_url = request.is_secure(
    ) and 'https://' or 'http://' + host + request.path
    oauth_request = Request2(request.method, base_url, params)
    message = '&'.join((
        oauth.escape(oauth_request.get_normalized_http_method()),
        oauth.escape(oauth_request.get_normalized_http_url()),
        oauth.escape(oauth_request.get_normalized_parameters()),
    ))
    return message
예제 #52
0
def _oauth_reauth_context(request):
    """
    再認証誘導ページヘリダイレクト
    """
    Log.debug("[Method] _oauth_reauth_context")

    if settings.OPENSOCIAL_SANDBOX:
        domain = 'pf-sb.gree.jp'
    else:
        domain = 'pf.gree.jp'
    app_url = 'http://{}{}'.format(settings.SITE_DOMAIN, request.path)
    provider_url = 'http://{}/{}?url={}'.format(domain, settings.APP_ID,
                                                urllib.quote(app_url, '~'))
    return RequestContext(request, {
        'message': u'ユーザー認証が失敗しました。もう一度ログインしてください。',
        'back_url': provider_url,
    })
예제 #53
0
파일: views.py 프로젝트: subc/anchovy
 def _get_opensocial_viewer(self, request):
     """
     requestから「opensocial_viewer_id」を取得する
     """
     if hasattr(request, 'opensocial_viewer_id'):
         opensocial_viewer_id = request.opensocial_viewer_id
     else:
         opensocial_viewer_id = request.REQUEST.get(
             'opensocial_viewer_id', None)
         if not opensocial_viewer_id:
             if 'opensocial_userid' in request.session:
                 opensocial_viewer_id = request.session['opensocial_userid']
             else:
                 raise SessionError('opensocial_userid is not in session.')
     Log.debug("_get_opensocial_viewer id: %s" % opensocial_viewer_id)
     Log.debug("_get_opensocial_viewer session: %s" % request.session)
     return opensocial_viewer_id
예제 #54
0
def _is_need_oauth_check_query(request):
    """
    oauth_check_queryが必要かを判定

    output
        True: 必要
        False: 不必要
    """
    Log.debug("[Method] _is_need_oauth_check_query")

    must_path_list = getattr(settings, 'OAUTH_MUST_PATH_QUERY', [])
    path = request.path
    for p in must_path_list:
        if path.startswith(p):
            return True

    return False
예제 #55
0
파일: models.py 프로젝트: subc/anchovy
    def send_message(self, request):
        Log.debug('send_message Base.')
        # 自身の持つデータを全員に送信する
        #opensocial_users = OpenSocialUser.objects.all()
        player_list = DailyAccessLog.objects.all().values('osuser_id').distinct()

        send_player_list = []
        for player_dict in player_list:
            send_player_list.append(player_dict['osuser_id'])

        #message = Message(request)

        #container = osrequest.Container(request)
        #for opensocial_user in opensocial_users:
        for user in send_player_list:
            # 全員に自身のメッセージを送信
            #message.send(None, opensocial_user.userid, self.title, self.body, self.url)
            Message().send(None, user, self.title, self.body, self.url)
예제 #56
0
파일: base.py 프로젝트: subc/anchovy
    def set_cache(cls, cache_key, cache_value, timeout=None):
        """
        キャッシュにセットする

        アプリ側のsettingsのtimeoutがあれば使う
        なければgsocialのsettingのtimeoutを使う
        """
        if timeout == None:
            # ここは普通のif文に変更した方がよいかも
            try:
                timeout = settings.GSOCIAL_CACHE_TIMEOUT
            except AttributeError:
                Log.info('GSOCIAL_CACHE_TIMEOUT isn\'t in settings.', timeout)
                timeout = DEFALT_CACHE_TIMEOUT


        Log.debug('Check timeout.', timeout)
        cache.set(cache_key, cache_value, timeout)
예제 #57
0
def create_hashed_debug_user_id(request):
    """
    Creates User-id randomly from request.
    Combining HTTP_USER_AGENT and REMOTE_ADDR will create unique id.
    *This is not the decorator.oauth_signature_required will call it.

    requestから、ランダムなユーザーIDを作成する。
    HTTP_USER_AGENTと、REMOTE_ADDRから一意なIDを生成。
    ※デコレータでは無い。oauth_signature_required から呼ばれる。
    """
    Log.debug("[Method] create_hashed_debug_user_id")

    bulk_user_id = request.META.get('HTTP_USER_AGENT')
    hashed_debug_osuser_number = int(
        hashlib.sha1(bulk_user_id).hexdigest()[5:11], 16)
    hashed_debug_osuser_number %= 100000000
    opensocial_debug_user_id = hashed_debug_osuser_number + 9900000000
    return str(opensocial_debug_user_id)
예제 #58
0
def _oauth_rekey(request, webview_flag=False):
    """
    Reconfigure the keys for Oauth
    oauth周りのキーを再設定
    """

    Log.debug("[Method] _oauth_rekey")

    Log.debug("[Method] _oauth_rekey webview_flag:%s" % webview_flag)

    if request.REQUEST.get('opensocial_viewer_id', None):
        Log.debug("[Method] _oauth_rekey flush session")
        request.session.flush()
        request.session['opensocial_userid'] = request.REQUEST['opensocial_viewer_id']
        request.session['oauth_token'] = request.REQUEST['oauth_token']
        request.session['oauth_token_secret'] = request.REQUEST['oauth_token_secret']
        request.session.set_expiry(60 * 30)
    if webview_flag:
        Log.debug("[Method] _oauth_rekey _set_webview_session")
        _set_webview_session(request)


    # Send information about WebView application to app_usr_agent
    # WebViewアプリ情報をapp_user_agentに
    # app_user_agent = request.REQUEST.get('X-GREE-User-Agent', '')

#いらない
#    request.session['app_user_agent'] = request.device.name
#    if request.device.is_webview:
#        request.session['is_webview'] = True

    request.session_id = request.session.session_key
    request.session.save()
    # display "the authorization success screen"
    # 認証成功画面を表示
    ctx = RequestContext(request, {
        'scid': request.session_id,
        'next_path': request.path,
        'is_webview': request.device.is_webview,
        'get_dict': request.GET,
        'post_dict': request.POST,
    })

    device = get_current_device()

    if device.is_webview:
        return None

    res = render_to_response(settings.SMARTPHONE_AUTH_SUCCESS_TEMPLATE, ctx)
    res.set_cookie(settings.SESSION_COOKIE_NAME, request.session_id)
    # check again
    # 心配なのでもう一つチェック
    _security_set(request, res)
    return res