auth
Authentication REST API ResourcesLink
Provides Flask‑RESTful resources that implement a complete authentication workflow for the PlantDB server, including user registration, login, logout, JWT validation, and token refresh. The resources add security features such as rate‑limiting and automatic JWT extraction, making it easy to protect API endpoints while keeping the codebase tidy.
Key FeaturesLink
- Register - Create new user accounts with input validation, rate limiting, and JWT handling.
- Login - Check username existence, authenticate credentials, and return access/refresh tokens.
- Logout - Invalidate a user session and log the outcome.
- TokenValidation - Verify a JWT and return the associated user's basic profile information.
- TokenRefresh - Issue a fresh access token given a valid refresh token.
- Built‑in decorators (
@rate_limit,@add_jwt_from_header) ensure consistent security across all endpoints.
Usage ExamplesLink
Hereafter is a minimal working example that:
- Creates a
Flaskapp - Sets up a local test database with a JSON Web Token session manager
- Registers the
LoginandLogoutresources to a REST API - Starts the app
>>> import logging
>>> from flask import Flask
>>> from flask_restful import Api
>>> from plantdb.server.api.auth import Login, Logout
>>> from plantdb.commons.auth.session import JWTSessionManager
>>> from plantdb.commons.fsdb.core import FSDB
>>> from plantdb.commons.test_database import setup_test_database
>>> # Create a Flask application
>>> app = Flask(__name__)
>>> # Create a logger
>>> logger = logging.getLogger("plantdb.auth")
>>> logger.setLevel(logging.INFO)
>>> # Initialize a test database with a JWTSessionManager
>>> db_path = setup_test_database('real_plant')
>>> mgr = JWTSessionManager()
>>> db = FSDB(db_path, session_manager=mgr)
>>> db.connect()
>>> # RESTful API and resource registration
>>> api = Api(app)
>>> api.add_resource(Login, "/login", resource_class_kwargs={"db": db})
>>> api.add_resource(Logout, "/logout", resource_class_kwargs={"db": db, "logger": logger})
>>> # Start the APP
>>> app.run(host='0.0.0.0', port=5000)
It may be used as follows (in another Python REPL):
>>> import requests
>>> # Check if the user exists (valid username):
>>> response = requests.get("http://127.0.0.1:5000/login?username=admin")
>>> print(response.json())
{'username': 'admin', 'exists': True}
>>> # Login with default 'admin' credentials
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin', 'password': 'admin'})
>>> print(response.json())
{'access_token': 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwbGFudGRiLWFwaSIsInN1YiI6ImFkbWluIiwiYXVkIjoicGxhbnRkYi1jbGllbnQiLCJleHAiOjE3NzIxMzkxNzcsImlhdCI6MTc3MjEzODI3NywianRpIjoid2N2NnozNHg4aTY5SG5LTG9WaUk4dyIsInR5cGUiOiJhY2Nlc3MifQ.lmOkQMbp-EvfdIiuUq6u-yqIpDC32d8gCoZUBtMUc-mC6gC8pb3RPQPnwIhATyjrqWS-aMq-9WuTD-4ogU5EGg', 'message': 'Login successful', 'refresh_token': 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwbGFudGRiLWFwaSIsInN1YiI6ImFkbWluIiwiYXVkIjoicGxhbnRkYi1jbGllbnQiLCJleHAiOjE3NzIyMjQ2NzcsImlhdCI6MTc3MjEzODI3NywianRpIjoiVW1seVQ4M2J1LUVqcUhaTGhENy1GQSIsInR5cGUiOiJyZWZyZXNoIn0.jP1rPM4lfOwxARksOEK35z2DOK2ntGwFJ7b_waYfKu-SWcQXiS3gujz29RrHr0J_JcUy92vtRa-aYh78FEWfPA', 'user': {'fullname': 'PlantDB Admin', 'username': 'admin'}}
>>> token = response.json()['access_token']
>>> # Now try to log out:
>>> response = requests.post("http://127.0.0.1:5000/logout", headers={'Authorization': 'Bearer ' + token})
>>> print(response.json()['message'])
Logout successful from admin
CreateApiToken
Link
Bases: Resource
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
593 594 595 596 597 598 599 600 601 602 603 604 | |
post
Link
post(**kwargs)
Refresh JSON Web Token.
This method expects a JSON payload containing a 'refresh_token'. It validates the refresh token and issues a new access/refresh token pair.
Source code in plantdb/server/api/auth.py
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
Login
Link
Bases: Resource
A RESTful resource to handle user login and authentication processes.
This class processes HTTP requests for user authentication, including checking if a username exists in the database and validating login credentials.
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
251 252 253 254 255 256 257 258 259 260 261 262 | |
get
Link
get()
Checks if a given username exists in the database and returns the result.
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary with the result and an HTTP status code.
If the |
int
|
An HTTP status code. If the |
Raises:
| Type | Description |
|---|---|
HTTPException
|
If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client. |
Notes
In the URL, you can use the username parameter to check if a user exists.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Check if the user exists (valid username):
>>> response = requests.get("http://127.0.0.1:5000/login?username=admin")
>>> print(response.json())
{'username': 'admin', 'exists': True}
>>> # Check if the user exists (invalid username):
>>> response = requests.get("http://127.0.0.1:5000/login?username=superman")
>>> print(response.json())
{'username': 'superman', 'exists': False}
Source code in plantdb/server/api/auth.py
264 265 266 267 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 306 307 | |
post
Link
post()
Handle user authentication via POST request with username and password.
This method processes a POST request containing user credentials (username and password) and validates them against stored user data. It returns authentication status and a descriptive message.
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary with the following keys and values:
- 'authenticated' : bool
The result of the authentication process ( |
int
|
The HTTP status code ( |
Raises:
| Type | Description |
|---|---|
BadRequest
|
If the request doesn't contain valid JSON data (handled by Flask) |
HTTPException
|
If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client. |
Notes
The method expects a JSON payload with 'username' and 'password' fields.
The authentication process uses the check_credentials method to validate
the provided credentials against the database.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Valid login request
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin', 'password': 'admin'})
>>> print(response.json())
{'authenticated': True, 'message': 'Login successful. Welcome, Guy Fawkes!'}
>>> print(response.status_code)
200
>>> # Invalid request (missing credentials)
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin'})
>>> print(response.json())
{'authenticated': False, 'message': 'Missing username or password'}
>>> print(response.status_code)
400
Source code in plantdb/server/api/auth.py
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 344 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
Logout
Link
Bases: Resource
Resource handling user logout requests.
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
401 402 403 404 405 406 407 408 409 410 411 412 | |
post
Link
post(**kwargs)
Handle user logout.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Start by log in as 'admin'
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin', 'password': 'admin'})
>>> print(response.json()['message'])
Login successful
>>> token = response.json()['access_token']
>>> # Now try to log out:
>>> response = requests.post("http://127.0.0.1:5000/logout", headers={'Authorization': 'Bearer ' + token})
>>> print(response.json()['message'])
Logout successful
Source code in plantdb/server/api/auth.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 | |
Register
Link
Bases: Resource
A RESTful resource to manage user registration via HTTP POST requests.
Responsible for handling the registration process by validating and creating user records in the database. This class provides a structured way to interact with user data, ensuring error handling and proper responses for client requests. Only users with ADMIN rights can add user records.
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
140 141 142 143 144 145 146 147 148 149 150 151 | |
post
Link
post(**kwargs)
Handle HTTP POST request to register a new user.
Processes user registration by validating the input data and creating a new user in the database. Expects a JSON payload in the request body with required user details. Only users with ADMIN rights can add user records.
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary with the following keys and values: - 'success' (bool): Indicates if operation was successful - 'message' (str): Description of the operation result |
int
|
HTTP status code ( |
Raises:
| Type | Description |
|---|---|
HTTPException
|
If the rate limit is exceeded, it returns an HTTP 429 ("Too Many Requests") response to the client. |
ValueError
|
If required fields are missing from the request |
Exception
|
If user creation fails (e.g., duplicate username) |
Notes
- The rate limit is enforced per client IP address
- The method doesn't take direct parameters but expects a JSON payload in the request body with the following fields:
- username: Unique identifier for the user.
- fullname: User's full name.
- password: User's password (will be hashed before storage).
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Start by login as admin to have permission to create new users
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin', 'password': 'admin'})
>>> token = response.json()['access_token']
>>> # Now create a new user:
>>> new_user = {"username":"batman", "fullname":"Bruce Wayne", "password":"Alfred123!"}
>>> response = requests.post("http://127.0.0.1:5000/register", json=new_user, headers={'Authorization': 'Bearer ' + token})
>>> res_dict = response.json()
>>> res_dict["success"]
True
>>> res_dict["message"]
'User successfully created'
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'batman', 'password': 'Alfred123!'})
>>> res_dict = response.json()
>>> res_dict["message"]
'Login successful'
Source code in plantdb/server/api/auth.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
TokenRefresh
Link
Bases: Resource
Refresh JSON Web Token for an authenticated user.
The TokenRefresh resource provides an endpoint that accepts an
existing JSON Web Token, validates the current session, and issues a new
access token when the refresh is successful. The resource interacts
with a database session manager that exposes a refresh_session method
to perform the actual token renewal.
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
539 540 541 542 543 544 545 546 547 548 549 550 | |
post
Link
post(**kwargs)
Refresh JSON Web Token.
This method expects a JSON payload containing a 'refresh_token'. It validates the refresh token and issues a new access/refresh token pair.
Source code in plantdb/server/api/auth.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
TokenValidation
Link
Bases: Resource
Validate a JSON Web Token (JWT) and retrieve associated user data.
The resource exposes a POST endpoint that accepts a JSON Web Token, verifies its
validity against the database session manager, and returns the authenticated
user’s basic profile information. On success a 200 response is returned
containing the user’s username and fullname; on failure a 401
response is returned with an error message.
Attributes:
| Name | Type | Description |
|---|---|---|
db |
FSDB
|
The database providing the resources to serve. |
logger |
Logger
|
The logger used to record operations and errors. |
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
FSDB
|
A database instance providing the resources to serve. |
required |
|
Logger
|
A logger instance to record operations and errors. |
None
|
Source code in plantdb/server/api/auth.py
469 470 471 472 473 474 475 476 477 478 479 480 | |
post
Link
post(**kwargs)
Handle JSON Web Token validation.
Examples:
>>> # Start a test REST API server first:
>>> # $ fsdb_rest_api --test
>>> import requests
>>> # Start by login as admin
>>> response = requests.post('http://127.0.0.1:5000/login', json={'username': 'admin', 'password': 'admin'})
>>> token = response.json()['access_token']
>>> # Now create a new user:
>>> response = requests.post("http://127.0.0.1:5000/token-validation", headers={'Authorization': 'Bearer ' + token})
>>> print(response.json()['message'])
Token validation successful
Source code in plantdb/server/api/auth.py
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |