session
Session Management
Provides a flexible session management system supporting both standard and JWT-based sessions. It handles session creation, validation, expiration, concurrency limits, and refresh logic, making it suitable for web applications and database connections.
Key Features
- Centralized session store with expiration tracking
- Support for plain token and JSON Web Tokens with standard claims
- Concurrency control (max concurrent sessions)
- Automatic cleanup of expired sessions
- Session refresh mechanism to extend validity
Usage Examples
from plantdb.commons.auth.session import JWTSessionManager manager = JWTSessionManager(session_timeout=1800, secret_key='my_secret') token = manager.create_session('alice') user_info = manager.validate_session(token) print(user_info) {'username': 'alice', 'issued_at': 1769011058, 'expires_at': 1769012858, 'jti': 'HVaAR4XHmIJgCKbZMDqmwg', 'issuer': 'plantdb-api', 'audience': 'plantdb-client'} new_token = manager.refresh_session(token)
AccessTokenNotFoundError
Link
Bases: SessionValidationError
Raised when an access token isn’t present in the active‑session store.
InvalidTokenProcessingError
Link
Bases: SessionValidationError
Raised for unexpected errors while processing a token (e.g. decoding issues).
JWTSessionManager
Link
JWTSessionManager(session_timeout=900, refresh_timeout=86400, max_concurrent_sessions=10, secret_key=None, leeway=2, api_token_dir=gettempdir())
Bases: SessionManager
Manage JWT-based user sessions with configurable timeouts and concurrency limits.
This session manager extends SessionManager by issuing JSON Web Tokens (JWT) for authentication.
An access token is short‑lived and is used for authorizing API calls, while a refresh token
is long‑lived and can be exchanged for a new access token when the original expires.
An api token is long‑lived and adds dataset-specific rights to the token with a custom datasets claims.
The manager keeps track of active access tokens to enforce a maximum number of concurrent
sessions per application instance. Tokens are signed with a secret key that is either supplied by
the caller or generated automatically. All tokens conform to RFC7519 and contain the standard
registered claims (iss, sub, aud, exp, iat, jti) plus a custom type claim that
identifies the token as 'access', 'api' or 'refresh'.
Attributes:
| Name | Type | Description |
|---|---|---|
sessions |
Dict[str, dict]
|
A dictionary storing active sessions. Each key is a session ID, and each value is a dictionary containing: - 'username': str - The user associated with this session. - 'created_at': datetime - When the session was created. - 'last_accessed': datetime - Last time the session was accessed. - 'expires_at': datetime - Expiry time of the session. |
session_timeout |
int
|
Duration in seconds after which a session expires.
The default value ( |
max_concurrent_sessions |
int
|
The maximum number of concurrent sessions to allow. |
logger |
Logger
|
The logger to use for this session manager. |
refresh_timeout |
int
|
Lifetime of a refresh token in seconds.
The default value ( |
secret_key |
str | bytes | None
|
Secret used for HS512 signing of JWTs.
If |
refresh_tokens |
dict
|
Mapping from refresh token identifier ( |
_lock |
Lock
|
A locking mechanism to lock |
api_token_dir |
str or Path
|
Directory where the |
Manage user sessions with timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The duration for which the access token should be valid in seconds.
Defaults to |
900
|
|
int
|
The duration for which the refresh token should be valid in seconds.
Defaults to |
86400
|
|
int
|
The maximum number of concurrent sessions to allow.
Defaults to |
10
|
|
str | bytes | None
|
Secret used for HS512 signing of JWTs.
- If a |
None
|
|
int
|
Allowed leeway, in seconds, after tokens expiration date, to accommodate for clock-skew.
Set it to |
2
|
|
str or Path
|
Directory where the |
gettempdir()
|
Source code in plantdb/commons/auth/session.py
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 | |
cleanup_expired_sessions
Link
cleanup_expired_sessions()
Remove expired sessions from tracking.
Source code in plantdb/commons/auth/session.py
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 | |
create_api_token
Link
Generate a new API token for a user.
This method creates a time‑limited API token associated with the specified username.
If token_exp is None the token will expire one hour from the moment of creation.
An optional list of datasets can be provided to restrict the token's access scope.
The generated token is persisted via the internal storage mechanism.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Identifier of the user for whom the token is being created. |
required |
|
If a string, there should be an iso-formatted expiration date.
If an integer, act as an expiration interval in seconds.
Use of a datetime is possible.
By default, use |
3600
|
|
|
Optional collection of dataset identifiers that the token should be allowed to access. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The newly created API token. |
Notes
The token includes a unique identifier generated with secrets and is timestamped using UTC.
The internal helper methods handle token assembly and storage, ensuring consistency across calls.
Examples:
>>> from plantdb.commons.auth.session import JWTSessionManager
>>> from plantdb.commons.auth.models import Permission
>>> manager = JWTSessionManager()
>>> api_token = manager.create_api_token('batman', datasets={'joker': [Permission.DELETE]})
>>> print(manager.api_token_file)
>>> with open(manager.api_token_file, 'rb') as f: print(f.read())
Source code in plantdb/commons/auth/session.py
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 | |
create_session
Link
create_session(username)
Create a new session for a user.
If the user already has an active session, it returns the existing session ID. Otherwise, it creates a new session and returns its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the user for whom to create a session. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[str, str] or None
|
A tuple containing (access_token, refresh_token) if successful, |
Notes
Creates JSON Web Tokens following RFC 7519 standards with registered claims:
- iss (issuer): Identifies the token issuer
- sub (subject): The username of the authenticated user
- aud (audience): Intended audience for the token
- exp (expiration time): Token expiration timestamp
- iat (issued at): Token creation timestamp
- jti (JWT ID): Unique identifier for the token generated using secrets.token_urlsafe.
Source code in plantdb/commons/auth/session.py
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 | |
has_logged_user
Link
has_logged_user()
Check if there is at least one active (logged‑in) user.
This method first cleans up any expired sessions and then determines
whether the internal sessions dictionary contains any entries.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in plantdb/commons/auth/session.py
244 245 246 247 248 249 250 251 252 253 254 255 256 | |
invalidate_api_token
Link
invalidate_api_token(token)
Revoke an API token, removing it from memory and the persistent file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The full JWT string of the API token to revoke. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in plantdb/commons/auth/session.py
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 | |
invalidate_session
Link
Invalidate a session by removing it from tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
JSON Web Token to invalidate |
None
|
|
str
|
Token ID to invalidate directly |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
str
|
The username corresponding to the invalidated JSON Web Token |
Source code in plantdb/commons/auth/session.py
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 | |
n_active_sessions
Link
n_active_sessions()
Returns the number of active sessions.
Cleans up expired sessions before counting and returns the number of remaining active sessions in the collection.
Returns:
| Type | Description |
|---|---|
int
|
The number of currently active sessions. |
See Also
cleanup_expired_sessions : Cleans up the expired sessions in the collection.
Source code in plantdb/commons/auth/session.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
refresh_session
Link
refresh_session(refresh_token)
Refresh a session using a valid refresh token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The refresh token to use. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[str, str]
|
A tuple containing (new_access_token, new_refresh_token) if successful. |
Source code in plantdb/commons/auth/session.py
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 | |
session_token
Link
session_token(username)
Retrieve the active session token, if any, for a given username.
This method cleans up any expired sessions first and then searches the internal
sessions attribute dictionary for a session belonging to the supplied username.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The username whose session ID is requested. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The session ID associated with |
Source code in plantdb/commons/auth/session.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
session_username
Link
session_username(token)
Extract username from JSON Web Token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Current JSON Web Token. |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
The corresponding username if the token is valid. |
Source code in plantdb/commons/auth/session.py
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 | |
validate_session
Link
validate_session(token)
Validate a JSON Web Token and return user information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The JSON Web Token to validate. |
required |
Returns:
| Type | Description |
|---|---|
dict or None
|
User information if valid,
|
Source code in plantdb/commons/auth/session.py
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 | |
NoAuthSessionManager
Link
NoAuthSessionManager(session_timeout=3600)
Bases: SessionManager
A session manager for testing where every request is considered
authenticated as the built‑in admin user.
- The admin token is created once at construction and reused.
validate_sessionalways succeeds (refreshes the token only when it has expired).- Suitable for use in
plantdb.commons.fsdb.core.FSDBtests and docstring examples where security is irrelevant.
Examples:
>>> from plantdb.commons.auth.session import NoAuthSessionManager
>>> noauth_sm = NoAuthSessionManager()
>>> token = noauth_sm.admin_token()
>>> noauth_sm.validate_session(token)['username']
'admin'
>>> # Any request that expects a session manager can now receive `noauth_sm` without worrying about authentication.
>>> from plantdb.commons.test_database import setup_test_database
>>> from plantdb.commons.fsdb.core import FSDB
>>> db_path = setup_test_database('real_plant')
>>> db = FSDB(db_path, session_manager=NoAuthSessionManager())
>>> db.connect()
>>> scan = db.get_scan('real_plant') # no need to log in to access the dataset
>>> scan.set_metadata('test', "No authentication required to write stuff!")
>>> print(scan.get_metadata('test'))
No authentication required to write stuff!
Source code in plantdb/commons/auth/session.py
553 554 555 556 557 558 559 560 561 | |
admin_token
Link
admin_token()
Return the (static) admin token.
Source code in plantdb/commons/auth/session.py
566 567 568 | |
cleanup_expired_sessions
Link
cleanup_expired_sessions()
Remove expired sessions from the session dictionary.
This method iterates through all stored sessions and deletes any that have an expiration time earlier than the current time.
Notes
This function modifies the self.sessions dictionary in-place.
Source code in plantdb/commons/auth/session.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
create_session
Link
create_session(username=None)
Ignore the supplied username and always return the pre‑created admin token.
Source code in plantdb/commons/auth/session.py
573 574 575 | |
has_logged_user
Link
has_logged_user()
Check if there is at least one active (logged‑in) user.
This method first cleans up any expired sessions and then determines
whether the internal sessions dictionary contains any entries.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in plantdb/commons/auth/session.py
244 245 246 247 248 249 250 251 252 253 254 255 256 | |
invalidate_session
Link
invalidate_session(session_id)
Remove the given session identifier from the active sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the session to be removed. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
str | None
|
The username corresponding to the invalidated session |
Notes
The session ID is removed from the internal session dictionary. If the session does not exist, this method has no effect.
Source code in plantdb/commons/auth/session.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
n_active_sessions
Link
n_active_sessions()
Returns the number of active sessions.
Cleans up expired sessions before counting and returns the number of remaining active sessions in the collection.
Returns:
| Type | Description |
|---|---|
int
|
The number of currently active sessions. |
See Also
cleanup_expired_sessions : Cleans up the expired sessions in the collection.
Source code in plantdb/commons/auth/session.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
refresh_session
Link
refresh_session(session_id)
Refresh a session if it's still valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Current session token |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
New session token if refresh is successful |
Source code in plantdb/commons/auth/session.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
session_token
Link
session_token(username)
Retrieve the active session token, if any, for a given username.
This method cleans up any expired sessions first and then searches the internal
sessions attribute dictionary for a session belonging to the supplied username.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The username whose session ID is requested. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The session ID associated with |
Source code in plantdb/commons/auth/session.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
session_username
Link
session_username(session_id)
Always return admin for any session identifier.
Source code in plantdb/commons/auth/session.py
591 592 593 594 | |
validate_session
Link
validate_session(session_id)
Validate the stored admin token.
If it has expired, recreate it and return the fresh session information.
Source code in plantdb/commons/auth/session.py
577 578 579 580 581 582 583 584 585 586 587 588 589 | |
RefreshTokenNotFoundError
Link
Bases: SessionValidationError
Raised when a refresh token isn’t present in the active‑refresh‑store.
SessionManager
Link
SessionManager(session_timeout=3600, max_concurrent_sessions=10)
Manages user sessions with expiration and validation.
This class provides methods to create, validate, invalidate, and cleanup expired sessions. Each session is associated with a unique identifier (session_id) and has an expiry time based on the session timeout duration specified during initialization.
Attributes:
| Name | Type | Description |
|---|---|---|
sessions |
Dict[str, dict]
|
A dictionary storing active sessions. Each key is a session ID, and each value is a dictionary containing: - 'username': str - The user associated with this session. - 'created_at': datetime - When the session was created. - 'last_accessed': datetime - Last time the session was accessed. - 'expires_at': datetime - Expiry time of the session. |
session_timeout |
int
|
Duration in seconds after which a session expires. |
max_concurrent_sessions |
int
|
The maximum number of concurrent sessions to allow. |
logger |
Logger
|
The logger to use for this session manager. |
Manage user sessions with timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The duration for which the session should be valid in seconds.
A session that exceeds this duration will be considered expired and removed.
Defaults to |
3600
|
|
int
|
The maximum number of concurrent sessions to allow.
Defaults to |
10
|
Source code in plantdb/commons/auth/session.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
cleanup_expired_sessions
Link
cleanup_expired_sessions()
Remove expired sessions from the session dictionary.
This method iterates through all stored sessions and deletes any that have an expiration time earlier than the current time.
Notes
This function modifies the self.sessions dictionary in-place.
Source code in plantdb/commons/auth/session.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
create_session
Link
create_session(username)
Create a new session for a user.
If the user already has an active session, it returns the existing session ID. Otherwise, it creates a new session and returns its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the user for whom to create a session. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The ID of the created or existing session. |
Notes
The session ID is a token generated using secrets.token_urlsafe.
The session data includes the user ID, creation timestamp, last accessed timestamp, and expiration timestamp.
Source code in plantdb/commons/auth/session.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
has_logged_user
Link
has_logged_user()
Check if there is at least one active (logged‑in) user.
This method first cleans up any expired sessions and then determines
whether the internal sessions dictionary contains any entries.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in plantdb/commons/auth/session.py
244 245 246 247 248 249 250 251 252 253 254 255 256 | |
invalidate_session
Link
invalidate_session(session_id)
Remove the given session identifier from the active sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the session to be removed. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
str | None
|
The username corresponding to the invalidated session |
Notes
The session ID is removed from the internal session dictionary. If the session does not exist, this method has no effect.
Source code in plantdb/commons/auth/session.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
n_active_sessions
Link
n_active_sessions()
Returns the number of active sessions.
Cleans up expired sessions before counting and returns the number of remaining active sessions in the collection.
Returns:
| Type | Description |
|---|---|
int
|
The number of currently active sessions. |
See Also
cleanup_expired_sessions : Cleans up the expired sessions in the collection.
Source code in plantdb/commons/auth/session.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
refresh_session
Link
refresh_session(session_id)
Refresh a session if it's still valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Current session token |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
New session token if refresh is successful |
Source code in plantdb/commons/auth/session.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
session_token
Link
session_token(username)
Retrieve the active session token, if any, for a given username.
This method cleans up any expired sessions first and then searches the internal
sessions attribute dictionary for a session belonging to the supplied username.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The username whose session ID is requested. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The session ID associated with |
Source code in plantdb/commons/auth/session.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
session_username
Link
session_username(session_id)
Retrieve the username associated with a given session ID.
The method validates the supplied session ID by delegating to validate_session.
If the session is active, the username stored in the session data is returned;
otherwise None is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier for the session to query. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The username linked to the session, or |
Source code in plantdb/commons/auth/session.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
validate_session
Link
validate_session(session_id)
Validate a given session by checking its existence and expiration status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the session to be validated. |
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
A dictionary with user information if valid,
|
Notes
The validate_session method updates the session's last accessed time upon successful validation.
Source code in plantdb/commons/auth/session.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
SessionValidationError
Link
SingleSessionManager
Link
SingleSessionManager(session_timeout=3600, **kwargs)
Bases: SessionManager
Generate a single-session manager for handling database connections.
The SingleSessionManager class is designed to manage a single active
database session at any given time. It inherits from the base SessionManager
class and overrides its initialization to ensure only one concurrent session
is allowed, even if the base class allows more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The timeout duration for each database session in seconds. If not specified, defaults to 3600 (1 hour). |
3600
|
Attributes:
| Name | Type | Description |
|---|---|---|
sessions |
Dict[str, dict]
|
A dictionary storing active sessions. Each key is a session ID, and each value is a dictionary containing: - 'username': str - The user associated with this session. - 'created_at': datetime - When the session was created. - 'last_accessed': datetime - Last time the session was accessed. - 'expires_at': datetime - Expiry time of the session. |
session_timeout |
int
|
The configured timeout duration for sessions. |
max_concurrent_sessions |
int
|
Always set to 1 to ensure only one concurrent session is allowed. |
logger |
Logger
|
The logger to use for this session manager. |
Examples:
>>> from plantdb.commons.auth.session import SingleSessionManager
>>> # Initialize the session manager
>>> manager = SingleSessionManager()
>>> # Create a new session with the username 'test'
>>> session_token = manager.create_session('test')
>>> # Attempt to create another session with the username 'test2'
>>> _ = manager.create_session('test2')
WARNING [SessionManager] Reached max concurrent sessions limit (1)
>>> # Validate the session and get its info
>>> session = manager.validate_session(session_token)
>>> print(session['expires_at']) # Print the expiration date
>>> # Refresh the session using the existing session token
>>> new_session_token = manager.refresh_session(session_token)
>>> # Validate the session and get its info
>>> session = manager.validate_session(new_session_token)
>>> print(session['expires_at']) # Print the expiration date of the refreshed session
Notes
The SingleSessionManager enforces a single-session policy, which means any
attempt to create more than one active session will result in an error or be
handled according to the logic defined within this class.
See Also
session_manager.SessionManager : Base class for managing database sessions.
Source code in plantdb/commons/auth/session.py
520 521 | |
cleanup_expired_sessions
Link
cleanup_expired_sessions()
Remove expired sessions from the session dictionary.
This method iterates through all stored sessions and deletes any that have an expiration time earlier than the current time.
Notes
This function modifies the self.sessions dictionary in-place.
Source code in plantdb/commons/auth/session.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
create_session
Link
create_session(username)
Create a new session for a user.
If the user already has an active session, it returns the existing session ID. Otherwise, it creates a new session and returns its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the user for whom to create a session. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The ID of the created or existing session. |
Notes
The session ID is a token generated using secrets.token_urlsafe.
The session data includes the user ID, creation timestamp, last accessed timestamp, and expiration timestamp.
Source code in plantdb/commons/auth/session.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
has_logged_user
Link
has_logged_user()
Check if there is at least one active (logged‑in) user.
This method first cleans up any expired sessions and then determines
whether the internal sessions dictionary contains any entries.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in plantdb/commons/auth/session.py
244 245 246 247 248 249 250 251 252 253 254 255 256 | |
invalidate_session
Link
invalidate_session(session_id)
Remove the given session identifier from the active sessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the session to be removed. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
str | None
|
The username corresponding to the invalidated session |
Notes
The session ID is removed from the internal session dictionary. If the session does not exist, this method has no effect.
Source code in plantdb/commons/auth/session.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
n_active_sessions
Link
n_active_sessions()
Returns the number of active sessions.
Cleans up expired sessions before counting and returns the number of remaining active sessions in the collection.
Returns:
| Type | Description |
|---|---|
int
|
The number of currently active sessions. |
See Also
cleanup_expired_sessions : Cleans up the expired sessions in the collection.
Source code in plantdb/commons/auth/session.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
refresh_session
Link
refresh_session(session_id)
Refresh a session if it's still valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
Current session token |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
New session token if refresh is successful |
Source code in plantdb/commons/auth/session.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
session_token
Link
session_token(username)
Retrieve the active session token, if any, for a given username.
This method cleans up any expired sessions first and then searches the internal
sessions attribute dictionary for a session belonging to the supplied username.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The username whose session ID is requested. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The session ID associated with |
Source code in plantdb/commons/auth/session.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
session_username
Link
session_username(session_id)
Retrieve the username associated with a given session ID.
The method validates the supplied session ID by delegating to validate_session.
If the session is active, the username stored in the session data is returned;
otherwise None is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier for the session to query. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The username linked to the session, or |
Source code in plantdb/commons/auth/session.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
validate_session
Link
validate_session(session_id)
Validate a given session by checking its existence and expiration status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
str
|
The unique identifier of the session to be validated. |
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
A dictionary with user information if valid,
|
Notes
The validate_session method updates the session's last accessed time upon successful validation.
Source code in plantdb/commons/auth/session.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
TokenType
Link
Bases: Enum
Canonical token types used throughout the API.
__eq__
Link
__eq__(other)
Equality operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Object to compare with the token type instance.
If a string is provided, it is interpreted as a token type name and converted to a
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Notes
The method safely handles objects that do not expose a value attribute.
This ensures that comparisons with unrelated types do not raise unexpected exceptions.
Examples:
>>> from plantdb.commons.auth.session import TokenType
>>> tt = TokenType.ACCESS
>>> tt == TokenType.ACCESS # direct comparison with TokenType
True
>>> tt == 'access' # comparison with string
True
>>> tt == 'Access' # comparison with string is case-insensitive
True
>>> tt == TokenType.API # direct comparison with TokenType
False
>>> tt == 'api' # comparison with string
Fasle
Source code in plantdb/commons/auth/session.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |