Beispiel #1
0
def __check_login__(token):
    """
    platform兼容各平台
    统计总平台与各平台设备hgetall,
    通过placeholder来限制各平台设备数
    备注:映射关系 {email + platform + place --> ssid}无法设置过期时间,
    当APP内用户量庞大时需要定时清理ssid为None的epp映射关系,一期暂时不做清理
    :return:
    """
    key_pix = r.get(token)
    if key_pix:
        # 是否注销登录
        no_valid_token = jwt.decode(
            token,
            signers=[jws.HmacSha(bits=256, key=web['token_key'] + key_pix)])
        # 校验token是否有效
        if no_valid_token['valid']:
            now_timestamp = time.time()
            if no_valid_token['payload']['exp'] > now_timestamp:
                return no_valid_token['payload']['username']
            else:
                r.delete(token)
                return False
        else:
            r.delete(token)
            return False
    else:
        return False
Beispiel #2
0
def de_token(token):
    if token is None:
        return None
    token = str(token)
    token_key_pix = redis_service.get(token)
    if token_key_pix is None:
        return None
    token_keys = web['token_key'] + token_key_pix
    no_valid_token = jwt.decode(
        token, signers=[jws.HmacSha(bits=256, key=token_keys)])
    if no_valid_token['valid']:
        return no_valid_token['payload']
    else:
        return None
Beispiel #3
0
    def POST(self):
        content_type = web.ctx.env.get("CONTENT_TYPE", "")
        if content_type == "application/jwt":
            token = jwt.decode(web.data(), signers=[jws.HmacSha(keydict=CLIENT_KEYS)])
            if not token["valid"]:
                print >>web.webapi.debug, (
                    "Bad signature from %s!  Ignoring results." % token["headers"].get("kid", "(unknown)")
                )
                raise web.badrequest("bad signature")
            r = token["payload"]
        elif REQUIRE_SIGNED:
            print >>web.webapi.debug, ("Signature required but plain JSON received.  " "Ignoring results.")
            raise web.badrequest("signature required")
        else:
            r = json.loads(web.data())

        # All dates/datetimes are stored in UTC
        result = {"runstamp": datetime.now(tz_utc).strftime("%Y-%m-%d %H:%M:%S")}

        try:
            result["starttime"] = int(r["data"]["starttime"])
            result["throbberstart"] = int(r["data"]["throbberstart"])
            result["throbberstop"] = int(r["data"]["throbberstop"])
            result["cached"] = int(r["data"]["cached"])
            result["blddate"] = datetime.utcfromtimestamp(float(r["data"]["blddate"])).strftime("%Y-%m-%d %H:%M:%S")
            result["rejected"] = int(r["data"]["rejected"])
        except ValueError:
            print >>web.webapi.debug, "Request: %s, %s" % ((r, traceback.format_exc()))
            raise web.badrequest()

        for key in (
            "phoneid",
            "testname",
            "revision",
            "author",
            "bldtype",
            "productname",
            "productversion",
            "osver",
            "machineid",
        ):
            if r["data"][key] and not is_clean(r["data"][key]):
                print >>web.webapi.debug, ("Request %s: %s %s is not clean" % (r["data"], key, r["data"][key]))
                raise web.badrequest()
            result[key] = r["data"][key]

        autophonedb.db.insert(autophonedb.SQL_TABLE, **result)
Beispiel #4
0
    def POST(self):
        content_type = web.ctx.env.get('CONTENT_TYPE', '')
        if content_type == 'application/jwt':
            token = jwt.decode(web.data(),
                               signers=[jws.HmacSha(keydict=CLIENT_KEYS)])
            if not token['valid']:
                print >> web.webapi.debug, (
                    'Bad signature from %s!  Ignoring results.' %
                    token['headers'].get('kid', '(unknown)'))
                raise web.badrequest('bad signature')
            r = token['payload']
        elif REQUIRE_SIGNED:
            print >> web.webapi.debug, (
                'Signature required but plain JSON received.  '
                'Ignoring results.')
            raise web.badrequest('signature required')
        else:
            r = json.loads(web.data())

        # All dates/datetimes are stored in UTC
        result = {'runstamp': datetime.now(tz_utc).strftime("%Y-%m-%d %H:%M:%S")}

        try:
            result['starttime'] = int(r['data']['starttime'])
            result['throbberstart'] = int(r['data']['throbberstart'])
            result['throbberstop'] = int(r['data']['throbberstop'])
            result['cached'] = int(r['data']['cached'])
            result['blddate'] = datetime.utcfromtimestamp(
                float(r["data"]["blddate"])).strftime("%Y-%m-%d %H:%M:%S")
            result['rejected'] = int(r['data']['rejected'])
        except ValueError:
            print >> web.webapi.debug, 'Request: %s, %s' % (
                (r, traceback.format_exc()))
            raise web.badrequest()

        for key in ('phoneid', 'testname', 'revision', 'bldtype', 'productname',
                    'productversion', 'osver', 'machineid'):
            if not is_clean(r['data'][key]):
                print >> web.webapi.debug, (
                    'Request %s: %s %s is not clean' % (
                        r['data'], key, r['data'][key]))
                raise web.badrequest()
            result[key] = r['data'][key]

        autophonedb.db.insert(autophonedb.SQL_TABLE, **result)
Beispiel #5
0
    def test_hmac_sha256(self):
        self.assertEqual(jwt.decode(self.jws_repr,
                                    signers=[jws.HmacSha(key=self.key)]),
                         { 'headers': {u'alg': u'HS256', u'typ': u'JWT'},
                           'payload': self.payload,
                           'valid': True })

        # test encoding and decoding using key id
        keydict = {'secret': self.key, 'secret2': 'abcd'}
        self.assertEqual(jwt.decode(
                jwt.encode(self.payload,
                           signer=jws.HmacSha(keydict=keydict,
                                                  key_id='secret')),
                signers=[jws.HmacSha(keydict=keydict)]),
                         { 'headers': {u'alg': u'HS256', u'typ': u'JWT',
                                       u'kid': u'secret'},
                           'payload': self.payload,
                           'valid': True })

        # Test some errors in encoding.
        self.assertRaises(jws.KeyRequiredException, jwt.encode,
                          self.payload, signer=jws.HmacSha())

        self.assertRaises(jws.KeyRequiredException, jwt.encode,
                          self.payload,
                          signer=jws.HmacSha(keydict=keydict,
                                                 key_id='notfound'))

        # Test encoding with no kid.

        msg = jwt.encode(self.payload, jws.HmacSha(key=self.key))
        # Just default key given to decoder.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key=self.key)])['valid'])
        # Default key and random entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key=self.key, keydict={'foo': 'bar'})])['valid'])
        # Default key, nonmatching default key id, random entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key=self.key, key_id='foo', keydict={'foo': 'bar'})])['valid'])
        # No default key, nonmatching default key id, random entry in keydict.
        self.assertFalse(jwt.decode(msg, signers=[jws.HmacSha(key_id='foo', keydict={'foo': 'bar'})])['valid'])
        # No default key, matching default key id, random entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key_id='foo', keydict={'foo': self.key})])['valid'])
        # No key given to decoder.
        self.assertFalse(jwt.decode(msg, signers=[jws.HmacSha()])['valid'])
        self.assertFalse(jwt.decode(msg, signers=[jws.HmacSha(keydict={'foo': 'bar'})])['valid'])

        # With kid.
        msg = jwt.encode(self.payload, jws.HmacSha(key=self.key, key_id=self.key_id))
        # Default matching key.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key=self.key)])['valid'])
        # Nonmatching default key, matching entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key='nope', keydict={self.key_id: self.key})])['valid'])
        # Default key and random entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key=self.key, keydict={'foo': 'bar'})])['valid'])
        # No default key, nonmatching default key id, random entry in keydict.
        self.assertFalse(jwt.decode(msg, signers=[jws.HmacSha(key_id='foo', keydict={'foo': 'bar'})])['valid'])
        # No default key, matching default key id, random entry in keydict.
        self.assertTrue(jwt.decode(msg, signers=[jws.HmacSha(key_id='foo', keydict={'foo': self.key})])['valid'])

        msg = jwt.encode(self.payload, signer=jws.HmacSha(
                key=self.key, key_id='secret'))
        self.assertFalse(jwt.decode(msg, signers=[jws.HmacSha(
                    keydict={'wrongkid': self.key})])['valid'])