Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to pass Auth Key as base64 string #144

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion apns2/credentials.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
from typing import Optional, Tuple, TYPE_CHECKING
from base64 import b64decode

import jwt

Expand Down Expand Up @@ -43,9 +44,13 @@ def __init__(self, cert_file: Optional[str] = None, password: Optional[str] = No
# Credentials subclass for JWT token based authentication
class TokenCredentials(Credentials):
def __init__(self, auth_key_path: str, auth_key_id: str, team_id: str,
auth_key_base64: Optional[str] = None,
encryption_algorithm: str = DEFAULT_TOKEN_ENCRYPTION_ALGORITHM,
token_lifetime: int = DEFAULT_TOKEN_LIFETIME) -> None:
self.__auth_key = self._get_signing_key(auth_key_path)
if auth_key_base64 is not None:
self.__auth_key = self._decode_signing_key(auth_key_base64)
else:
self.__auth_key = self._get_signing_key(auth_key_path)
self.__auth_key_id = auth_key_id
self.__team_id = team_id
self.__encryption_algorithm = encryption_algorithm
Expand All @@ -71,6 +76,13 @@ def _get_signing_key(key_path: str) -> str:
secret = f.read()
return secret

@staticmethod
def _decode_signing_key(key_base64: str) -> str:
secret = ''
if key_base64:
secret = b64decode(key_base64).decode()
return secret

def _get_or_create_topic_token(self) -> str:
# dict of topic to issue date and JWT token
token_pair = self.__jwt_token
Expand Down
5 changes: 5 additions & 0 deletions test/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# - timing out of the token
# - creating multiple tokens for different topics

from base64 import b64encode
import pytest
from freezegun import freeze_time

Expand All @@ -21,6 +22,10 @@ def token_credentials():
token_lifetime=30, # seconds
)

def test_auth_key_base64():
with open('test/eckey.pem', 'rb') as f:
auth_key_base64 = b64encode(f.read()).decode()
assert TokenCredentials._get_signing_key('test/eckey.pem') == TokenCredentials._decode_signing_key(auth_key_base64)

def test_token_expiration(token_credentials):
with freeze_time('2012-01-14 12:00:00'):
Expand Down