authfn 0.1.0__py3-none-any.whl

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.
authfn/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ authfn - API key authentication library using Superfunctions abstractions for Python.
3
+
4
+ Example usage:
5
+ >>> from authfn import create_authfn, AuthFnConfig
6
+ >>> from authfn.types import ApiKeyCreate
7
+ >>>
8
+ >>> auth = create_authfn(
9
+ ... AuthFnConfig(
10
+ ... database=adapter,
11
+ ... namespace="authfn",
12
+ ... )
13
+ ... )
14
+ >>> result = await auth.create_key(
15
+ ... ApiKeyCreate(
16
+ ... name="My App Key",
17
+ ... resourceIds=["app-1"],
18
+ ... scopes=["read", "write"],
19
+ ... )
20
+ ... )
21
+ >>> session = await auth.provider.authenticate(request)
22
+ """
23
+
24
+ __version__ = "0.0.1"
25
+ __author__ = "21n"
26
+ __license__ = "MIT"
27
+
28
+ from .authfn import AuthFn, AuthFnProvider, create_authfn
29
+ from .schema import get_schema
30
+ from .types import (
31
+ ApiKey,
32
+ ApiKeyCreate,
33
+ ApiKeyResponse,
34
+ ApiKeySanitized,
35
+ ApiKeySession,
36
+ AuthFnConfig,
37
+ AuthFnError,
38
+ DatabaseAdapter,
39
+ ExpiredCredentialsError,
40
+ InvalidCredentialsError,
41
+ NotFoundError,
42
+ UnauthorizedError,
43
+ )
44
+
45
+ __all__ = [
46
+ "__version__",
47
+ "__author__",
48
+ "__license__",
49
+ # Main classes
50
+ "AuthFn",
51
+ "AuthFnProvider",
52
+ "create_authfn",
53
+ # Configuration
54
+ "AuthFnConfig",
55
+ # Types
56
+ "ApiKey",
57
+ "ApiKeyCreate",
58
+ "ApiKeyResponse",
59
+ "ApiKeySanitized",
60
+ "ApiKeySession",
61
+ # Protocols
62
+ "DatabaseAdapter",
63
+ # Exceptions
64
+ "AuthFnError",
65
+ "InvalidCredentialsError",
66
+ "ExpiredCredentialsError",
67
+ "UnauthorizedError",
68
+ "NotFoundError",
69
+ # Schema
70
+ "get_schema",
71
+ ]
authfn/authfn.py ADDED
@@ -0,0 +1,213 @@
1
+ """Main authfn implementation."""
2
+
3
+ import secrets
4
+ import time
5
+ from datetime import datetime
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from .types import (
9
+ ApiKey,
10
+ ApiKeyCreate,
11
+ ApiKeyResponse,
12
+ ApiKeySanitized,
13
+ ApiKeySession,
14
+ AuthFnConfig,
15
+ DatabaseAdapter,
16
+ ExpiredCredentialsError,
17
+ InvalidCredentialsError,
18
+ NotFoundError,
19
+ Request,
20
+ WhereClause,
21
+ OrderByClause,
22
+ )
23
+
24
+
25
+ def generate_api_key(prefix: str = "ak") -> str:
26
+ """Generate a secure API key."""
27
+ random_bytes = secrets.token_bytes(32)
28
+ key = random_bytes.hex()
29
+ return f"{prefix}_{key}"
30
+
31
+
32
+ def generate_id(prefix: str) -> str:
33
+ """Generate unique ID."""
34
+ timestamp = format(int(time.time() * 1000), "x")
35
+ random_str = secrets.token_hex(5)[:7]
36
+ return f"{prefix}_{timestamp}{random_str}"
37
+
38
+
39
+ class AuthFnProvider:
40
+ """Auth provider implementation for authfn."""
41
+
42
+ def __init__(self, database: DatabaseAdapter, namespace: str = "authfn"):
43
+ self.database = database
44
+ self.namespace = namespace
45
+
46
+ async def authenticate(self, request: Request) -> Optional[ApiKeySession]:
47
+ """Authenticate a request and return session."""
48
+ auth_header = request.headers.get("authorization") or request.headers.get("Authorization")
49
+
50
+ if not auth_header:
51
+ return None
52
+
53
+ # Extract token from Bearer scheme
54
+ token = auth_header
55
+ if token.lower().startswith("bearer "):
56
+ token = token[7:].strip()
57
+
58
+ if not token:
59
+ return None
60
+
61
+ # Look up API key in database
62
+ api_key_data = await self.database.find_one(
63
+ model="apiKeys",
64
+ where=[WhereClause(field="key", operator="eq", value=token)],
65
+ namespace=self.namespace,
66
+ )
67
+
68
+ if not api_key_data:
69
+ raise InvalidCredentialsError("Invalid API key")
70
+
71
+ # Convert to ApiKey model
72
+ api_key = ApiKey(**api_key_data)
73
+
74
+ # Check if revoked
75
+ if api_key.revoked_at:
76
+ raise InvalidCredentialsError("API key has been revoked")
77
+
78
+ # Check if expired
79
+ if api_key.expires_at:
80
+ if api_key.expires_at < datetime.utcnow():
81
+ raise ExpiredCredentialsError("API key has expired")
82
+
83
+ # Update last used timestamp
84
+ await self.database.update(
85
+ model="apiKeys",
86
+ where=[WhereClause(field="id", operator="eq", value=api_key.id)],
87
+ data={"lastUsedAt": datetime.utcnow().isoformat()},
88
+ namespace=self.namespace,
89
+ )
90
+
91
+ return ApiKeySession(
92
+ id=api_key.id,
93
+ type="api-key",
94
+ keyId=api_key.id,
95
+ name=api_key.name,
96
+ resourceIds=api_key.resource_ids,
97
+ scopes=api_key.scopes,
98
+ expiresAt=api_key.expires_at,
99
+ metadata=api_key.metadata,
100
+ )
101
+
102
+ async def authorize(self, session: ApiKeySession, resource_id: str) -> bool:
103
+ """Authorize a session to access a resource."""
104
+ return resource_id in session.resource_ids
105
+
106
+ async def revoke(self, session_id: str) -> None:
107
+ """Revoke a session."""
108
+ await self.database.update(
109
+ model="apiKeys",
110
+ where=[WhereClause(field="id", operator="eq", value=session_id)],
111
+ data={"revokedAt": datetime.utcnow().isoformat()},
112
+ namespace=self.namespace,
113
+ )
114
+
115
+
116
+ class AuthFn:
117
+ """AuthFn instance with provider and key management."""
118
+
119
+ def __init__(self, config: AuthFnConfig):
120
+ """Initialize AuthFn instance."""
121
+ self.config = config
122
+ self.database = config.database
123
+ self.namespace = config.namespace
124
+ self._provider = AuthFnProvider(self.database, self.namespace)
125
+
126
+ @property
127
+ def provider(self) -> AuthFnProvider:
128
+ """Get the auth provider."""
129
+ return self._provider
130
+
131
+ async def create_key(self, data: ApiKeyCreate) -> ApiKeyResponse:
132
+ """Create a new API key."""
133
+ key_id = generate_id("key")
134
+ key = generate_api_key("ak")
135
+
136
+ key_data = {
137
+ "id": key_id,
138
+ "key": key,
139
+ "name": data.name,
140
+ "resourceIds": data.resource_ids,
141
+ "scopes": data.scopes,
142
+ "metadata": data.metadata,
143
+ "expiresAt": data.expires_at.isoformat() if data.expires_at else None,
144
+ "lastUsedAt": None,
145
+ "revokedAt": None,
146
+ "createdAt": datetime.utcnow().isoformat(),
147
+ }
148
+
149
+ await self.database.create(
150
+ model="apiKeys",
151
+ data=key_data,
152
+ namespace=self.namespace,
153
+ )
154
+
155
+ return ApiKeyResponse(id=key_id, key=key)
156
+
157
+ async def revoke_key(self, key_id: str) -> None:
158
+ """Revoke an API key."""
159
+ await self.database.update(
160
+ model="apiKeys",
161
+ where=[WhereClause(field="id", operator="eq", value=key_id)],
162
+ data={"revokedAt": datetime.utcnow().isoformat()},
163
+ namespace=self.namespace,
164
+ )
165
+
166
+ async def get_key(self, key_id: str) -> Optional[ApiKeySanitized]:
167
+ """Get API key by ID (without the secret key)."""
168
+ key_data = await self.database.find_one(
169
+ model="apiKeys",
170
+ where=[WhereClause(field="id", operator="eq", value=key_id)],
171
+ namespace=self.namespace,
172
+ )
173
+
174
+ if not key_data:
175
+ return None
176
+
177
+ # Remove the secret key field
178
+ key_data_copy = key_data.copy()
179
+ key_data_copy.pop("key", None)
180
+
181
+ return ApiKeySanitized(**key_data_copy)
182
+
183
+ async def list_keys(
184
+ self, filters: Optional[Dict[str, Any]] = None
185
+ ) -> List[ApiKeySanitized]:
186
+ """List API keys (without the secret keys)."""
187
+ where: List[WhereClause] = []
188
+
189
+ if filters and filters.get("resourceId"):
190
+ where.append(
191
+ WhereClause(field="resourceIds", operator="contains", value=filters["resourceId"])
192
+ )
193
+
194
+ keys_data = await self.database.find_many(
195
+ model="apiKeys",
196
+ where=where,
197
+ order_by=[OrderByClause(field="createdAt", direction="desc")],
198
+ namespace=self.namespace,
199
+ )
200
+
201
+ # Sanitize results by removing the secret key field
202
+ sanitized_keys = []
203
+ for key_data in keys_data:
204
+ key_data_copy = key_data.copy()
205
+ key_data_copy.pop("key", None)
206
+ sanitized_keys.append(ApiKeySanitized(**key_data_copy))
207
+
208
+ return sanitized_keys
209
+
210
+
211
+ def create_authfn(config: AuthFnConfig) -> AuthFn:
212
+ """Create authfn instance."""
213
+ return AuthFn(config)
authfn/schema.py ADDED
@@ -0,0 +1,118 @@
1
+ """Schema definition for authfn database tables."""
2
+
3
+ from typing import Any, Dict, List, TypedDict
4
+
5
+
6
+ class FieldSchema(TypedDict, total=False):
7
+ """Schema for a field in a table."""
8
+
9
+ type: str
10
+ required: bool
11
+ unique: bool
12
+ fieldName: str
13
+
14
+
15
+ class IndexSchema(TypedDict):
16
+ """Schema for an index."""
17
+
18
+ name: str
19
+ fields: List[str]
20
+ unique: bool
21
+
22
+
23
+ class TableSchema(TypedDict):
24
+ """Schema for a database table."""
25
+
26
+ modelName: str
27
+ fields: Dict[str, FieldSchema]
28
+ indexes: List[IndexSchema]
29
+
30
+
31
+ class SchemaDefinition(TypedDict):
32
+ """Complete schema definition."""
33
+
34
+ version: int
35
+ schemas: List[TableSchema]
36
+
37
+
38
+ def get_schema(config: Dict[str, Any] = None) -> SchemaDefinition:
39
+ """
40
+ Get schema definition for authfn.
41
+
42
+ Args:
43
+ config: Optional configuration dict with 'namespace' key
44
+
45
+ Returns:
46
+ Schema definition with version and table schemas
47
+ """
48
+ namespace = (config or {}).get("namespace", "authfn")
49
+
50
+ return {
51
+ "version": 1,
52
+ "schemas": [
53
+ # API Keys table
54
+ {
55
+ "modelName": "apiKeys",
56
+ "fields": {
57
+ "id": {
58
+ "type": "string",
59
+ "required": True,
60
+ "fieldName": "id",
61
+ },
62
+ "key": {
63
+ "type": "string",
64
+ "required": True,
65
+ "unique": True,
66
+ "fieldName": "key",
67
+ },
68
+ "name": {
69
+ "type": "string",
70
+ "required": True,
71
+ "fieldName": "name",
72
+ },
73
+ "resourceIds": {
74
+ "type": "json",
75
+ "required": True,
76
+ "fieldName": "resource_ids",
77
+ },
78
+ "scopes": {
79
+ "type": "json",
80
+ "required": False,
81
+ "fieldName": "scopes",
82
+ },
83
+ "metadata": {
84
+ "type": "json",
85
+ "required": False,
86
+ "fieldName": "metadata",
87
+ },
88
+ "expiresAt": {
89
+ "type": "date",
90
+ "required": False,
91
+ "fieldName": "expires_at",
92
+ },
93
+ "lastUsedAt": {
94
+ "type": "date",
95
+ "required": False,
96
+ "fieldName": "last_used_at",
97
+ },
98
+ "revokedAt": {
99
+ "type": "date",
100
+ "required": False,
101
+ "fieldName": "revoked_at",
102
+ },
103
+ "createdAt": {
104
+ "type": "date",
105
+ "required": True,
106
+ "fieldName": "created_at",
107
+ },
108
+ },
109
+ "indexes": [
110
+ {
111
+ "name": f"idx_{namespace}_api_keys_key",
112
+ "fields": ["key"],
113
+ "unique": True,
114
+ }
115
+ ],
116
+ }
117
+ ],
118
+ }
authfn/types.py ADDED
@@ -0,0 +1,203 @@
1
+ """Core type definitions for authfn Python SDK."""
2
+
3
+ from datetime import datetime
4
+ from typing import Any, Dict, List, Optional, Protocol
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class ApiKeySession(BaseModel):
9
+ """API key session extends base auth session."""
10
+
11
+ id: str
12
+ type: str = "api-key"
13
+ key_id: str = Field(alias="keyId")
14
+ name: str
15
+ resource_ids: List[str] = Field(alias="resourceIds")
16
+ scopes: Optional[List[str]] = None
17
+ expires_at: Optional[datetime] = Field(None, alias="expiresAt")
18
+ metadata: Optional[Dict[str, Any]] = None
19
+
20
+ class Config:
21
+ populate_by_name = True
22
+
23
+
24
+ class ApiKey(BaseModel):
25
+ """API key data stored in database."""
26
+
27
+ id: str
28
+ key: str
29
+ name: str
30
+ resource_ids: List[str] = Field(alias="resourceIds")
31
+ scopes: Optional[List[str]] = None
32
+ metadata: Optional[Dict[str, Any]] = None
33
+ expires_at: Optional[datetime] = Field(None, alias="expiresAt")
34
+ last_used_at: Optional[datetime] = Field(None, alias="lastUsedAt")
35
+ revoked_at: Optional[datetime] = Field(None, alias="revokedAt")
36
+ created_at: datetime = Field(alias="createdAt")
37
+
38
+ class Config:
39
+ populate_by_name = True
40
+
41
+
42
+ class ApiKeyCreate(BaseModel):
43
+ """Data for creating a new API key."""
44
+
45
+ name: str
46
+ resource_ids: List[str] = Field(alias="resourceIds")
47
+ scopes: Optional[List[str]] = None
48
+ metadata: Optional[Dict[str, Any]] = None
49
+ expires_at: Optional[datetime] = Field(None, alias="expiresAt")
50
+
51
+ class Config:
52
+ populate_by_name = True
53
+
54
+
55
+ class ApiKeyResponse(BaseModel):
56
+ """Response when creating an API key."""
57
+
58
+ id: str
59
+ key: str
60
+
61
+
62
+ class ApiKeySanitized(BaseModel):
63
+ """API key without the secret key field."""
64
+
65
+ id: str
66
+ name: str
67
+ resource_ids: List[str] = Field(alias="resourceIds")
68
+ scopes: Optional[List[str]] = None
69
+ metadata: Optional[Dict[str, Any]] = None
70
+ expires_at: Optional[datetime] = Field(None, alias="expiresAt")
71
+ last_used_at: Optional[datetime] = Field(None, alias="lastUsedAt")
72
+ revoked_at: Optional[datetime] = Field(None, alias="revokedAt")
73
+ created_at: datetime = Field(alias="createdAt")
74
+
75
+ class Config:
76
+ populate_by_name = True
77
+
78
+
79
+ class AuthFnConfig(BaseModel):
80
+ """Configuration for authfn."""
81
+
82
+ database: Any # Database adapter
83
+ namespace: str = "authfn"
84
+ enable_api: bool = Field(False, alias="enableApi")
85
+ api_config: Optional[Dict[str, Any]] = Field(None, alias="apiConfig")
86
+
87
+ class Config:
88
+ populate_by_name = True
89
+ arbitrary_types_allowed = True
90
+
91
+
92
+ class WhereClause(BaseModel):
93
+ """Database where clause."""
94
+
95
+ field: str
96
+ operator: str
97
+ value: Any
98
+
99
+
100
+ class OrderByClause(BaseModel):
101
+ """Database order by clause."""
102
+
103
+ field: str
104
+ direction: str = "asc"
105
+
106
+
107
+ # Protocols for dependency injection
108
+ class DatabaseAdapter(Protocol):
109
+ """Protocol for database adapters."""
110
+
111
+ async def find_one(
112
+ self,
113
+ model: str,
114
+ where: List[WhereClause],
115
+ namespace: str,
116
+ ) -> Optional[Dict[str, Any]]:
117
+ """Find a single record."""
118
+ ...
119
+
120
+ async def find_many(
121
+ self,
122
+ model: str,
123
+ where: List[WhereClause],
124
+ order_by: Optional[List[OrderByClause]],
125
+ namespace: str,
126
+ ) -> List[Dict[str, Any]]:
127
+ """Find multiple records."""
128
+ ...
129
+
130
+ async def create(
131
+ self,
132
+ model: str,
133
+ data: Dict[str, Any],
134
+ namespace: str,
135
+ ) -> None:
136
+ """Create a new record."""
137
+ ...
138
+
139
+ async def update(
140
+ self,
141
+ model: str,
142
+ where: List[WhereClause],
143
+ data: Dict[str, Any],
144
+ namespace: str,
145
+ ) -> None:
146
+ """Update records."""
147
+ ...
148
+
149
+
150
+ class Request(Protocol):
151
+ """Protocol for HTTP requests."""
152
+
153
+ @property
154
+ def headers(self) -> Dict[str, str]:
155
+ """Request headers."""
156
+ ...
157
+
158
+
159
+ class AuthProvider(Protocol):
160
+ """Protocol for auth providers."""
161
+
162
+ async def authenticate(self, request: Request) -> Optional[ApiKeySession]:
163
+ """Authenticate a request and return session."""
164
+ ...
165
+
166
+ async def authorize(self, session: ApiKeySession, resource_id: str) -> bool:
167
+ """Authorize a session to access a resource."""
168
+ ...
169
+
170
+ async def revoke(self, session_id: str) -> None:
171
+ """Revoke a session."""
172
+ ...
173
+
174
+
175
+ # Exceptions
176
+ class AuthFnError(Exception):
177
+ """Base exception for authfn."""
178
+
179
+ pass
180
+
181
+
182
+ class InvalidCredentialsError(AuthFnError):
183
+ """Invalid credentials error."""
184
+
185
+ pass
186
+
187
+
188
+ class ExpiredCredentialsError(AuthFnError):
189
+ """Expired credentials error."""
190
+
191
+ pass
192
+
193
+
194
+ class UnauthorizedError(AuthFnError):
195
+ """Unauthorized error."""
196
+
197
+ pass
198
+
199
+
200
+ class NotFoundError(AuthFnError):
201
+ """Not found error."""
202
+
203
+ pass
@@ -0,0 +1,367 @@
1
+ Metadata-Version: 2.4
2
+ Name: authfn
3
+ Version: 0.1.0
4
+ Summary: API key authentication library using Superfunctions abstractions for Python
5
+ Project-URL: Documentation, https://docs.superfunctions.dev/authfn
6
+ Project-URL: Repository, https://github.com/21nCo/super-functions
7
+ Project-URL: Issues, https://github.com/21nCo/super-functions/issues
8
+ Author-email: 21n <support@superfunctions.dev>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: api-keys,auth,authentication,superfunctions
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: cryptography>=41.0.0
22
+ Requires-Dist: pydantic>=2.5.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: black>=23.11.0; extra == 'dev'
25
+ Requires-Dist: mypy>=1.7.0; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
27
+ Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
28
+ Requires-Dist: pytest>=7.4.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.1.6; extra == 'dev'
30
+ Provides-Extra: fastapi
31
+ Requires-Dist: fastapi>=0.104.0; extra == 'fastapi'
32
+ Provides-Extra: flask
33
+ Requires-Dist: flask>=3.0.0; extra == 'flask'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # authfn Python SDK
37
+
38
+ > API key authentication library using Superfunctions abstractions for Python
39
+
40
+ Python implementation of authfn with async/await support for API key-based authentication.
41
+
42
+ ## Overview
43
+
44
+ `authfn` is a reference implementation of authentication that provides API key-based authentication. It includes:
45
+
46
+ - **Auth Provider**: Async authentication and authorization
47
+ - **Database Storage**: Uses database adapters for storing API keys
48
+ - **Key Management**: Secure API key generation and validation
49
+ - **Type Safety**: Full type hints with Pydantic models
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install authfn
55
+ ```
56
+
57
+ ## Quick Start
58
+
59
+ ### 1. Setup Database
60
+
61
+ You'll need a database adapter that implements the `DatabaseAdapter` protocol:
62
+
63
+ ```python
64
+ from authfn.types import DatabaseAdapter, WhereClause, OrderByClause
65
+ from typing import Any, Dict, List, Optional
66
+
67
+
68
+ class MyDatabaseAdapter:
69
+ """Your database adapter implementation."""
70
+
71
+ async def find_one(
72
+ self,
73
+ model: str,
74
+ where: List[WhereClause],
75
+ namespace: str,
76
+ ) -> Optional[Dict[str, Any]]:
77
+ # Your implementation here
78
+ pass
79
+
80
+ async def find_many(
81
+ self,
82
+ model: str,
83
+ where: List[WhereClause],
84
+ order_by: Optional[List[OrderByClause]],
85
+ namespace: str,
86
+ ) -> List[Dict[str, Any]]:
87
+ # Your implementation here
88
+ pass
89
+
90
+ async def create(
91
+ self,
92
+ model: str,
93
+ data: Dict[str, Any],
94
+ namespace: str,
95
+ ) -> None:
96
+ # Your implementation here
97
+ pass
98
+
99
+ async def update(
100
+ self,
101
+ model: str,
102
+ where: List[WhereClause],
103
+ data: Dict[str, Any],
104
+ namespace: str,
105
+ ) -> None:
106
+ # Your implementation here
107
+ pass
108
+ ```
109
+
110
+ ### 2. Create authfn Instance
111
+
112
+ ```python
113
+ from authfn import create_authfn, AuthFnConfig
114
+
115
+ adapter = MyDatabaseAdapter()
116
+
117
+ auth = create_authfn(
118
+ AuthFnConfig(
119
+ database=adapter,
120
+ namespace="authfn",
121
+ enable_api=True,
122
+ api_config={
123
+ "admin_key": "your-admin-key", # Optional: protect management API
124
+ },
125
+ )
126
+ )
127
+ ```
128
+
129
+ ### 3. Create API Keys
130
+
131
+ ```python
132
+ from authfn.types import ApiKeyCreate
133
+
134
+ # Create a new API key
135
+ result = await auth.create_key(
136
+ ApiKeyCreate(
137
+ name="Production API Key",
138
+ resourceIds=["resource-1", "resource-2"],
139
+ scopes=["read", "write"],
140
+ metadata={"environment": "production"},
141
+ )
142
+ )
143
+
144
+ print(f"API Key ID: {result.id}")
145
+ print(f"API Key: {result.key}") # Save this securely!
146
+ ```
147
+
148
+ ### 4. Authenticate Requests
149
+
150
+ ```python
151
+ from authfn.types import Request
152
+
153
+ class MyRequest:
154
+ """Your request wrapper."""
155
+
156
+ def __init__(self, headers: Dict[str, str]):
157
+ self._headers = headers
158
+
159
+ @property
160
+ def headers(self) -> Dict[str, str]:
161
+ return self._headers
162
+
163
+
164
+ # Authenticate a request
165
+ request = MyRequest({"Authorization": "Bearer ak_..."})
166
+
167
+ try:
168
+ session = await auth.provider.authenticate(request)
169
+ if session:
170
+ print(f"Authenticated as: {session.name}")
171
+ print(f"Resource IDs: {session.resource_ids}")
172
+ print(f"Scopes: {session.scopes}")
173
+ except Exception as e:
174
+ print(f"Authentication failed: {e}")
175
+ ```
176
+
177
+ ### 5. Authorize Resource Access
178
+
179
+ ```python
180
+ # Check if session has access to a resource
181
+ if session:
182
+ has_access = await auth.provider.authorize(session, "resource-1")
183
+ if has_access:
184
+ print("Access granted to resource-1")
185
+ else:
186
+ print("Access denied to resource-1")
187
+ ```
188
+
189
+ ### 6. Manage API Keys
190
+
191
+ ```python
192
+ # Get API key by ID
193
+ key = await auth.get_key("key_...")
194
+ if key:
195
+ print(f"Key name: {key.name}")
196
+ print(f"Created at: {key.created_at}")
197
+
198
+ # List all API keys
199
+ keys = await auth.list_keys()
200
+ for key in keys:
201
+ print(f"- {key.name} ({key.id})")
202
+
203
+ # List keys for a specific resource
204
+ keys = await auth.list_keys(filters={"resourceId": "resource-1"})
205
+
206
+ # Revoke an API key
207
+ await auth.revoke_key("key_...")
208
+ ```
209
+
210
+ ## Complete Example
211
+
212
+ ```python
213
+ import asyncio
214
+ from authfn import create_authfn, AuthFnConfig
215
+ from authfn.types import ApiKeyCreate
216
+
217
+
218
+ async def main():
219
+ # Setup (you would use your actual database adapter)
220
+ adapter = MyDatabaseAdapter()
221
+
222
+ auth = create_authfn(
223
+ AuthFnConfig(
224
+ database=adapter,
225
+ namespace="authfn",
226
+ )
227
+ )
228
+
229
+ # Create an API key
230
+ result = await auth.create_key(
231
+ ApiKeyCreate(
232
+ name="My App Key",
233
+ resourceIds=["app-1", "app-2"],
234
+ scopes=["read", "write"],
235
+ )
236
+ )
237
+
238
+ print(f"Created API key: {result.key}")
239
+
240
+ # Simulate authentication
241
+ class SimpleRequest:
242
+ def __init__(self, token: str):
243
+ self._headers = {"Authorization": f"Bearer {token}"}
244
+
245
+ @property
246
+ def headers(self):
247
+ return self._headers
248
+
249
+ request = SimpleRequest(result.key)
250
+ session = await auth.provider.authenticate(request)
251
+
252
+ if session:
253
+ print(f"Authenticated as: {session.name}")
254
+
255
+ # Check authorization
256
+ can_access = await auth.provider.authorize(session, "app-1")
257
+ print(f"Can access app-1: {can_access}")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ asyncio.run(main())
262
+ ```
263
+
264
+ ## Schema Definition
265
+
266
+ Get the schema definition for creating database tables:
267
+
268
+ ```python
269
+ from authfn.schema import get_schema
270
+
271
+ schema = get_schema({"namespace": "authfn"})
272
+ print(schema)
273
+ # {
274
+ # "version": 1,
275
+ # "schemas": [
276
+ # {
277
+ # "modelName": "apiKeys",
278
+ # "fields": {...},
279
+ # "indexes": [...]
280
+ # }
281
+ # ]
282
+ # }
283
+ ```
284
+
285
+ ## API Reference
286
+
287
+ ### `create_authfn(config: AuthFnConfig) -> AuthFn`
288
+
289
+ Create an authfn instance.
290
+
291
+ ### `AuthFn`
292
+
293
+ Main authfn class with the following methods:
294
+
295
+ - `provider: AuthFnProvider` - Auth provider for authentication
296
+ - `async create_key(data: ApiKeyCreate) -> ApiKeyResponse` - Create a new API key
297
+ - `async revoke_key(key_id: str) -> None` - Revoke an API key
298
+ - `async get_key(key_id: str) -> Optional[ApiKeySanitized]` - Get an API key by ID
299
+ - `async list_keys(filters: Optional[Dict]) -> List[ApiKeySanitized]` - List API keys
300
+
301
+ ### `AuthFnProvider`
302
+
303
+ Auth provider with the following methods:
304
+
305
+ - `async authenticate(request: Request) -> Optional[ApiKeySession]` - Authenticate a request
306
+ - `async authorize(session: ApiKeySession, resource_id: str) -> bool` - Authorize resource access
307
+ - `async revoke(session_id: str) -> None` - Revoke a session
308
+
309
+ ## Type Safety
310
+
311
+ The SDK uses Pydantic models for full type safety:
312
+
313
+ ```python
314
+ from authfn.types import (
315
+ ApiKey,
316
+ ApiKeyCreate,
317
+ ApiKeyResponse,
318
+ ApiKeySanitized,
319
+ ApiKeySession,
320
+ AuthFnConfig,
321
+ )
322
+ ```
323
+
324
+ ## Error Handling
325
+
326
+ ```python
327
+ from authfn.types import (
328
+ InvalidCredentialsError,
329
+ ExpiredCredentialsError,
330
+ UnauthorizedError,
331
+ NotFoundError,
332
+ )
333
+
334
+ try:
335
+ session = await auth.provider.authenticate(request)
336
+ except InvalidCredentialsError:
337
+ print("Invalid API key")
338
+ except ExpiredCredentialsError:
339
+ print("API key has expired")
340
+ ```
341
+
342
+ ## Development
343
+
344
+ ```bash
345
+ # Install dependencies
346
+ pip install -e ".[dev]"
347
+
348
+ # Run tests
349
+ pytest
350
+
351
+ # Type checking
352
+ mypy authfn
353
+
354
+ # Linting
355
+ ruff check authfn
356
+
357
+ # Format code
358
+ black authfn
359
+ ```
360
+
361
+ ## License
362
+
363
+ MIT
364
+
365
+ ## Repository
366
+
367
+ https://github.com/21nCo/super-functions
@@ -0,0 +1,8 @@
1
+ authfn/__init__.py,sha256=-bQy8AjyMf3oqcfp3Aucxr1RQ3-zXgHwrIoG8Fr1RK4,1569
2
+ authfn/authfn.py,sha256=LpzHGUQWV1BjmGTHvU6VdFXSK7sNaQ9NYI4qfz4jBoI,6605
3
+ authfn/schema.py,sha256=OpIVVUjDEaWMiqy7gB0bbTzP0FkzJAOgw00lyaYDPGo,3358
4
+ authfn/types.py,sha256=uDpIBi35pSIbWo5nCe71cx2B3E4OxzOG-eR6Iu8hqQk,4781
5
+ authfn-0.1.0.dist-info/METADATA,sha256=hDbY6NRd4psONM3xkidX_d7UUq1k2P0ypv25lG-nUvI,8750
6
+ authfn-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
+ authfn-0.1.0.dist-info/licenses/LICENSE,sha256=1sZNTdMfFnGoOrwfdfQmXIdqbyGXzR2sT0tyIy8IG7U,1060
8
+ authfn-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 21n
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.