flask-session.manager.sk 0.1.1__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,18 @@
1
+ """Flask companion package for react-session.manager.sk.
2
+
3
+ Public API (stable):
4
+ SessionManager — Flask extension for JWT session management
5
+ SessionManagerCallbacks — frozen dataclass of callback hooks
6
+ token_response — create a Flask response with an HttpOnly JWT cookie
7
+ clear_token_response — create a Flask response that clears JWT cookies
8
+ """
9
+
10
+ from .cookies import clear_token_response, token_response
11
+ from .extension import SessionManager, SessionManagerCallbacks
12
+
13
+ __all__ = [
14
+ "SessionManager",
15
+ "SessionManagerCallbacks",
16
+ "token_response",
17
+ "clear_token_response",
18
+ ]
@@ -0,0 +1,109 @@
1
+ """Cookie and CSRF helpers for Flask JWT session management."""
2
+
3
+ import hashlib
4
+ from datetime import UTC, datetime
5
+ from urllib.parse import urlparse
6
+
7
+ UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
8
+
9
+
10
+ def _normalise_origin(value):
11
+ if not value:
12
+ return None
13
+ parsed = urlparse(value)
14
+ if not parsed.scheme or not parsed.netloc:
15
+ return None
16
+ return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
17
+
18
+
19
+ def configured_browser_origins(app=None):
20
+ from flask import current_app
21
+
22
+ _app = app if app is not None else current_app
23
+ origins = set()
24
+
25
+ frontend_url = _app.config.get("FRONTEND_URL")
26
+ frontend_origin = _normalise_origin(frontend_url)
27
+ if frontend_origin:
28
+ origins.add(frontend_origin)
29
+
30
+ for origin in _app.config.get("CORS_ORIGINS", []):
31
+ normalised = _normalise_origin(origin)
32
+ if normalised:
33
+ origins.add(normalised)
34
+
35
+ return origins
36
+
37
+
38
+ def request_uses_cookie_auth(req=None, app=None):
39
+ from flask import current_app, request
40
+
41
+ _req = req if req is not None else request
42
+ _app = app if app is not None else current_app
43
+ return bool(_req.cookies.get(_app.config["JWT_ACCESS_COOKIE_NAME"]))
44
+
45
+
46
+ def request_has_bearer_auth(req=None):
47
+ from flask import request
48
+
49
+ _req = req if req is not None else request
50
+ return _req.headers.get("Authorization", "").startswith("Bearer ")
51
+
52
+
53
+ def csrf_origin_is_allowed(req=None, app=None):
54
+ from flask import current_app, request
55
+
56
+ _req = req if req is not None else request
57
+ _app = app if app is not None else current_app
58
+
59
+ origin = _normalise_origin(_req.headers.get("Origin"))
60
+ referer = _normalise_origin(_req.headers.get("Referer"))
61
+ allowed = configured_browser_origins(_app)
62
+ return bool(
63
+ allowed and ((origin and origin in allowed) or (referer and referer in allowed))
64
+ )
65
+
66
+
67
+ def reject_cookie_csrf(req=None, app=None):
68
+ from flask import current_app, jsonify, request
69
+
70
+ _req = req if req is not None else request
71
+ _app = app if app is not None else current_app
72
+
73
+ if _req.method not in UNSAFE_METHODS:
74
+ return None
75
+ if not request_uses_cookie_auth(_req, _app) or request_has_bearer_auth(_req):
76
+ return None
77
+ if csrf_origin_is_allowed(_req, _app):
78
+ return None
79
+
80
+ return jsonify(status="fail", message="CSRF origin check failed"), 403
81
+
82
+
83
+ def token_response(payload, status=200, access_token=None):
84
+ """Create a Flask JSON response, optionally setting an HttpOnly JWT cookie."""
85
+ from flask import jsonify
86
+ from flask_jwt_extended import set_access_cookies
87
+
88
+ response = jsonify(payload)
89
+ if access_token:
90
+ set_access_cookies(response, access_token)
91
+ return response, status
92
+
93
+
94
+ def clear_token_response(payload=None, status=200):
95
+ """Create a response that clears JWT access cookies."""
96
+ from flask import jsonify
97
+ from flask_jwt_extended import unset_jwt_cookies
98
+
99
+ response = jsonify(payload or {"status": "success", "message": "Logged out"})
100
+ unset_jwt_cookies(response)
101
+ return response, status
102
+
103
+
104
+ def clear_session_token_value(token_record):
105
+ """Invalidate a session token while preserving its registered-device row."""
106
+ token_record.token_hash = hashlib.sha256(b"").hexdigest()
107
+ token_record.hint = ""
108
+ token_record.token = None
109
+ token_record.last_modified = datetime.now(UTC)
@@ -0,0 +1,110 @@
1
+ """Flask extension for cookie-driven JWT session management."""
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class SessionManagerCallbacks:
10
+ """Callback hooks for the SessionManager extension.
11
+
12
+ Required:
13
+ user_lookup — resolve an identity value to a user object (or None)
14
+ refresh_user_token — create and return a new JWT for a user (or None)
15
+
16
+ Optional:
17
+ verify_user_token — validate a known token for a user (return record or None)
18
+ is_user_active — check whether a user object is active (return bool)
19
+ """
20
+
21
+ user_lookup: Callable[[str], Any | None]
22
+ refresh_user_token: Callable[[Any, str, str | None], str | None]
23
+ verify_user_token: Callable[[Any, str | None, str | None], Any | None] | None = None
24
+ is_user_active: Callable[[Any], bool] | None = None
25
+
26
+
27
+ class SessionManager:
28
+ """Flask extension that wires JWT handlers with application callbacks.
29
+
30
+ Usage::
31
+
32
+ manager = SessionManager()
33
+ manager.init_app(app, callbacks=SessionManagerCallbacks(...))
34
+ """
35
+
36
+ def __init__(self, app=None, callbacks=None):
37
+ from flask_jwt_extended import JWTManager
38
+
39
+ self.jwt = JWTManager()
40
+ if app is not None:
41
+ self.init_app(app, callbacks)
42
+
43
+ def init_app(self, app, callbacks=None):
44
+ """Register JWT handlers on the given Flask app."""
45
+ self.jwt.init_app(app)
46
+ if callbacks is not None:
47
+ self._register_callbacks(app, callbacks)
48
+
49
+ def _register_callbacks(self, app, callbacks: SessionManagerCallbacks):
50
+ """Wire up Flask-JWT-Extended handlers from the callback object."""
51
+ from flask import jsonify, request
52
+
53
+ @self.jwt.user_identity_loader
54
+ def _identity_loader(user):
55
+ return user
56
+
57
+ @self.jwt.user_lookup_loader
58
+ def _user_lookup(_jwt_header, jwt_data):
59
+ identity = jwt_data["sub"]
60
+ return callbacks.user_lookup(identity)
61
+
62
+ # ---- token verification (optional) ----
63
+ if callbacks.verify_user_token is not None:
64
+
65
+ @self.jwt.token_verification_loader
66
+ def _token_verification(_self, jwt_data):
67
+ user = callbacks.user_lookup(jwt_data["sub"])
68
+
69
+ if callbacks.is_user_active is not None and (
70
+ not user or not callbacks.is_user_active(user)
71
+ ):
72
+ return None
73
+
74
+ from .request import get_dets_from_request
75
+
76
+ agent, device_uid, token = get_dets_from_request(request)
77
+ return callbacks.verify_user_token(user, agent, device_uid, token)
78
+
79
+ # ---- verification failure ----
80
+ @self.jwt.token_verification_failed_loader
81
+ def _verification_failed(_self, _callback):
82
+ return (
83
+ jsonify(logged_in=False, refreshed=False, msg="Invalid Token"),
84
+ 455,
85
+ )
86
+
87
+ # ---- expired token refresh ----
88
+ @self.jwt.expired_token_loader
89
+ def _expired_token(jwt_header, jwt_payload):
90
+ identity = jwt_payload["sub"]
91
+ user = callbacks.user_lookup(identity)
92
+ if user is None:
93
+ return (
94
+ jsonify(code="Invalid", msg="Invalid Token"),
95
+ 455,
96
+ )
97
+
98
+ from .request import get_dets_from_request
99
+
100
+ agent, device_uid, _ = get_dets_from_request(request)
101
+ new_token = callbacks.refresh_user_token(user, agent, device_uid)
102
+ if new_token:
103
+ return (
104
+ jsonify(refreshed=True, access_token=new_token),
105
+ 200,
106
+ )
107
+ return (
108
+ jsonify(code="Invalid", msg="Invalid Token"),
109
+ 455,
110
+ )
@@ -0,0 +1,35 @@
1
+ """Request helpers for extracting device/agent/token info."""
2
+
3
+
4
+ def get_agent(req):
5
+ """Parse the User-Agent header into a human-readable device/browser name."""
6
+ from ua_parser import user_agent_parser
7
+
8
+ parsed = user_agent_parser.Parse(req.user_agent.to_header())
9
+ os_family = parsed["os"]["family"]
10
+ browser = parsed["user_agent"]["family"]
11
+ return f"{os_family} {browser}"
12
+
13
+
14
+ def get_ip(req):
15
+ """Return the client's remote IP address."""
16
+ return req.remote_addr
17
+
18
+
19
+ def get_token(req):
20
+ """Extract a JWT from the Authorization bearer header or access cookie."""
21
+ from flask import current_app
22
+
23
+ auth_header = req.headers.get("Authorization", "")
24
+ if auth_header.startswith("Bearer "):
25
+ return auth_header[7:]
26
+
27
+ cookie_name = current_app.config.get(
28
+ "JWT_ACCESS_COOKIE_NAME", "access_token_cookie"
29
+ )
30
+ return req.cookies.get(cookie_name)
31
+
32
+
33
+ def get_dets_from_request(req):
34
+ """Collect (agent_name, device_uid, token) from a Flask request."""
35
+ return get_agent(req), req.headers.get("deviceUID"), get_token(req)
@@ -0,0 +1,43 @@
1
+ """Token hashing and verification utilities."""
2
+
3
+ import hashlib
4
+ from datetime import UTC
5
+
6
+
7
+ def create_token_hash(token):
8
+ """Return the SHA-256 hex digest of a token string."""
9
+ return hashlib.sha256(token.encode()).hexdigest()
10
+
11
+
12
+ def token_hint(token, length=8):
13
+ """Return the last `length` characters of a token for display identification."""
14
+ return token[-length:] if len(token) >= length else token
15
+
16
+
17
+ def verify_token_hash(candidate, stored_hash):
18
+ """Return True if the candidate token's hash matches the stored hash."""
19
+ if not candidate or not stored_hash:
20
+ return False
21
+ return create_token_hash(candidate) == stored_hash
22
+
23
+
24
+ def update_token_record(record, token):
25
+ """Atomically update a token record with a new hashed token value.
26
+
27
+ Mutates the provided record-like object in place. Does not commit.
28
+ """
29
+ from datetime import datetime
30
+
31
+ record.token_hash = create_token_hash(token)
32
+ record.hint = token_hint(token)
33
+ record.last_modified = datetime.now(UTC)
34
+
35
+
36
+ def clear_session_token_value(token_record):
37
+ """Invalidate a session token while preserving its registered-device row."""
38
+ from datetime import datetime
39
+
40
+ token_record.token_hash = create_token_hash("")
41
+ token_record.hint = ""
42
+ token_record.token = None
43
+ token_record.last_modified = datetime.now(UTC)
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: flask-session.manager.sk
3
+ Version: 0.1.1
4
+ Summary: Flask companion package for react-session.manager.sk
5
+ Project-URL: Homepage, https://github.com/Skulldorom/flask-session.manager.sk
6
+ Project-URL: Repository, https://github.com/Skulldorom/flask-session.manager.sk
7
+ Project-URL: Issues, https://github.com/Skulldorom/flask-session.manager.sk/issues
8
+ Author: Skulldorom
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Classifier: Framework :: Flask
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: flask-jwt-extended>=4.7
18
+ Requires-Dist: flask>=3.1
19
+ Requires-Dist: ua-parser>=1.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # flask-session.manager.sk
23
+
24
+ Flask companion package for
25
+ [react-session.manager.sk](https://github.com/Skulldorom/react-session.manager.sk).
26
+
27
+ Cookie-driven JWT session management for Flask backends, designed to pair with the
28
+ React session manager's HttpOnly-cookie transport.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install flask-session.manager.sk
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```python
39
+ from flask import Flask, jsonify
40
+ from flask_jwt_extended import create_access_token
41
+ from flask_session_manager_sk import SessionManager, SessionManagerCallbacks
42
+
43
+ app = Flask(__name__)
44
+ app.config.update(
45
+ {
46
+ "SECRET_KEY": "your-secret-key",
47
+ "JWT_TOKEN_LOCATION": ["cookies"],
48
+ "JWT_COOKIE_SECURE": True, # require HTTPS in production
49
+ "JWT_COOKIE_CSRF_PROTECT": True,
50
+ "JWT_ACCESS_COOKIE_NAME": "access_token_cookie",
51
+ "FRONTEND_URL": "https://myapp.example.com",
52
+ "CORS_ORIGINS": ["https://myapp.example.com"],
53
+ }
54
+ )
55
+
56
+ manager = SessionManager()
57
+
58
+ callbacks = SessionManagerCallbacks(
59
+ user_lookup=lambda identity: get_user_by_id(identity),
60
+ refresh_user_token=lambda user, agent, device_uid: create_and_store_token(
61
+ user, agent, device_uid
62
+ ),
63
+ verify_user_token=lambda user, agent, device_uid, token: user.check_token(
64
+ agent, device_uid, token
65
+ ),
66
+ is_user_active=lambda user: user.is_active,
67
+ )
68
+
69
+ manager.init_app(app, callbacks=callbacks)
70
+
71
+
72
+ @app.route("/auth/who")
73
+ @jwt_required(optional=True)
74
+ def whoami():
75
+ from flask_jwt_extended import current_user
76
+
77
+ if current_user:
78
+ return jsonify(logged_in=True, user_id=current_user.id)
79
+ return jsonify(logged_in=False)
80
+ ```
81
+
82
+ ## Public API (v0.1)
83
+
84
+ Only four names are part of the stable surface:
85
+
86
+ | Name | Description |
87
+ |------|-------------|
88
+ | `SessionManager` | Flask extension that wires JWT callbacks |
89
+ | `SessionManagerCallbacks` | Frozen dataclass of application hooks |
90
+ | `token_response` | Create a JSON response with an HttpOnly JWT cookie |
91
+ | `clear_token_response` | Create a response that clears JWT cookies |
92
+
93
+ Everything else in the package is internal and may change without notice.
94
+
95
+ ### SessionManagerCallbacks
96
+
97
+ ```python
98
+ @dataclass(frozen=True)
99
+ class SessionManagerCallbacks:
100
+ # Required
101
+ user_lookup: Callable[[str], Any | None]
102
+ refresh_user_token: Callable[[Any, str, str | None], str | None]
103
+
104
+ # Optional
105
+ verify_user_token: Callable[[Any, str | None, str | None], Any | None] | None = None
106
+ is_user_active: Callable[[Any], bool] | None = None
107
+ ```
108
+
109
+ ## Flask Configuration Reference
110
+
111
+ These values are read at runtime via `current_app.config`. No configuration is
112
+ stored in the package.
113
+
114
+ | Key | Required | Default | Description |
115
+ |-----|----------|---------|-------------|
116
+ | `SECRET_KEY` | Yes | — | Flask secret, must be ≥32 bytes for HMAC-SHA256 |
117
+ | `JWT_TOKEN_LOCATION` | Yes | — | Should include `"cookies"` |
118
+ | `JWT_ACCESS_COOKIE_NAME` | Yes | — | Cookie name; `react-session.manager.sk` expects `"access_token_cookie"` |
119
+ | `JWT_COOKIE_CSRF_PROTECT` | Yes | — | Must be `True` for browser clients |
120
+ | `JWT_COOKIE_SECURE` | Yes | — | `True` in production (HTTPS only) |
121
+ | `JWT_COOKIE_SAMESITE` | No | — | `"Lax"` or `"Strict"` |
122
+ | `FRONTEND_URL` | Yes | — | Canonical URL of the SPA |
123
+ | `CORS_ORIGINS` | Yes | — | List of allowed browser origins |
124
+
125
+ ## React Companion Contract
126
+
127
+ The frontend companion
128
+ [react-session.manager.sk](https://github.com/Skulldorom/react-session.manager.sk)
129
+ (v4.0+) uses this transport contract:
130
+
131
+ - **Axios** configured with `withCredentials: true`, `withXSRFToken: true`
132
+ - Cookies expected at default Flask-JWT-Extended names:
133
+ - `access_token_cookie` (JWT)
134
+ - `csrf_access_token` (CSRF double-submit)
135
+ - CSRF header sent as `X-CSRF-TOKEN`
136
+ - `deviceUID` header sent on every request
137
+ - `appVersion` header sent on every request
138
+ - No `Authorization` bearer header for browser requests
139
+ - Legacy `localStorage`/`sessionStorage` bearer tokens are automatically cleared
140
+
141
+ ## Internal Modules
142
+
143
+ Not part of the stable API. Import at your own risk.
144
+
145
+ | Module | Content |
146
+ |--------|---------|
147
+ | `flask_session_manager_sk.cookies` | CSRF origin checks, cookie auth detection, `clear_session_token_value` |
148
+ | `flask_session_manager_sk.request` | `get_agent`, `get_ip`, `get_token`, `get_dets_from_request` |
149
+ | `flask_session_manager_sk.tokens` | `create_token_hash`, `token_hint`, `verify_token_hash`, `update_token_record` |
150
+ | `flask_session_manager_sk.extension` | `SessionManager` implementation details |
151
+
152
+ ## Migrating from Bearer Tokens
153
+
154
+ If your backend currently returns access tokens as JSON payloads (e.g.
155
+ `{"access_token": "..."}`) and stores them in `localStorage`:
156
+
157
+ 1. **Package adoption**: Wire `SessionManager` with your user-lookup and
158
+ token-refresh callbacks.
159
+ 2. **Login endpoint**: Call `token_response(payload, status, access_token)`
160
+ instead of `jsonify(payload)`. This sets the HttpOnly cookie automatically.
161
+ 3. **CSRF check**: Add `reject_cookie_csrf()` as a `@app.before_request` hook
162
+ for all unsafe methods (POST, PUT, DELETE).
163
+ 4. **Frontend**: Upgrade `react-session.manager.sk` to v4.0+. It removes
164
+ bearer-token browser storage and sends cookie credentials automatically.
165
+ 5. **Backwards compatibility**: Non-browser clients (API scripts, scheduled
166
+ tasks) can still send `Authorization: Bearer <token>`. The CSRF check
167
+ skips bearer-authenticated requests.
168
+
169
+ ## License
170
+
171
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,9 @@
1
+ flask_session_manager_sk/__init__.py,sha256=K58JHApJp9wbe5EZkY0BgJuJhfgyTWnHkgjj75QZDR0,629
2
+ flask_session_manager_sk/cookies.py,sha256=XWuCHGQNb3WnB3pXcp8kpmgFpGVLHHwcvnohhoEBJX4,3357
3
+ flask_session_manager_sk/extension.py,sha256=D_9j0wrpJ-LOwy9kJEDHdQLZekhsYb12SamgXH2J5P4,3854
4
+ flask_session_manager_sk/request.py,sha256=EUbeLOap8e6sBApFJyiscC-bpjXA2M816H7hMXq2AAQ,1077
5
+ flask_session_manager_sk/tokens.py,sha256=TlHWKhtF9ONKVZ2V_Ci6yyOSXkXMC5IFIP-0BD-me30,1340
6
+ flask_session_manager_sk-0.1.1.dist-info/METADATA,sha256=HfnpgVrXPPn7VJS06fRDIeflLUsnSExjHA8mmsmBjIo,6245
7
+ flask_session_manager_sk-0.1.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
8
+ flask_session_manager_sk-0.1.1.dist-info/licenses/LICENSE,sha256=P_AP_YoS_q-_NkE6-so0jyniNuae4W0iDuTApI48cow,1067
9
+ flask_session_manager_sk-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Skulldorom
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.