|
| 1 | +from castle.configuration import configuration |
| 2 | +from castle.api import Api |
| 3 | +from castle.context.default import ContextDefault |
| 4 | +from castle.context.merger import ContextMerger |
| 5 | +from castle.commands.authenticate import CommandsAuthenticate |
| 6 | +from castle.commands.identify import CommandsIdentify |
| 7 | +from castle.commands.track import CommandsTrack |
| 8 | +from castle.exceptions import InternalServerError |
| 9 | +from castle.failover_response import FailoverResponse |
| 10 | + |
| 11 | + |
| 12 | +class Client(object): |
| 13 | + def __init__(self, request, options): |
| 14 | + self.options = options or dict() |
| 15 | + self.do_not_track = self.default_tracking() |
| 16 | + self.context = self.setup_context(request) |
| 17 | + self.api = Api() |
| 18 | + |
| 19 | + def identify(self, options): |
| 20 | + if not self.tracked(): |
| 21 | + return |
| 22 | + return self.api.call(CommandsIdentify(self.context).build(options)) |
| 23 | + |
| 24 | + def authenticate(self, options): |
| 25 | + if self.tracked(): |
| 26 | + try: |
| 27 | + response = self.api.call(CommandsAuthenticate(self.context).build(options)) |
| 28 | + response.update(failover=False, failover_reason=None) |
| 29 | + return response |
| 30 | + except InternalServerError as exception: |
| 31 | + return self.failover(options, exception) |
| 32 | + else: |
| 33 | + return FailoverResponse(options['user_id'], 'allow', 'Castle set to do not track.').call() |
| 34 | + |
| 35 | + def track(self, options): |
| 36 | + if not self.tracked(): |
| 37 | + return |
| 38 | + return self.api.call(CommandsTrack(self.context).build(options)) |
| 39 | + |
| 40 | + def disable_tracking(self): |
| 41 | + self.do_not_track = True |
| 42 | + |
| 43 | + def enable_tracking(self): |
| 44 | + self.do_not_track = False |
| 45 | + |
| 46 | + def tracked(self): |
| 47 | + return not self.do_not_track |
| 48 | + |
| 49 | + def default_tracking(self): |
| 50 | + return self.options['do_not_track'] if 'do_not_track' in self.options else False |
| 51 | + |
| 52 | + def setup_context(self, request): |
| 53 | + default_context = ContextDefault(request, self.options.get('cookies', dict())).call() |
| 54 | + return ContextMerger(default_context).call(self.options.get('context', dict())) |
| 55 | + |
| 56 | + def failover(self, options, exception): |
| 57 | + if configuration.failover_strategy != 'throw': |
| 58 | + return FailoverResponse(options['user_id'], None, exception.__class__.__name__).call() |
| 59 | + raise exception |
0 commit comments