Skip to content
Merged
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: 4 additions & 6 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,10 @@ Here is a simple example of track event.
.. code:: python

from castle.client import Client
from castle import events

castle = Client.from_request(request)
castle.track({
'event': events.LOGIN_SUCCEEDED,
'event': '$login',
'user_id': 'user_id'
})

Expand All @@ -148,11 +147,10 @@ background worker you can generate data for a worker:
.. code:: python

from castle.payload.prepare import PayloadPrepare
from castle import events

payload = PayloadPrepare.call(
{
'event': events.LOGIN_SUCCEEDED,
'event': '$login',
'user_id': user.id,
'properties': { 'key': 'value' },
'user_traits': { 'key': 'value' }
Expand All @@ -172,7 +170,7 @@ and use it later in a way
Events
--------------

List of Recognized Events can be found `here <https://github.com/castle/castle-python/tree/master/castle/events.py>`_ or in the `docs <https://docs.castle.io/api_reference/#list-of-recognized-events>`_.
List of Recognized Events can be found in the `docs <https://docs.castle.io/api_reference/#list-of-recognized-events>`_.

Device management
-----------------
Expand Down Expand Up @@ -234,7 +232,7 @@ error <https://github.com/castle/castle-python/blob/master/castle/errors.py>`__.
Webhooks
--------

Castle uses webhooks to notify about ``$incident.confirmed`` or `$review.opened` events.
Castle uses webhooks to notify about ``$incident.confirmed`` or ``$review.opened`` events.
Each webhook has ``X-Castle-Signature`` header that allows verifying webhook's source.

.. code:: python
Expand Down
9 changes: 0 additions & 9 deletions castle/api/review.py

This file was deleted.

48 changes: 29 additions & 19 deletions castle/client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from castle.api_request import APIRequest
from castle.commands.authenticate import CommandsAuthenticate
from castle.commands.identify import CommandsIdentify
from castle.commands.start_impersonation import CommandsStartImpersonation
from castle.commands.end_impersonation import CommandsEndImpersonation
from castle.commands.track import CommandsTrack
from castle.configuration import configuration
from castle.context.prepare import ContextPrepare
from castle.options.merge import OptionsMerge
from castle.options.get_default import OptionsGetDefault
from castle.errors import InternalServerError, RequestError, ImpersonationFailed
from castle.failover.prepare_response import FailoverPrepareResponse
from castle.failover.strategy import FailoverStrategy
Expand All @@ -18,8 +19,11 @@ def from_request(cls, request, options=None):
if options is None:
options = {}

options.setdefault('context', ContextPrepare.call(request, options))
return cls(options)
default_options = OptionsGetDefault(request, options.get('cookies')).call()
options_with_default_opts = OptionsMerge.call(options, default_options)

options_with_default_opts.setdefault('context', ContextPrepare.call(options))
return cls(options_with_default_opts)

@staticmethod
def failover_response_or_raise(options, exception):
Expand All @@ -32,6 +36,8 @@ def failover_response_or_raise(options, exception):
def __init__(self, options=None):
if options is None:
options = {}

self.default_options = options
self.do_not_track = options.get('do_not_track', False)
self.timestamp = options.get('timestamp')
self.context = options.get('context')
Expand All @@ -42,47 +48,51 @@ def _add_timestamp_if_necessary(self, options):
options.setdefault('timestamp', self.timestamp)

def authenticate(self, options):
options_with_default_opts = OptionsMerge.call(options, self.default_options)

if self.tracked():
self._add_timestamp_if_necessary(options)
command = CommandsAuthenticate(self.context).call(options)
self._add_timestamp_if_necessary(options_with_default_opts)
command = CommandsAuthenticate(self.context).call(options_with_default_opts)
try:
response = self.api.call(command)
response.update(failover=False, failover_reason=None)
return response
except (RequestError, InternalServerError) as exception:
return Client.failover_response_or_raise(options, exception)
return Client.failover_response_or_raise(options_with_default_opts, exception)
else:
return FailoverPrepareResponse(
options.get('user_id'),
options_with_default_opts.get('user_id'),
'allow',
'Castle set to do not track.'
).call()

def identify(self, options):
if not self.tracked():
return None
self._add_timestamp_if_necessary(options)
return self.api.call(CommandsIdentify(self.context).call(options))

def start_impersonation(self, options):
self._add_timestamp_if_necessary(options)
response = self.api.call(CommandsStartImpersonation(self.context).call(options))
options_with_default_opts = OptionsMerge.call(options, self.default_options)

self._add_timestamp_if_necessary(options_with_default_opts)
response = self.api.call(CommandsStartImpersonation(
self.context).call(options_with_default_opts))
if not response.get('success'):
raise ImpersonationFailed
return response

def end_impersonation(self, options):
self._add_timestamp_if_necessary(options)
response = self.api.call(CommandsEndImpersonation(self.context).call(options))
options_with_default_opts = OptionsMerge.call(options, self.default_options)

self._add_timestamp_if_necessary(options_with_default_opts)
response = self.api.call(CommandsEndImpersonation(
self.context).call(options_with_default_opts))
if not response.get('success'):
raise ImpersonationFailed
return response

def track(self, options):
options_with_default_opts = OptionsMerge.call(options, self.default_options)

if not self.tracked():
return None
self._add_timestamp_if_necessary(options)
return self.api.call(CommandsTrack(self.context).call(options))
self._add_timestamp_if_necessary(options_with_default_opts)
return self.api.call(CommandsTrack(self.context).call(options_with_default_opts))

def disable_tracking(self):
self.do_not_track = True
Expand Down
3 changes: 1 addition & 2 deletions castle/commands/end_impersonation.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ def __init__(self, context):
self.context = context

def call(self, options):
ValidatorsPresent.call(options, 'user_id')
ValidatorsPresent.call(options, 'user_id', 'headers')

context = ContextMerge.call(self.context, options.get('context'))
context = ContextSanitize.call(context)
ValidatorsPresent.call(context, 'user_agent', 'ip')

if context:
options.update({'context': context})
Expand Down
20 changes: 0 additions & 20 deletions castle/commands/identify.py

This file was deleted.

15 changes: 0 additions & 15 deletions castle/commands/review.py

This file was deleted.

3 changes: 1 addition & 2 deletions castle/commands/start_impersonation.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ def __init__(self, context):
self.context = context

def call(self, options):
ValidatorsPresent.call(options, 'user_id')
ValidatorsPresent.call(options, 'user_id', 'headers')

context = ContextMerge.call(self.context, options.get('context'))
context = ContextSanitize.call(context)
ValidatorsPresent.call(context, 'user_agent', 'ip')

if context:
options.update({'context': context})
Expand Down
39 changes: 2 additions & 37 deletions castle/context/get_default.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,18 @@
from castle.version import VERSION
from castle.headers.filter import HeadersFilter
from castle.client_id.extract import ClientIdExtract
from castle.headers.extract import HeadersExtract
from castle.ips.extract import IPsExtract

__version__ = VERSION


class ContextGetDefault(object):
def __init__(self, request, cookies):
self.cookies = self._fetch_cookies(request, cookies)
self.pre_headers = HeadersFilter(request).call()

def call(self):
@staticmethod
def call():
context = dict({
'client_id': self._client_id(),
'active': True,
'headers': self._headers(),
'ip': self._ip(),
'library': {
'name': 'castle-python',
'version': __version__
}
})
context.update(self._optional_defaults())

return context

def _ip(self):
return IPsExtract(self.pre_headers).call()

def _client_id(self):
return ClientIdExtract(self.pre_headers, self.cookies).call()

def _headers(self):
return HeadersExtract(self.pre_headers).call()

def _optional_defaults(self):
context = dict()
if 'Accept-Language' in self.pre_headers:
context['locale'] = self.pre_headers.get('Accept-Language')
if 'User-Agent' in self.pre_headers:
context['user_agent'] = self.pre_headers.get('User-Agent')
return context

@staticmethod
def _fetch_cookies(request, cookies):
if cookies:
return cookies
if hasattr(request, 'COOKIES') and request.COOKIES:
return request.COOKIES
return None
5 changes: 2 additions & 3 deletions castle/context/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
class ContextPrepare(object):

@staticmethod
def call(request, options=None):
def call(options=None):
if options is None:
options = {}
default_context = ContextGetDefault(
request, options.get('cookies')).call()
default_context = ContextGetDefault.call()
return ContextMerge.call(default_context, options.get('context', {}))
42 changes: 0 additions & 42 deletions castle/events.py

This file was deleted.

File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class ClientIdExtract(object):
class FingerprintExtract(object):
def __init__(self, headers, cookies=None):
self.headers = headers
self.cookies = cookies or dict()
Expand Down
Empty file added castle/options/__init__.py
Empty file.
39 changes: 39 additions & 0 deletions castle/options/get_default.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from castle.version import VERSION
from castle.headers.filter import HeadersFilter
from castle.fingerprint.extract import FingerprintExtract
from castle.headers.extract import HeadersExtract
from castle.ips.extract import IPsExtract

__version__ = VERSION


class OptionsGetDefault(object):
def __init__(self, request, cookies):
self.cookies = self._fetch_cookies(request, cookies)
self.pre_headers = HeadersFilter(request).call()

def call(self):
context = dict({
'fingerprint': self._fingerprint(),
'headers': self._headers(),
'ip': self._ip(),
})

return context

def _ip(self):
return IPsExtract(self.pre_headers).call()

def _fingerprint(self):
return FingerprintExtract(self.pre_headers, self.cookies).call()

def _headers(self):
return HeadersExtract(self.pre_headers).call()

@staticmethod
def _fetch_cookies(request, cookies):
if cookies:
return cookies
if hasattr(request, 'COOKIES') and request.COOKIES:
return request.COOKIES
return None
11 changes: 11 additions & 0 deletions castle/options/merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from castle.utils.merge import UtilsMerge
from castle.utils.clone import UtilsClone


class OptionsMerge(object):

@staticmethod
def call(initial_options, request_options):
source_copy = UtilsClone.call(initial_options)
UtilsMerge.call(source_copy, request_options)
return source_copy
Loading