Skip to content

Commit f4bbc1d

Browse files
author
Inbal Tako
committed
Restructure project
1 parent b9cd3f5 commit f4bbc1d

19 files changed

Lines changed: 96 additions & 229 deletions

securenative/api_manager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@ def __init__(self, event_manager, securenative_options):
1515
def track(self, event_options):
1616
Logger.debug("Track event call")
1717
event = SDKEvent(event_options, self.options)
18-
self.event_manager.send_async(event, ApiRoute.TRACK, True)
18+
self.event_manager.send_async(event, ApiRoute.TRACK.value)
1919

2020
def verify(self, event_options):
2121
Logger.debug("Verify event call")
2222
event = SDKEvent(event_options, self.options)
2323
try:
24-
self.event_manager.send_sync(VerifyResult, event, ApiRoute.VERIFY)
24+
self.event_manager.send_sync(event, ApiRoute.VERIFY.value, False)
2525
except Exception as e:
2626
Logger.debug("Failed to call verify; {}".format(e))
27-
if self.options.fail_over_startegy is FailOverStrategy.FAIL_OPEN:
28-
return VerifyResult(RiskLevel.LOW, 0, None)
29-
return VerifyResult(RiskLevel.HIGH, 1, None)
27+
if self.options.fail_over_strategy is FailOverStrategy.FAIL_OPEN.value:
28+
return VerifyResult(RiskLevel.LOW.value, 0, None)
29+
return VerifyResult(RiskLevel.HIGH.value, 1, None)

securenative/config/configuration_builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self):
1313
self.auto_send = True
1414
self.disable = False
1515
self.log_level = "CRITICAL"
16-
self.fail_over_strategy = FailOverStrategy.FAIL_OPEN
16+
self.fail_over_strategy = FailOverStrategy.FAIL_OPEN.value
1717

1818
@staticmethod
1919
def default_config_builder():

securenative/config/configuration_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
class ConfigurationManager(object):
88
DEFAULT_CONFIG_FILE = "securenative.ini"
99
CUSTOM_CONFIG_FILE_ENV_NAME = "SECURENATIVE_COMFIG_FILE"
10-
config = ConfigParser.ConfigParser()
10+
config = ConfigParser()
1111

1212
@classmethod
1313
def read_resource_file(cls, resource_path):

securenative/config/securenative_options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
class SecureNativeOptions(object):
55

66
def __init__(self, api_key=None, api_url=None, interval=1000, max_events=1000, timeout=1500, auto_send=True,
7-
disable=False, log_level="CRITICAL", fail_over_strategy=FailOverStrategy.FAIL_OPEN):
7+
disable=False, log_level="CRITICAL", fail_over_strategy=FailOverStrategy.FAIL_OPEN.value):
88
self.api_key = api_key
99
self.api_url = api_url
1010
self.interval = interval

securenative/event_manager.py

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ def __init__(self, options=SecureNativeOptions(), http_client=None):
3333
self.attempt = 0
3434
self.coefficients = [1, 1, 2, 3, 5, 8, 13]
3535
self.scheduler = None
36+
self.thread = None
3637

3738
if self.options.auto_send and not self.options.disable:
3839
interval_seconds = max(options.interval // 1000, 1)
@@ -45,7 +46,7 @@ def send_async(self, event, resource_path):
4546

4647
item = QueueItem(
4748
resource_path,
48-
json.dumps(event.as_dict()),
49+
json.dumps(EventManager.serialize(event)),
4950
False
5051
)
5152

@@ -65,17 +66,17 @@ def send_sync(self, event, resource_path, retry):
6566
Logger.warning("SDK is disabled. no operation will be performed")
6667
return
6768

68-
Logger.debug("Attempting to send event {}".format(event.as_dict()))
69+
Logger.debug("Attempting to send event {}".format(event))
6970
res = self.http_client.post(
7071
resource_path,
71-
json.dumps(event.as_dict())
72+
json.dumps(EventManager.serialize(event))
7273
)
73-
if res.status != 200:
74-
Logger.info("SecureNative failed to call endpoint {} with event {}. adding back to queue")
75-
74+
if res.status_code != 200:
75+
Logger.info("SecureNative failed to call endpoint {} with event {}. adding back to queue".format(
76+
resource_path, event))
7677
item = QueueItem(
7778
resource_path,
78-
json.dumps(event.as_dict()),
79+
json.dumps(EventManager.serialize(event)),
7980
retry
8081
)
8182
self.queue.insert(0, item)
@@ -90,10 +91,10 @@ def _send_events(self):
9091
for item in self.queue:
9192
try:
9293
res = self.http_client.post(item.url, item.body)
93-
if res.status is 401:
94+
if res.status_code is 401:
9495
item.retry = False
95-
elif res.status != 200:
96-
raise SecureNativeHttpException(res.status)
96+
elif res.status_code != 200:
97+
raise SecureNativeHttpException(res.status_code)
9798

9899
Logger.debug("Event successfully sent; {}".format(item.body))
99100
self.queue.remove(item)
@@ -116,9 +117,10 @@ def start_event_persist(self):
116117
if self.options.auto_send or self.send_enabled:
117118
self.send_enabled = True
118119
try:
120+
119121
self.scheduler = sched.scheduler(time.time, time.sleep)
120122
self.scheduler.enter(self.options.interval, 1, self._send_events)
121-
self.scheduler.run()
123+
self.thread = threading.Thread(target=self.scheduler.run).start()
122124
except Exception:
123125
pass
124126
else:
@@ -128,8 +130,34 @@ def stop_event_persist(self):
128130
if self.send_enabled:
129131
Logger.debug("Attempting to stop automatic event persistence")
130132
try:
133+
self.thread.stop()
131134
self.scheduler.cancel(self._send_events)
132135
except ValueError:
133136
pass
134137

135138
Logger.debug("Stopped event persistence")
139+
140+
@staticmethod
141+
def serialize(obj):
142+
return {
143+
"rid": obj.rid,
144+
"eventType": obj.event_type.value,
145+
"userId": obj.user_id,
146+
"userTraits": {
147+
"name": obj.user_traits.name,
148+
"email": obj.user_traits.email,
149+
"createdAt": obj.user_traits.created_at,
150+
},
151+
"request": {
152+
"cid": obj.request.cid,
153+
"vid": obj.request.vid,
154+
"fp": obj.request.fp,
155+
"ip": obj.request.ip,
156+
"remoteIp": obj.request.remote_ip,
157+
"method": obj.request.method,
158+
"url": obj.request.url,
159+
"headers": obj.request.headers
160+
},
161+
"timestamp": obj.timestamp,
162+
"properties": obj.properties,
163+
}

securenative/event_options_builder.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,13 @@ def with_user_id(self, user_id):
1313
self.event_options.user_id = user_id
1414
return self
1515

16-
def with_user_traits(self, user_traits, name, email, created_at):
17-
if user_traits:
18-
self.event_options.user_traits = user_traits
19-
return self
20-
elif name and email and created_at:
21-
self.event_options.user_traits = UserTraits(name, email, created_at)
22-
return self
23-
else:
24-
self.event_options.user_traits = UserTraits(name, email)
25-
return self
16+
def with_user_traits(self, user_traits):
17+
self.event_options.user_traits = user_traits
18+
return self
19+
20+
def with_user(self, name, email, created_at=None):
21+
self.event_options.user_traits = UserTraits(name, email, created_at)
22+
return self
2623

2724
def with_context(self, context):
2825
self.event_options.context = context
@@ -37,7 +34,8 @@ def with_timestamp(self, timestamp):
3734
return self
3835

3936
def build(self):
40-
if len(self.event_options.properties) > self.MAX_PROPERTIES_SIZE:
37+
if self.event_options.properties is not None \
38+
and len(self.event_options.properties) > self.MAX_PROPERTIES_SIZE:
4139
raise SecureNativeInvalidOptionsException(
4240
"You can have only up to {} custom properties", self.MAX_PROPERTIES_SIZE)
4341
return self.event_options
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
class EventOptions(object):
22

33
def __init__(self, event, user_id=None, user_traits=None,
4-
securenative_context=None, properties=None, timestamp=None):
4+
context=None, properties=None, timestamp=None):
55
self.event = event
66
self.user_id = user_id
77
self.user_traits = user_traits
8-
self.context = securenative_context
8+
self.context = context
99
self.properties = properties
1010
self.timestamp = timestamp

securenative/models/request_context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,4 @@ def with_method(self, method):
5858
return self
5959

6060
def build(self):
61-
return RequestContext(self.cid, self.vid, self.fp, self.ip, self.remote_ip, self.url, self.method)
61+
return RequestContext(self.cid, self.vid, self.fp, self.ip, self.remote_ip, self.headers, self.url, self.method)

securenative/models/sdk_event.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,27 +9,27 @@
99
class SDKEvent(object):
1010

1111
def __init__(self, event_options, securenative_options):
12-
if event_options.securenative_context:
13-
context = event_options.securenative_context
12+
if event_options.context is not None:
13+
self.context = event_options.context
1414
else:
15-
context = ContextBuilder.default_context_builder().build()
15+
self.context = ContextBuilder.default_context_builder().build()
1616

17-
client_token = EncryptionUtils.decrypt(context.client_token, securenative_options.api_key)
17+
client_token = EncryptionUtils.decrypt(self.context.client_token, securenative_options.api_key)
1818

19-
self.rid = uuid.uuid4()
20-
self.event_optionsType = event_options.getevent_options()
21-
self.userId = event_options.getUserId()
22-
self.userTraits = event_options.getUserTraits()
23-
self.request = RequestContextBuilder().\
24-
with_cid(client_token.cid)\
25-
.with_vid(client_token.vid)\
26-
.with_fp(client_token.fp)\
27-
.with_ip(context.ip)\
28-
.with_remote_ip(context.remote_ip)\
29-
.with_method(context.method)\
30-
.with_url(context.url)\
31-
.with_headers(context.headers)\
19+
self.rid = str(uuid.uuid4())
20+
self.event_type = event_options.event
21+
self.user_id = event_options.user_id
22+
self.user_traits = event_options.user_traits
23+
self.request = RequestContextBuilder() \
24+
.with_cid(client_token.cid) \
25+
.with_vid(client_token.vid) \
26+
.with_fp(client_token.fp) \
27+
.with_ip(self.context.ip) \
28+
.with_remote_ip(self.context.remote_ip) \
29+
.with_method(self.context.method) \
30+
.with_url(self.context.url) \
31+
.with_headers(self.context.headers) \
3232
.build()
3333

3434
self.timestamp = DateUtils.to_timestamp(event_options.timestamp)
35-
self.properties = event_options.getProperties()
35+
self.properties = event_options.properties

securenative/utils/date_utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,6 @@ class DateUtils(object):
55

66
@staticmethod
77
def to_timestamp(date):
8+
if not date:
9+
return datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
810
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")

0 commit comments

Comments
 (0)