Skip to content

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:

  1. Creates a Flask app
  2. Sets up a local test database with a JSON Web Token session manager
  3. Registers the Login and Logout resources to a REST API
  4. 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

CreateApiToken(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
624
625
626
627
628
629
630
631
632
633
634
635
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
@add_jwt_from_header
def post(self, **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.
    """
    data = request.get_json()
    if "datasets" not in data:
        return {'error': 'Missing "datasets" field'}, 400
    if "token_exp" not in data:
        return {'error': 'Missing "token_exp" field'}, 400
    token_exp = int(data['token_exp'])

    try:
        token = self.db.create_api_token(
            token_exp=token_exp,
            datasets=data['datasets'],
            **kwargs
        )
    except Exception as e:
        response = {'error': f'Token creation failed: {e}'}, 500
    else:
        exp_date = datetime.now(timezone.utc) + timedelta(seconds=token_exp)
        response = (
            {
                "message": "API Token generated successfully",
                "api_token": token,
                "expiration date": exp_date.isoformat(),
            },
            200,
        )

    return response

Login Link

Login(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
255
256
257
258
259
260
261
262
263
264
265
266
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

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 username is missing, the dictionary will contain an error message. Otherwise, the dictionary will contain the username and a boolean indicating whether it exist or not.

int

An HTTP status code. If the username is missing the status code will be 400, otherwise 200.

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 the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # 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}
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/auth.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
@rate_limit(max_requests=120, window_seconds=60)
def get(self):
    """Checks if a given username exists in the database and returns the result.

    Returns
    -------
    dict
        A dictionary with the result and an HTTP status code.
        If the `username` is missing, the dictionary will contain an error message.
        Otherwise, the dictionary will contain the `username` and a boolean indicating whether it exist or not.
    int
        An HTTP status code. If the `username` is missing  the status code will be ``400``, otherwise ``200``.

    Raises
    ------
    http.client.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 the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # 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}
    >>> # Stop the test server
    >>> server.stop()
    """
    # Extract username from query parameters
    username = request.args.get('username', None)
    # Return an error if the username parameter is missing
    if not username:
        response = {'error': 'Missing username parameter'}, 400
    else:
        # Query database to check if the user exists
        user_exists = check_username_exists(self.db, username)
        response = {'username': username, 'exists': user_exists}, 200

    return response

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 (True if successful, False otherwise). - 'message' : str A message describing the result of the authentication attempt.

int

The HTTP status code (200 for successful response, 400 for bad request).

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 the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # 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.ok)
True
>>> # 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
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/auth.py
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
@rate_limit(max_requests=20, window_seconds=60)
def post(self):
    """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
    -------
    dict
        A dictionary with the following keys and values:
            - 'authenticated' : bool
                The result of the authentication process (``True`` if successful, ``False`` otherwise).
            - 'message' : str
                A message describing the result of the authentication attempt.
    int
        The HTTP status code (``200`` for successful response, ``400`` for bad request).

    Raises
    ------
    werkzeug.exceptions.BadRequest
        If the request doesn't contain valid JSON data (handled by Flask)
    http.client.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 the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # 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.ok)
    True
    >>> # 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
    >>> # Stop the test server
    >>> server.stop()
    """
    # Get JSON data from the request body
    data = request.get_json()
    # Validate that required fields are present in the request
    if not data or 'username' not in data or 'password' not in data:
        return {'authenticated': False, 'error': 'Missing username or password'}, 400

    # Extract credentials from request data
    username = data['username']
    password = data['password']

    try:
        access_token, refresh_token = authenticate_user(self.db, username, password)
    except InvalidCredentialsError:
        response = {'error': 'Invalid credentials'}, 401  # HTTP 401 Unauthorized (authentication)
    except Exception as e:
        response = {'error': f'Authentication failed: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        # Build the successful response with user info, access token, and refresh token
        user = self.db.get_user_data(token=access_token)
        response = {
            'message': 'Login successful',
            'user': {
                'username': user.username,
                'fullname': user.fullname,
            },
            'access_token': access_token,
            'refresh_token': refresh_token
        }, 200

    return response

Logout Link

Logout(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
423
424
425
426
427
428
429
430
431
432
433
434
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

post Link

post(**kwargs)

Handle user logout.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # 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
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/auth.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
@add_jwt_from_header
def post(self, **kwargs):
    """Handle user logout.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # 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
    >>> # Stop the test server
    >>> server.stop()
    """
    # The decorator supplies the token via kwargs
    token = kwargs.get('token')
    if not token:
        self.logger.error("Logout error: no active session!")
        return {'error': 'Logout failed, no active session!'}, 401  # HTTP 401 Unauthorized (authentication)

    try:
        # Delegate to the service layer
        username = logout_user(self.db, token, logger=self.logger)
    except NoAuthUserError as e:
        response = {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except Exception as e:
        self.logger.error(f"Logout error: {str(e)}")
        response = {'error': 'Logout failed!'}, 500  # HTTP 500 Internal Server Error
    else:
        response = {'message': f'Logout successful from {username}'}, 200

    return response

Register Link

Register(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
137
138
139
140
141
142
143
144
145
146
147
148
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger

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 (201 for success, 400 for error)

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 the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> # 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'
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/auth.py
150
151
152
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
235
236
237
238
239
@rate_limit(max_requests=5, window_seconds=60)  # maximum of 1 requests per minute
@add_jwt_from_header
def post(self, **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
    -------
    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 (``201`` for success, ``400`` for error)

    Raises
    ------
    http.client.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 the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> # 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'
    >>> # Stop the test server
    >>> server.stop()
    """
    # Parse JSON data from request body
    data = request.get_json()
    # Check if all required fields are present in the request
    required_fields = ['username', 'fullname', 'password']
    if not data or not all(field in data for field in required_fields):
        return {
            'success': False,
            'error': 'Missing required fields. Please provide username, fullname, and password'
        }, 400

    try:
        # Delegate to the service layer
        register_user(self.db, data, token=kwargs.get('token'))
    except MissingFieldError as e:
        response = {'error': str(e)}, 400  # HTTP 400 Bad Request
    except NoAuthUserError as e:
        response = {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except SessionValidationError as e:
        response = {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except UserExistsError as e:
        response = {'error': f'Failed to create user: {str(e)}'}, 409  # HTTP 409 Conflict
    except Exception as e:
        response = {'error': f'Failed to create user: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        response = {'message': f"User {data['username']} successfully created"}, 201

    return response

TokenRefresh Link

TokenRefresh(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
574
575
576
577
578
579
580
581
582
583
584
585
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def post(self, **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.
    """
    data = request.get_json()
    refresh_token_str = data.get('refresh_token')
    try:
        # Delegate to the service layer
        access_token, new_refresh_token = refresh_token(self.db, refresh_token_str)
    except NoAuthUserError as e:
        response = {'error': str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except TokenError as e:
        response = {'error': f'Invalid or expired refresh token: {str(e)}'}, 401  # HTTP 401 Unauthorized (authentication)
    except Exception as e:
        response = {'error': f'Token refresh failed: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        response = {
            'message': 'Token refreshed successfully',
            'access_token': access_token,
            'refresh_token': new_refresh_token
        }, 200

    return response

TokenValidation Link

TokenValidation(db, logger=None)

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

db Link

FSDB

A database instance providing the resources to serve.

required

logger Link

Logger

A logger instance to record operations and errors.

None
Source code in plantdb/server/api/auth.py
498
499
500
501
502
503
504
505
506
507
508
509
def __init__(self, db, logger=None):
    """Initialize the resource.

    Parameters
    ----------
    db : plantdb.commons.fsdb.core.FSDB
        A database instance providing the resources to serve.
    logger : logging.Logger
        A logger instance to record operations and errors.
    """
    self.db: FSDB = db
    self.logger: logging.Logger = logger if logger else get_logger(self.__class__.__name__)

post Link

post(**kwargs)

Handle JSON Web Token validation.

Examples:

>>> # Start the REST API server (in test mode)
>>> from plantdb.server.test_rest_api import TestRestApiServer
>>> # Create a test database and start the Flask App serving a REST API
>>> server = TestRestApiServer(test=True)
>>> server.start()
>>> import requests
>>> from plantdb.commons import api_endpoints
>>> from plantdb.commons import api_endpoints
>>> # Start by login as admin
>>> response = requests.post("http://127.0.0.1:5000" + api_endpoints.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" + api_endpoints.token_validation(), headers={'Authorization': 'Bearer ' + token})
>>> print(response.json()['message'])
Token validation successful
>>> # Stop the test server
>>> server.stop()
Source code in plantdb/server/api/auth.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
@add_jwt_from_header
def post(self, **kwargs):
    """Handle JSON Web Token validation.

    Examples
    --------
    >>> # Start the REST API server (in test mode)
    >>> from plantdb.server.test_rest_api import TestRestApiServer
    >>> # Create a test database and start the Flask App serving a REST API
    >>> server = TestRestApiServer(test=True)
    >>> server.start()

    >>> import requests
    >>> from plantdb.commons import api_endpoints
    >>> from plantdb.commons import api_endpoints
    >>> # Start by login as admin
    >>> response = requests.post("http://127.0.0.1:5000" + api_endpoints.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" + api_endpoints.token_validation(), headers={'Authorization': 'Bearer ' + token})
    >>> print(response.json()['message'])
    Token validation successful
    >>> # Stop the test server
    >>> server.stop()
    """
    # The decorator supplies the token via kwargs
    token = kwargs.get('token')

    try:
        # Delegate to the service layer
        user_info = validate_token(self.db, token)
    except NoAuthUserError as e:
        response = {"error": str(e)}, 401  # HTTP 401 Unauthorized (authentication)
    except TokenError as e:
        response = {'error': f'Token validation failed: {str(e)}'}, 401  # HTTP 401 Unauthorized (authentication)
    except Exception as e:
        response = {'error': f'Unexpected error: {str(e)}'}, 500  # HTTP 500 Internal Server Error
    else:
        response = {
            'message': 'Token validation successful',
            'user': user_info,
        }, 200

    return response