fastjwt-kit 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.
@@ -0,0 +1,34 @@
1
+ """fastjwt-kit: a small, opinionated wrapper around PyJWT.
2
+
3
+ Usage:
4
+
5
+ from fastjwt_kit import create_access_token, verify_token, TokenExpiredError
6
+
7
+ token = create_access_token(subject="user-123", secret="change-me")
8
+ claims = verify_token(token, secret="change-me")
9
+ """
10
+ from .exceptions import (
11
+ InvalidClaimsError,
12
+ InvalidTokenError,
13
+ TokenError,
14
+ TokenExpiredError,
15
+ )
16
+ from .tokens import (
17
+ create_access_token,
18
+ create_refresh_token,
19
+ create_token,
20
+ verify_token,
21
+ )
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ __all__ = [
26
+ "create_token",
27
+ "create_access_token",
28
+ "create_refresh_token",
29
+ "verify_token",
30
+ "TokenError",
31
+ "TokenExpiredError",
32
+ "InvalidTokenError",
33
+ "InvalidClaimsError",
34
+ ]
@@ -0,0 +1,21 @@
1
+ """Custom exceptions for fastjwt_kit.
2
+
3
+ Wrapping PyJWT's exceptions means callers only ever need to catch
4
+ fastjwt_kit exceptions, not reach into the underlying jwt library.
5
+ """
6
+
7
+
8
+ class TokenError(Exception):
9
+ """Base class for all token-related errors."""
10
+
11
+
12
+ class TokenExpiredError(TokenError):
13
+ """Raised when a token's expiry (exp claim) has passed."""
14
+
15
+
16
+ class InvalidTokenError(TokenError):
17
+ """Raised when a token is malformed or its signature is invalid."""
18
+
19
+
20
+ class InvalidClaimsError(TokenError):
21
+ """Raised when required claims (iss, aud, sub, etc.) are missing or wrong."""
fastjwt_kit/tokens.py ADDED
@@ -0,0 +1,168 @@
1
+ """Core JWT creation and verification utilities.
2
+
3
+ Thin, opinionated wrapper around PyJWT that handles the boilerplate most
4
+ projects rewrite by hand: expiry, claim validation, and friendly errors.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import datetime as dt
9
+ from typing import Any, Optional
10
+
11
+ import jwt
12
+
13
+ from .exceptions import (
14
+ InvalidClaimsError,
15
+ InvalidTokenError,
16
+ TokenExpiredError,
17
+ )
18
+
19
+ DEFAULT_ALGORITHM = "HS256"
20
+ DEFAULT_ACCESS_TOKEN_EXPIRE_MINUTES = 15
21
+ DEFAULT_REFRESH_TOKEN_EXPIRE_DAYS = 7
22
+
23
+
24
+ def _now() -> dt.datetime:
25
+ return dt.datetime.now(dt.timezone.utc)
26
+
27
+
28
+ def create_token(
29
+ subject: str,
30
+ secret: str,
31
+ *,
32
+ expires_in: dt.timedelta,
33
+ algorithm: str = DEFAULT_ALGORITHM,
34
+ issuer: Optional[str] = None,
35
+ audience: Optional[str] = None,
36
+ extra_claims: Optional[dict[str, Any]] = None,
37
+ ) -> str:
38
+ """Create a signed JWT.
39
+
40
+ Args:
41
+ subject: The "sub" claim — usually a user ID.
42
+ secret: Signing secret (or private key for RS256/ES256).
43
+ expires_in: How long until the token expires.
44
+ algorithm: Signing algorithm, defaults to HS256.
45
+ issuer: Optional "iss" claim.
46
+ audience: Optional "aud" claim.
47
+ extra_claims: Any additional claims to embed (e.g. {"role": "admin"}).
48
+
49
+ Returns:
50
+ Encoded JWT string.
51
+ """
52
+ now = _now()
53
+ payload: dict[str, Any] = {
54
+ "sub": subject,
55
+ "iat": now,
56
+ "exp": now + expires_in,
57
+ }
58
+ if issuer:
59
+ payload["iss"] = issuer
60
+ if audience:
61
+ payload["aud"] = audience
62
+ if extra_claims:
63
+ payload.update(extra_claims)
64
+
65
+ return jwt.encode(payload, secret, algorithm=algorithm)
66
+
67
+
68
+ def create_access_token(
69
+ subject: str,
70
+ secret: str,
71
+ *,
72
+ expires_in: dt.timedelta = dt.timedelta(minutes=DEFAULT_ACCESS_TOKEN_EXPIRE_MINUTES),
73
+ algorithm: str = DEFAULT_ALGORITHM,
74
+ issuer: Optional[str] = None,
75
+ audience: Optional[str] = None,
76
+ extra_claims: Optional[dict[str, Any]] = None,
77
+ ) -> str:
78
+ """Create a short-lived access token. See create_token for arg details."""
79
+ claims = dict(extra_claims or {})
80
+ claims["type"] = "access"
81
+ return create_token(
82
+ subject,
83
+ secret,
84
+ expires_in=expires_in,
85
+ algorithm=algorithm,
86
+ issuer=issuer,
87
+ audience=audience,
88
+ extra_claims=claims,
89
+ )
90
+
91
+
92
+ def create_refresh_token(
93
+ subject: str,
94
+ secret: str,
95
+ *,
96
+ expires_in: dt.timedelta = dt.timedelta(days=DEFAULT_REFRESH_TOKEN_EXPIRE_DAYS),
97
+ algorithm: str = DEFAULT_ALGORITHM,
98
+ issuer: Optional[str] = None,
99
+ audience: Optional[str] = None,
100
+ extra_claims: Optional[dict[str, Any]] = None,
101
+ ) -> str:
102
+ """Create a long-lived refresh token. See create_token for arg details."""
103
+ claims = dict(extra_claims or {})
104
+ claims["type"] = "refresh"
105
+ return create_token(
106
+ subject,
107
+ secret,
108
+ expires_in=expires_in,
109
+ algorithm=algorithm,
110
+ issuer=issuer,
111
+ audience=audience,
112
+ extra_claims=claims,
113
+ )
114
+
115
+
116
+ def verify_token(
117
+ token: str,
118
+ secret: str,
119
+ *,
120
+ algorithm: str = DEFAULT_ALGORITHM,
121
+ issuer: Optional[str] = None,
122
+ audience: Optional[str] = None,
123
+ ) -> dict[str, Any]:
124
+ """Verify and decode a JWT, raising fastjwt_kit exceptions on failure.
125
+
126
+ Args:
127
+ token: The encoded JWT string.
128
+ secret: Signing secret (or public key for RS256/ES256).
129
+ algorithm: Expected signing algorithm.
130
+ issuer: If set, the token's "iss" claim must match this exactly.
131
+ audience: If set, the token's "aud" claim must match this exactly.
132
+
133
+ Returns:
134
+ The decoded claims dict.
135
+
136
+ Raises:
137
+ TokenExpiredError: if the token's exp claim has passed.
138
+ InvalidClaimsError: if iss/aud don't match what was expected.
139
+ InvalidTokenError: for any other malformed/invalid token.
140
+ """
141
+ try:
142
+ options = {}
143
+ kwargs: dict[str, Any] = {}
144
+ if audience is not None:
145
+ kwargs["audience"] = audience
146
+ else:
147
+ options["verify_aud"] = False
148
+
149
+ claims = jwt.decode(
150
+ token,
151
+ secret,
152
+ algorithms=[algorithm],
153
+ options=options,
154
+ **kwargs,
155
+ )
156
+ except jwt.ExpiredSignatureError as exc:
157
+ raise TokenExpiredError("Token has expired") from exc
158
+ except jwt.InvalidAudienceError as exc:
159
+ raise InvalidClaimsError("Token audience does not match") from exc
160
+ except jwt.InvalidIssuerError as exc:
161
+ raise InvalidClaimsError("Token issuer does not match") from exc
162
+ except jwt.PyJWTError as exc:
163
+ raise InvalidTokenError(f"Invalid token: {exc}") from exc
164
+
165
+ if issuer is not None and claims.get("iss") != issuer:
166
+ raise InvalidClaimsError("Token issuer does not match")
167
+
168
+ return claims
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastjwt-kit
3
+ Version: 0.1.0
4
+ Summary: A small, opinionated JWT toolkit: create, verify, expire, and handle errors without writing the same PyJWT boilerplate every project.
5
+ Project-URL: Homepage, https://github.com/yourusername/fastjwt-kit
6
+ Project-URL: Issues, https://github.com/yourusername/fastjwt-kit/issues
7
+ Author-email: Shreyas G <shreyasg2526@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: auth,authentication,fastapi,jwt,security,token
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: pyjwt>=2.8.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: build; extra == 'dev'
25
+ Requires-Dist: pytest>=7.0; extra == 'dev'
26
+ Requires-Dist: twine; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # fastjwt-kit
30
+
31
+ A small, opinionated wrapper around [PyJWT](https://pyjwt.readthedocs.io/) that
32
+ handles the boilerplate every project rewrites: token creation, expiry,
33
+ claim validation, and clean error handling — without you having to import
34
+ `jwt` exceptions directly.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install fastjwt-kit
40
+ ```
41
+
42
+ ## Quickstart
43
+
44
+ ```python
45
+ from fastjwt_kit import create_access_token, verify_token, TokenExpiredError
46
+
47
+ token = create_access_token(subject="user-123", secret="change-me")
48
+
49
+ try:
50
+ claims = verify_token(token, secret="change-me")
51
+ print(claims["sub"]) # "user-123"
52
+ except TokenExpiredError:
53
+ print("Token expired — ask the user to log in again")
54
+ ```
55
+
56
+ That's it — no manual `exp` math, no catching raw `jwt.ExpiredSignatureError`.
57
+
58
+ ## Access + refresh tokens
59
+
60
+ ```python
61
+ from fastjwt_kit import create_access_token, create_refresh_token
62
+
63
+ access = create_access_token(subject="user-123", secret="change-me") # 15 min default
64
+ refresh = create_refresh_token(subject="user-123", secret="change-me") # 7 days default
65
+ ```
66
+
67
+ ## Custom expiry, issuer, audience, and extra claims
68
+
69
+ ```python
70
+ import datetime as dt
71
+ from fastjwt_kit import create_token, verify_token
72
+
73
+ token = create_token(
74
+ subject="user-123",
75
+ secret="change-me",
76
+ expires_in=dt.timedelta(hours=1),
77
+ issuer="my-app",
78
+ audience="my-app-clients",
79
+ extra_claims={"role": "admin"},
80
+ )
81
+
82
+ claims = verify_token(token, secret="change-me", issuer="my-app", audience="my-app-clients")
83
+ ```
84
+
85
+ ## Error handling
86
+
87
+ All errors inherit from `TokenError`, so you can catch broadly or specifically:
88
+
89
+ ```python
90
+ from fastjwt_kit import TokenError, TokenExpiredError, InvalidTokenError, InvalidClaimsError
91
+
92
+ try:
93
+ claims = verify_token(token, secret="change-me")
94
+ except TokenExpiredError:
95
+ ... # token was valid but has expired
96
+ except InvalidClaimsError:
97
+ ... # issuer/audience didn't match
98
+ except InvalidTokenError:
99
+ ... # malformed or tampered token
100
+ except TokenError:
101
+ ... # catch-all
102
+ ```
103
+
104
+ ## API
105
+
106
+ | Function | Description |
107
+ |---|---|
108
+ | `create_token(subject, secret, *, expires_in, ...)` | Create a JWT with full control over claims. |
109
+ | `create_access_token(subject, secret, ...)` | Create a short-lived token (default 15 min), tagged `type: access`. |
110
+ | `create_refresh_token(subject, secret, ...)` | Create a long-lived token (default 7 days), tagged `type: refresh`. |
111
+ | `verify_token(token, secret, *, algorithm, issuer, audience)` | Decode and validate a token, raising `fastjwt_kit` exceptions. |
112
+
113
+ ## Why not just use PyJWT directly?
114
+
115
+ You can! This package just wraps the parts everyone ends up rewriting:
116
+ expiry defaults, issuer/audience checks, and exception types that don't
117
+ leak the underlying library. If you only need raw encode/decode, PyJWT
118
+ alone is enough.
119
+
120
+ ## Roadmap
121
+
122
+ - [ ] Password hashing module
123
+ - [ ] FastAPI signup/login router + `get_current_user` dependency
124
+ - [ ] Config/env validation helpers
125
+
126
+ Feedback and issues welcome — this is an early release and will evolve
127
+ based on real usage.
128
+
129
+ ## License
130
+
131
+ MIT
@@ -0,0 +1,7 @@
1
+ fastjwt_kit/__init__.py,sha256=18YV5WECksqnK7PZaPPwfzedQgvk4GFHqrlnvgkfBU0,730
2
+ fastjwt_kit/exceptions.py,sha256=MIpm54TmPX2fWMAHswMEAH6FBgPs0-FJuqA3uinSkl4,592
3
+ fastjwt_kit/tokens.py,sha256=nrqPj9vPk8Hsop2s8pV3CHH-lImt8V00UN6Plqai5as,4819
4
+ fastjwt_kit-0.1.0.dist-info/METADATA,sha256=KIMgnXEs3abNj7-3IhFT2a4p6eYYyc1H8GWUK7qlJTU,4256
5
+ fastjwt_kit-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ fastjwt_kit-0.1.0.dist-info/licenses/LICENSE,sha256=Pfrz0aGFmWyOqX6CLppTalPP6KvVYEZaY7yq--lPxS4,1065
7
+ fastjwt_kit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shreyas G
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.