Esempio n. 1
0
    def calc_sha1_by_file(file_path):
        """
        :rtype : dict
        :param file_path: 欲计算其sha1 hash值的文件路径
        :return: lower格式的sha1 hash值
        """
        result = dict()
        result['state'] = Common.exchange_state(20000)

        if not os.path.isfile(file_path):
            result['state'] = Common.exchange_state(40401)
            result['state']['sub']['zh-cn'] = ''.join([
                result['state']['sub']['zh-cn'], ',目标"', file_path, '"不是一个有效文件'
            ])
            raise ji.JITError(json.dumps(result))

        with open(file_path, 'rb') as f:
            try:
                sha1_obj = hashlib.sha1()
                sha1_obj.update(f.read())
                return sha1_obj.hexdigest()
            except Exception, e:
                result['state'] = Common.exchange_state(50004)
                result['state']['sub']['zh-cn'] = ''.join(
                    [result['state']['sub']['zh-cn'], ',详细信息: ', e.message])
                raise ji.JITError(json.dumps(result))
Esempio n. 2
0
    def exchange_state(code):
        """
        :rtype : dict
        :param code: 状态码
        :return: dict格式返回状态信息
        """
        if not isinstance(code, int):
            result = Common.exchange_state(50001)
            raise ji.JITError(json.dumps(result, ensure_ascii=False))

        trunk_code = int(code / 100)
        if str(trunk_code) not in index_state['trunk']:
            result = Common.exchange_state(50002)
            raise ji.JITError(json.dumps(result, ensure_ascii=False))

        result = copy.copy(index_state['trunk'][(str(trunk_code))])

        if str(code) in index_state['branch']:
            result['sub'] = copy.copy(index_state["branch"][(str(code))])

        return result
Esempio n. 3
0
    def calc_sha1_by_fd(fd):
        """
        :rtype : dict
        :param fd: 欲计算其sha1 hash值的文件描述符
        :return: lower格式的sha1 hash值
        """
        result = dict()
        result['state'] = Common.exchange_state(20000)

        try:
            sha1_obj = hashlib.sha1()
            sha1_obj.update(fd.read())
            sha1 = sha1_obj.hexdigest()
        except Exception, e:
            result['state'] = Common.exchange_state(50004)
            result['state']['sub']['zh-cn'] = ''.join(
                [result['state']['sub']['zh-cn'], ',详细信息: ', e.message])
            raise ji.JITError(json.dumps(result))
Esempio n. 4
0
class Utils(object):

    exit_flag = False
    thread_counter = 0

    @staticmethod
    def shell_cmd(cmd):
        try:
            exit_status, output = commands.getstatusoutput(cmd)

            return exit_status, str(output)

        except Exception as e:
            return -1, e.message

    @classmethod
    def signal_handle(cls, signum=0, frame=None):
        cls.exit_flag = True
        raise RuntimeError('Shutdown app!')

    @staticmethod
    def dumps2response(func):
        """
        视图装饰器
        http://dormousehole.readthedocs.org/en/latest/patterns/viewdecorators.html
        """
        @wraps(func)
        def _dumps2response(*args, **kwargs):
            ret = func(*args, **kwargs)

            if func.func_name != 'r_before_request' and ret is None:
                ret = dict()
                ret['state'] = ji.Common.exchange_state(20000)

            if isinstance(ret, dict) and 'state' in ret:
                response = make_response()
                response.data = json.dumps(ret, ensure_ascii=False)
                response.status_code = int(ret['state']['code'])
                if 'redirect' in ret and request.args.get(
                        'auto_redirect', 'True') == 'True':
                    response.status_code = int(ret['redirect'].get(
                        'code', ret['state']['code']))
                    response.headers['location'] = ret['redirect'].get(
                        'location', request.host_url)
                    # 参考链接:
                    # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.autocorrect_location_header
                    # 变量操纵位置 werkzeug/wrappers.py
                    response.autocorrect_location_header = False
                return response

            if isinstance(ret, Response):
                return ret

        return _dumps2response

    @staticmethod
    def superuser(func):
        @wraps(func)
        def _superuser(*args, **kwargs):
            if not g.superuser:
                ret = dict()
                ret['state'] = ji.Common.exchange_state(40301)
                return ret

            return func(*args, **kwargs)

        return _superuser

    @staticmethod
    def generate_token(uid, ttl=app.config['token_ttl'], audience=None):
        payload = {
            'iat': ji.Common.ts(),  # 创建于
            'nbf': ji.Common.ts(),  # 在此之前不可用
            'exp': ji.Common.ts() + ttl,  # 过期时间
            'uid': uid
        }

        if audience is not None:
            payload['aud'] = audience

        return jwt.encode(payload=payload,
                          key=app.config['jwt_secret'],
                          algorithm=app.config['jwt_algorithm'])

    @staticmethod
    def verify_token(token, audience=None):
        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        try:
            if audience is None:
                payload = jwt.decode(jwt=token,
                                     key=app.config['jwt_secret'],
                                     algorithms=app.config['jwt_algorithm'])
            else:
                payload = jwt.decode(jwt=token,
                                     key=app.config['jwt_secret'],
                                     algorithms=app.config['jwt_algorithm'],
                                     audience=audience)

            return payload
        except jwt.InvalidTokenError, e:
            logger.error(e.message)
        ret['state'] = ji.Common.exchange_state(41208)
        raise ji.JITError(json.dumps(ret))