Skip to content

Commit 97596de

Browse files
committed
Initial implementation
1 parent 567c807 commit 97596de

File tree

4 files changed

+176
-1
lines changed

4 files changed

+176
-1
lines changed

README.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
1-
# warrant-python
1+
# Warrant Python Library
2+
3+
Use [Warrant](https://warrant.dev/) in Python projects.
4+
5+
## Installation
6+
7+
```python
8+
pip install warrant-python
9+
```
10+
11+
## Usage
12+
13+
```python
14+
import warrant
15+
16+
warrant = Warrant("api_test_f5dsKVeYnVSLHGje44zAygqgqXiLJBICbFzCiAg1E=")
17+
warrant.create_user()
18+
```
19+
20+
We’ve used a random API key in these code examples. Replace it with your
21+
[actual publishable API keys](https://app.warrant.dev) to
22+
test this code through your own Warrant account.
23+
24+
For more information on how to use the Warrant API, please refer to the
25+
[Warrant API reference](https://docs.warrant.dev).
26+
27+
Note that we may release new [minor and patch](https://semver.org/) versions of this library with small but backwards-incompatible fixes to the type declarations. These changes will not affect Warrant itself.
28+
29+
## Warrant Documentation
30+
31+
- [Warrant Docs](https://docs.warrant.dev/)

examples/example.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from warrant import Warrant
2+
3+
def make_warrant_requests(api_key):
4+
client = Warrant(api_key)
5+
6+
# Create users and session tokens
7+
print("Created user with provided id: " + client.create_user("custom_id_001"))
8+
new_user = client.create_user()
9+
print("Created user with generated id: " + new_user)
10+
print("Created session token: " + client.create_session(new_user))
11+
12+
# Create and check warrants
13+
print(client.create_warrant(object_type="store", object_id="store1", relation="owner", user=new_user))
14+
is_authorized = client.is_authorized(object_type="store", object_id="store1", relation="owner", user_to_check=new_user)
15+
print(f"New user authorization result: {is_authorized}")
16+
17+
if __name__ == '__main__':
18+
# Replace with your Warrant api key
19+
api_key = "API_KEY"
20+
make_warrant_requests(api_key)

setup.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import pathlib
2+
from setuptools import setup
3+
4+
DIR = pathlib.Path(__file__).parent
5+
README = (DIR / "README.md").read_text()
6+
7+
setup(
8+
name="warrant-python",
9+
version="0.2.0",
10+
description="Python SDK for Warrant",
11+
long_description=README,
12+
long_description_content_type="text/markdown",
13+
author="Warrant",
14+
author_email="[email protected]",
15+
url="https://github.com/warrant-dev/warrant-python",
16+
license="Apache Software License (http://www.apache.org/licenses/LICENSE-2.0.txt)",
17+
keywords="warrant api authorization access control",
18+
packages=["warrant"],
19+
install_requires=["requests"],
20+
project_urls={
21+
"Bug Tracker": "https://github.com/warrant-dev/warrant-python/issues",
22+
"Documentation": "https://docs.warrant.dev",
23+
"Source Code": "https://github.com/warrant-dev/warrant-python",
24+
},
25+
classifiers=[
26+
"Intended Audience :: Developers",
27+
"Operating System :: OS Independent",
28+
"Programming Language :: Python",
29+
"Programming Language :: Python :: 3",
30+
"Programming Language :: Python :: 3.4",
31+
"Programming Language :: Python :: 3.5",
32+
"Programming Language :: Python :: 3.6",
33+
"Programming Language :: Python :: 3.7",
34+
"Programming Language :: Python :: 3.8",
35+
"Programming Language :: Python :: 3.9",
36+
"Topic :: Software Development :: Libraries :: Python Modules",
37+
],
38+
)

warrant/__init__.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import requests
2+
import json
3+
4+
__version__ = "0.2.0"
5+
6+
API_ENDPOINT = "https://api.warrant.dev"
7+
API_VERSION = "/v1"
8+
9+
class WarrantException(Exception):
10+
def __init__(self, msg, status_code=-1):
11+
if status_code == -1:
12+
message = 'Warrant error: ' + msg
13+
else:
14+
message = f"Warrant error: {status_code} " + msg
15+
super().__init__(message)
16+
17+
class User(object):
18+
def __init__(self, object_type, object_id, relation):
19+
self.objectType = object_type
20+
self.objectId = object_id
21+
self.relation = relation
22+
23+
class Warrant(object):
24+
def __init__(self, api_key):
25+
self._apiKey = api_key
26+
27+
def _make_post_request(self, uri, json={}):
28+
headers = { "Authorization": "ApiKey " + self._apiKey }
29+
resp = requests.post(url = API_ENDPOINT+API_VERSION+uri, headers = headers, json = json)
30+
if resp.status_code == 200:
31+
return resp.json()
32+
else:
33+
raise WarrantException(msg=resp.text, status_code=resp.status_code)
34+
35+
def create_user(self, user_id=""):
36+
if user_id == "":
37+
payload = {}
38+
else:
39+
payload = { "userId": user_id }
40+
json = self._make_post_request(uri="/users", json=payload)
41+
return json['userId']
42+
43+
def create_session(self, user_id):
44+
if user_id == "":
45+
raise WarrantException(msg="Invalid userId provided")
46+
json = self._make_post_request(uri="/users/"+user_id+"/sessions")
47+
return json['token']
48+
49+
def create_warrant(self, object_type, object_id, relation, user):
50+
if object_type == "" or object_id == "" or relation == "":
51+
raise WarrantException(msg="Invalid object_type, object_id and/or relation")
52+
payload = {
53+
"objectType": object_type,
54+
"objectId": object_id,
55+
"relation": relation
56+
}
57+
if isinstance(user, str):
58+
payload["user"] = { "userId": user }
59+
elif isinstance(user, User):
60+
payload["user"] = json.dumps(user.__dict__)
61+
else:
62+
raise WarrantException(msg="Invalid type for \'user\'. Must be of type User or str")
63+
resp = self._make_post_request(uri="/warrants", json=payload)
64+
return resp['id']
65+
66+
def is_authorized(self, object_type, object_id, relation, user_to_check):
67+
if object_type == "" or object_id == "" or relation == "":
68+
raise WarrantException(msg="Invalid object_type, object_id and/or relation")
69+
payload = {
70+
"objectType": object_type,
71+
"objectId": object_id,
72+
"relation": relation
73+
}
74+
if isinstance(user_to_check, str):
75+
payload["user"] = { "userId": user_to_check }
76+
elif isinstance(user_to_check, User):
77+
payload["user"] = json.dumps(user_to_check.__dict__)
78+
else:
79+
raise WarrantException(msg="Invalid type for \'user_to_check\'. Must be of type User or str")
80+
headers = { "Authorization": "ApiKey " + self._apiKey }
81+
resp = requests.post(url = API_ENDPOINT+API_VERSION+"/authorize", headers = headers, json=payload)
82+
if resp.status_code == 200:
83+
return True
84+
elif resp.status_code == 401:
85+
return False
86+
else:
87+
raise WarrantException(msg=resp.text, status_code=resp.status_code)

0 commit comments

Comments
 (0)