Skip to content

Commit

Permalink
Merge pull request #1 from whitehead-ai/PROD-215
Browse files Browse the repository at this point in the history
Raise AuthError when necessary
  • Loading branch information
whiterabbit1983 authored Jul 19, 2021
2 parents 69d44f2 + 351294c commit a8c74b0
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 21 deletions.
44 changes: 43 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ cryptography = "^3.4.6"
gql = {version = "3.0.0a5", extras = ["all"], allow-prereleases = true}
py-gql-client = "^1.0.1"
dataclasses = {version = "^0.6", python = "~3.6"}
portalocker = "^2.3.0"
pywin32 = {version = "==228", markers="sys_platform == 'win32'"}


[build-system]
Expand Down
3 changes: 3 additions & 0 deletions whitehead_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from gql.client import Client
from gql.transport.aiohttp import AIOHTTPTransport
from . import config, utils, token_cache
from .exceptions import AuthError


def Whitehead(api_key, developer_id):
Expand All @@ -12,6 +13,8 @@ def Whitehead(api_key, developer_id):
if not jwt_token:
exchange_token, nonce = utils.create_exchange_token(api_key)
auth_data = utils.request_jwt(developer_id, exchange_token)
if auth_data.get("enc_token") is None:
raise AuthError(auth_data.get("error"))
jwt_token = utils.decrypt_jwt(auth_data, api_key, nonce)
cache.write(jwt_token)

Expand Down
2 changes: 2 additions & 0 deletions whitehead_sdk/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class AuthError(Exception):
pass
27 changes: 7 additions & 20 deletions whitehead_sdk/token_cache.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
import os
import fcntl
import hashlib
import tempfile
import portalocker
from contextlib import contextmanager, suppress
from datetime import datetime


@contextmanager
def file_lock(fd, cmd):
try:
fcntl.lockf(fd, cmd)
yield
except IOError:
yield
finally:
fcntl.lockf(fd, fcntl.LOCK_UN)


class TokenCache:
def __init__(self, dev_id, api_key):
self._hash = hashlib.md5(f"{dev_id}:{api_key}".encode()).hexdigest()
Expand All @@ -34,13 +23,11 @@ def cache_path(self):

def read(self):
with suppress(FileNotFoundError):
with open(self.cache_path, "r") as f:
with file_lock(f, fcntl.LOCK_SH):
return f.read()
with portalocker.Lock(self.cache_path, "r") as f:
return f.read()

def write(self, data):
with open(self.cache_path, "a") as f:
with file_lock(f, fcntl.LOCK_EX):
f.seek(0)
f.truncate(0)
f.write(data)
with portalocker.Lock(self.cache_path, "a") as f:
f.seek(0)
f.truncate(0)
f.write(data)

0 comments on commit a8c74b0

Please sign in to comment.