Skip to content
This repository was archived by the owner on Jun 22, 2022. It is now read-only.
Open

Py2 #22

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions jms/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,21 +128,21 @@ class AppAccessKey(AccessKey):
"""使用Access key来认证"""

def __init__(self, key_file=None, value=None, id=None, secret=None):
super().__init__(id=id, secret=secret)
super(AppAccessKey, self).__init__(id=id, secret=secret)
self._key_file = key_file
self.key_env = 'COCO_ACCESS_KEY'
self.key_value = value
self.sep = ":"
self.silent = False

def load_from_conf_env(self):
super().load_from_env(self.key_env, sep=self.sep, silent=self.silent)
super(AppAccessKey, self).load_from_env(self.key_env, sep=self.sep, silent=self.silent)

def load_from_conf_val(self):
super().load_from_val(self.key_value, sep=self.sep, silent=self.silent)
super(AppAccessKey, self).load_from_val(self.key_value, sep=self.sep, silent=self.silent)

def load_from_conf_file(self):
super().load_from_f(self._key_file, sep=self.sep, silent=self.silent)
super(AppAccessKey, self).load_from_f(self._key_file, sep=self.sep, silent=self.silent)

def load(self, **kwargs):
"""Should return access_key_id, access_key_secret"""
Expand All @@ -156,4 +156,4 @@ def load(self, **kwargs):
return None

def save_to_file(self):
return super().save_to_f(self._key_file)
return super(AppAccessKey, self).save_to_f(self._key_file)
81 changes: 81 additions & 0 deletions jms/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

"""
兼容Python版本
"""

import sys

is_py2 = (sys.version_info[0] == 2)
is_py3 = (sys.version_info[0] == 3)


try:
import simplejson as json
except (ImportError, SyntaxError):
import json


if is_py2:

def to_bytes(data):
"""若输入为unicode, 则转为utf-8编码的bytes;其他则原样返回。"""
if isinstance(data, unicode):
return data.encode('utf-8')
else:
return data

def to_string(data):
"""把输入转换为str对象"""
return to_bytes(data)

def to_unicode(data):
"""把输入转换为unicode,要求输入是unicode或者utf-8编码的bytes。"""
if isinstance(data, bytes):
return data.decode('utf-8')
else:
return data

def stringify(input):
if isinstance(input, dict):
return dict([(stringify(key), stringify(value)) for key,value in input.iteritems()])
elif isinstance(input, list):
return [stringify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input

builtin_str = str
bytes = str
str = unicode


elif is_py3:

def to_bytes(data):
"""若输入为str(即unicode),则转为utf-8编码的bytes;其他则原样返回"""
if isinstance(data, str):
return data.encode(encoding='utf-8')
else:
return data

def to_string(data):
"""若输入为bytes,则认为是utf-8编码,并返回str"""
if isinstance(data, bytes):
return data.decode('utf-8')
else:
return data

def to_unicode(data):
"""把输入转换为unicode,要求输入是unicode或者utf-8编码的bytes。"""
return to_string(data)

def stringify(input):
return input

builtin_str = str
bytes = bytes
str = str
22 changes: 22 additions & 0 deletions jms/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#


API_URL_MAPPING = {
'terminal-register': '/api/applications/v1/terminal/register/',
'terminal-heatbeat': '/api/applications/v1/terminal/heatbeat/',
'send-proxy-log': '/api/audits/v1/proxy-log/receive/',
'finish-proxy-log': '/api/audits/v1/proxy-log/%s/',
'send-command-log': '/api/audits/v1/command-log/',
'send-record-log': '/api/audits/v1/record-log/',
'user-auth': '/api/users/v1/auth/',
'my-assets': '/api/perms/v1/user/assets/',
'my-asset-groups': '/api/perms/v1/user/my/asset-groups/',
'my-asset-groups-assets': '/api/perms/v1/user/my/asset-groups-assets/',
'assets-of-group': '/api/perms/v1/user/my/asset-group/%s/assets/',
'my-profile': '/api/users/v1/profile/',
'system-user-auth-info': '/api/assets/v1/system-user/%s/auth-info/',
'validate-user-asset-permission':
'/api/perms/v1/asset-permission/user/validate/',
}
20 changes: 10 additions & 10 deletions jms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .utils import ssh_key_string_to_obj


class Decoder:
class Decoder(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
if hasattr(self, k):
Expand All @@ -23,7 +23,10 @@ def from_json(cls, json_dict):
try:
if len(v.strip().split()) == 2:
v += " +0000"
v = datetime.datetime.strptime(v, "%Y-%m-%d %H:%M:%S %z")
try:
v = datetime.datetime.strptime(v, "%Y-%m-%d %H:%M:%S %z")
except ValueError:
v = datetime.datetime.strptime(' '.join(v.split()[:2]), "%Y-%m-%d %H:%M:%S")
except TypeError:
pass
if hasattr(self, k):
Expand Down Expand Up @@ -85,7 +88,7 @@ def from_json(cls, json_dict):
json_dict["system_users_granted"] = system_users_granted
except KeyError:
pass
return super().from_json(json_dict)
return super(Asset, cls).from_json(json_dict)

@property
def system_users_name_list(self):
Expand Down Expand Up @@ -135,7 +138,7 @@ class AssetGroup(Decoder):
def from_json(cls, json_dict):
assets_granted = Asset.from_multi_json(json_dict["assets_granted"])
json_dict["assets_granted"] = assets_granted
return super().from_json(json_dict)
return super(AssetGroup, cls).from_json(json_dict)

def __str__(self):
return self.name
Expand Down Expand Up @@ -200,7 +203,7 @@ class Domain(Decoder):

@classmethod
def from_json(cls, json_dict):
data = super().from_json(json_dict)
data = super(Domain, cls).from_json(json_dict)
gateways = Gateway.from_multi_json(json_dict["gateways"])
data.gateways = gateways
return data
Expand Down Expand Up @@ -232,9 +235,6 @@ class CommandFilterRule(Decoder):

DENY, ALLOW, UNKNOWN = range(3)

def __init__(self, **kwargs):
super().__init__(**kwargs)

@property
def _pattern(self):
if self.__pattern:
Expand Down Expand Up @@ -273,7 +273,7 @@ class ServiceAccount(Decoder):

@classmethod
def from_json(cls, json_dict):
data = super().from_json(json_dict)
data = super(ServiceAccount, cls).from_json(json_dict)
access_key = AccessKey.from_json(json_dict.get("access_key", {}))
data.access_key = access_key
return data
Expand All @@ -291,7 +291,7 @@ class TerminalRegistration(Terminal):

@classmethod
def from_json(cls, json_dict):
data = super().from_json(json_dict)
data = super(TerminalRegistration, cls).from_json(json_dict)
service_account = ServiceAccount.from_json(json_dict.get("service_account", {}))
data.service_account = service_account
return data
6 changes: 3 additions & 3 deletions jms/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@


class Service(UsersMixin, TerminalMixin, PermsMixin, AssetsMixin,
AuditsMixin, OrgMixin):
AuditsMixin, OrgMixin, object):
def __init__(self, endpoint, auth=None):
self.endpoint = endpoint
self._auth = auth
Expand All @@ -46,7 +46,7 @@ class AppService(Service):
auth_class = AccessKeyAuth

def __init__(self, config):
super().__init__(config['CORE_HOST'])
super(AppService, self).__init__(config['CORE_HOST'])
self.config = config
self.access_key = self.access_key_class(config['ACCESS_KEY_FILE'])

Expand Down Expand Up @@ -109,7 +109,7 @@ def save_access_key(self):
class UserService(Service):

def __init__(self, endpoint):
super().__init__(endpoint)
super(UserService, self).__init__(endpoint)
self.username = ""
self.password = ""
self.pubkey = ""
Expand Down
1 change: 1 addition & 0 deletions jms/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import paramiko
import pyte
import pytz
from .compat import str
from email.utils import formatdate


Expand Down
13 changes: 9 additions & 4 deletions test/test_user_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@
password = 'redhat'
endpoint = 'http://localhost:8080'

user_service = UserService(app_name='coco', endpoint=endpoint)

user, token = user_service.login(username=username, password=password,
public_key=None, login_type='ST', remote_addr='2.2.2.2')
user_service = UserService(endpoint=endpoint)
data = {
'username': username,
'password': password,
'public_key': None,
'login_type': 'ST',
'remote_addr': '2.2.2.2'
}
user, token = user_service.login(data)
print(user)
print(token)

Expand Down