apexauthlib 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Apex LTD
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: apexauthlib
3
+ Version: 0.1.0
4
+ Summary: Apex authorization library for services
5
+ Author-email: Apex Dev <dev@apex.ge>
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # apexauthlib
12
+ Authorization library for apex services
@@ -0,0 +1,2 @@
1
+ # apexauthlib
2
+ Authorization library for apex services
File without changes
@@ -0,0 +1,6 @@
1
+ from apexauthlib.fastapi.auth import auth_api, get_user
2
+
3
+ __all__ = [
4
+ "auth_api",
5
+ "get_user",
6
+ ]
@@ -0,0 +1,60 @@
1
+ from dataclasses import dataclass
2
+ from typing import Annotated, Any
3
+
4
+ from apexdevkit.fastapi import inject
5
+ from fastapi import APIRouter, Depends, HTTPException
6
+ from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
7
+ from starlette import status
8
+
9
+ from apexauthlib.integration.api import AuthApiProvider
10
+
11
+ auth_api = APIRouter(tags=["Auth"])
12
+ AuthApiProviderDependable = Annotated[AuthApiProvider[Any], inject("auth")]
13
+
14
+
15
+ def oauth2() -> OAuth2PasswordBearer:
16
+ return OAuth2PasswordBearer(tokenUrl="auth/login")
17
+
18
+
19
+ TokenDependable = Annotated[str, Depends(oauth2())]
20
+
21
+
22
+ def get_user(
23
+ token: TokenDependable,
24
+ auth: AuthApiProviderDependable,
25
+ ) -> Any:
26
+ try:
27
+ api = auth.for_token(token)
28
+ return api.metadata_for(api.user())
29
+ except Exception as e:
30
+ raise HTTPException(
31
+ status_code=status.HTTP_401_UNAUTHORIZED,
32
+ detail=str(e),
33
+ headers={"WWW-Authenticate": "Bearer"},
34
+ )
35
+
36
+
37
+ @dataclass
38
+ class TokenResponse:
39
+ access_token: str
40
+ token_type: str = "Bearer"
41
+
42
+
43
+ @auth_api.post(
44
+ "/login",
45
+ status_code=200,
46
+ response_model=TokenResponse,
47
+ )
48
+ def login(
49
+ form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
50
+ auth: AuthApiProviderDependable,
51
+ ) -> TokenResponse:
52
+ try:
53
+ return TokenResponse(
54
+ access_token=auth.login(form_data.username, form_data.password)
55
+ )
56
+ except Exception:
57
+ raise HTTPException(
58
+ status_code=status.HTTP_401_UNAUTHORIZED,
59
+ detail="Incorrect username or password",
60
+ )
@@ -0,0 +1,3 @@
1
+ from apexauthlib.integration.api import AuthApiProvider
2
+
3
+ __all__ = ["AuthApiProvider"]
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Generic, Mapping, TypeVar
5
+
6
+ from apexdevkit.formatter import Formatter
7
+ from apexdevkit.http import FluentHttp, JsonDict
8
+
9
+ ItemT = TypeVar("ItemT")
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AuthApiProvider(Generic[ItemT]):
14
+ http: FluentHttp
15
+ service_name: str
16
+ formatter: Formatter[Mapping[str, Any], ItemT]
17
+
18
+ def login(self, username: str, password: str) -> str:
19
+ data = {
20
+ "grant_type": "password",
21
+ "username": username,
22
+ "password": password,
23
+ "scope": "",
24
+ "client_id": "string",
25
+ "client_secret": "string",
26
+ }
27
+
28
+ return str(
29
+ (
30
+ self.http.with_data(JsonDict(data))
31
+ .post()
32
+ .on_endpoint("/auth/login")
33
+ .on_failure(raises=RuntimeError)
34
+ .json()
35
+ )["access_token"]
36
+ )
37
+
38
+ def for_token(self, token: str) -> AuthApi[ItemT]:
39
+ return AuthApi(self.http, self.service_name, self.formatter, token)
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class AuthApi(Generic[ItemT]):
44
+ http: FluentHttp
45
+ service_name: str
46
+ formatter: Formatter[Mapping[str, Any], ItemT]
47
+ token: str
48
+
49
+ def user(self) -> str:
50
+ return str(
51
+ (
52
+ self.http.with_header("Authorization", f"Bearer {self.token}")
53
+ .get()
54
+ .on_endpoint("/auth/user")
55
+ .on_failure(raises=RuntimeError)
56
+ .json()
57
+ )["id"]
58
+ )
59
+
60
+ def metadata_for(self, user_id: str) -> ItemT:
61
+ result = JsonDict(
62
+ (
63
+ self.http.with_header("Authorization", f"Bearer {self.token}")
64
+ .get()
65
+ .on_endpoint(f"/services/{self.service_name}/metadata/{user_id}")
66
+ .on_failure(raises=RuntimeError)
67
+ .json()
68
+ )
69
+ )
70
+
71
+ return self.formatter.load(JsonDict(result["data"]["metadata"]["metadata"]))
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: apexauthlib
3
+ Version: 0.1.0
4
+ Summary: Apex authorization library for services
5
+ Author-email: Apex Dev <dev@apex.ge>
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # apexauthlib
12
+ Authorization library for apex services
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ apexauthlib/__init__.py
5
+ apexauthlib.egg-info/PKG-INFO
6
+ apexauthlib.egg-info/SOURCES.txt
7
+ apexauthlib.egg-info/dependency_links.txt
8
+ apexauthlib.egg-info/top_level.txt
9
+ apexauthlib/fastapi/__init__.py
10
+ apexauthlib/fastapi/auth.py
11
+ apexauthlib/integration/__init__.py
12
+ apexauthlib/integration/api.py
13
+ tests/test_api.py
@@ -0,0 +1 @@
1
+ apexauthlib
@@ -0,0 +1,63 @@
1
+ [project]
2
+ name = "apexauthlib"
3
+ version = "0.1.0"
4
+ description = "Apex authorization library for services"
5
+ authors = [{ name = "Apex Dev", email = "dev@apex.ge" }]
6
+ readme = "README.md"
7
+ requires-python = ">=3.12"
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.12"
11
+ httpx = "*"
12
+ fastapi = "*"
13
+ uvicorn = "*"
14
+ apexdevkit = "*"
15
+
16
+ [tool.poetry.group.dev.dependencies]
17
+ approvaltests = "*"
18
+ pytest = "*"
19
+ pytest-approvaltests = "*"
20
+ pytest-cov = "*"
21
+ pytest-recording = "*"
22
+ coverage = "*"
23
+ faker = "*"
24
+
25
+ [tool.poetry.group.lint.dependencies]
26
+ mypy = "*"
27
+ ruff = "*"
28
+
29
+ [tool.mypy]
30
+ python_version = "3.12"
31
+ ignore_missing_imports = true
32
+ strict = true
33
+
34
+ [tool.ruff]
35
+ target-version = "py312"
36
+ line-length = 88
37
+
38
+ exclude = [
39
+ ".git",
40
+ ".mypy_cache",
41
+ ".ruff_cache",
42
+ "venv",
43
+ ]
44
+
45
+ lint.select = ["E", "F", "I"]
46
+ lint.ignore = []
47
+ lint.fixable = ["A", "B", "C", "D", "E", "F", "I"]
48
+ lint.unfixable = []
49
+
50
+ [tool.ruff.lint.mccabe]
51
+ max-complexity = 10
52
+
53
+ [tool.coverage.run]
54
+ branch = true
55
+ source = [
56
+ "apexauthlib",
57
+ "tests",
58
+ ]
59
+
60
+ [tool.coverage.report]
61
+ skip_empty = true
62
+ skip_covered = true
63
+ show_missing = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,86 @@
1
+ from dataclasses import dataclass
2
+
3
+ from apexdevkit.formatter import DataclassFormatter
4
+ from apexdevkit.http import FakeHttp, FluentHttp, HttpMethod
5
+ from apexdevkit.http.fake import FakeResponse
6
+ from faker import Faker
7
+
8
+ from apexauthlib.integration import AuthApiProvider
9
+ from apexauthlib.integration.api import AuthApi
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TestPermissions:
14
+ role: str
15
+ read: bool
16
+ write: bool
17
+
18
+
19
+ def test_login() -> None:
20
+ http = FakeHttp(FakeResponse({"access_token": "token"}))
21
+ service_name = Faker().text()
22
+ api = AuthApiProvider[TestPermissions](
23
+ FluentHttp(http), service_name, DataclassFormatter(TestPermissions)
24
+ )
25
+
26
+ result = api.login("user", "9")
27
+
28
+ assert result == "token"
29
+
30
+ http.intercepted(HttpMethod.post).on_endpoint("/auth/login")
31
+
32
+ assert http.data == {
33
+ "grant_type": "password",
34
+ "username": "user",
35
+ "password": "9",
36
+ "scope": "",
37
+ "client_id": "string",
38
+ "client_secret": "string",
39
+ }
40
+
41
+
42
+ def test_user() -> None:
43
+ http = FakeHttp(FakeResponse({"id": "1"}))
44
+ service_name = Faker().text()
45
+ api = AuthApi[TestPermissions](
46
+ FluentHttp(http), service_name, DataclassFormatter(TestPermissions), "token"
47
+ )
48
+
49
+ result = api.user()
50
+
51
+ assert result == "1"
52
+
53
+ http.intercepted(HttpMethod.get).on_endpoint("/auth/user")
54
+
55
+ assert http.headers == {
56
+ "Authorization": "Bearer token",
57
+ }
58
+
59
+
60
+ def test_metadata() -> None:
61
+ http = FakeHttp(
62
+ FakeResponse(
63
+ {
64
+ "data": {
65
+ "metadata": {
66
+ "metadata": {"role": "admin", "read": True, "write": True}
67
+ }
68
+ }
69
+ }
70
+ )
71
+ )
72
+
73
+ service_name = Faker().text()
74
+ api = AuthApi[TestPermissions](
75
+ FluentHttp(http), service_name, DataclassFormatter(TestPermissions), "token"
76
+ )
77
+
78
+ result = api.metadata_for("1")
79
+
80
+ assert result == TestPermissions("admin", True, True)
81
+
82
+ http.intercepted(HttpMethod.get).on_endpoint(f"/services/{service_name}/metadata/1")
83
+
84
+ assert http.headers == {
85
+ "Authorization": "Bearer token",
86
+ }