Skip to content

login

plantimager.webui.login Link

User Authentication Module for Plant Imager Web UI.

This module provides components and callbacks for user authentication in the Plant Imager web interface, including login, logout, and user profile management.

Key Features
  • User authentication with username and password
  • User profile display with dynamically generated avatars
  • Login/logout modal interface with Bootstrap styling
  • REST API integration for authentication services
  • Secure password handling

create_avatar Link

create_avatar(fullname)

Create an avatar with user's initials in a colored circle.

Generates a circular avatar component containing the initials of a user's full name with a background color uniquely derived from the name using MD5 hashing.

Parameters:

Name Type Description Default
fullname str

The full name of the user. Can contain multiple names separated by spaces.

required

Returns:

Type Description
Div or None

A Dash HTML Div component containing the user's initials with styled background, or None if fullname is empty.

Notes
  • Background color is deterministically generated from the fullname using MD5 hash
  • Avatar is rendered as a 35x35px circle with centered text
  • Initials are automatically capitalized
  • Multiple word names will use the first letter of each word
Source code in plantimager/webui/login.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def create_avatar(fullname: str) -> html.Div | None:
    """Create an avatar with user's initials in a colored circle.

    Generates a circular avatar component containing the initials of a user's full name
    with a background color uniquely derived from the name using MD5 hashing.

    Parameters
    ----------
    fullname : str
        The full name of the user. Can contain multiple names separated by spaces.

    Returns
    -------
    dash.html.Div or None
        A Dash HTML Div component containing the user's initials with styled
        background, or ``None`` if fullname is empty.

    Notes
    -----
    - Background color is deterministically generated from the fullname using MD5 hash
    - Avatar is rendered as a 35x35px circle with centered text
    - Initials are automatically capitalized
    - Multiple word names will use the first letter of each word
    """
    if not fullname:
        return None

    # Get initials from fullname
    initials = ''.join(name[0].upper() for name in fullname.split() if name)
    # Generate a consistent color based on the fullname
    color_hash = hashlib.md5(fullname.encode('utf-8')).hexdigest()
    bg_color = f"#{color_hash[:6]}"
    avatar_style = {
        'backgroundColor': bg_color,
        'color': 'white',
        'borderRadius': '50%',
        'width': '35px',
        'height': '35px',
        'display': 'flex',
        'alignItems': 'center',
        'justifyContent': 'center',
        'fontSize': '14px',
        'fontWeight': 'bold',
    }
    return html.Div(initials, style=avatar_style)

create_login_button Link

create_login_button(is_logged_in=False, user_fullname=None)

Create a login/logout button with avatar for the navigation bar.

This function generates a navigation link component that displays either a default person icon (when logged out) or a user avatar (when logged in). The avatar is created using the user's full name initials.

Parameters:

Name Type Description Default
is_logged_in bool

Flag indicating whether a user is currently logged in. Default is False.

False
user_fullname str or None

The full name of the logged-in user. Used to create the avatar display. Default is None.

None

Returns:

Type Description
NavLink

A Bootstrap NavLink component containing either: - A user avatar (when logged in) - A default person icon (when logged out)

See Also

create_avatar : Function used to generate the user avatar display

Source code in plantimager/webui/login.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 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
def create_login_button(is_logged_in: bool = False, user_fullname: str | None = None) -> dbc.NavLink:
    """Create a login/logout button with avatar for the navigation bar.

    This function generates a navigation link component that displays either a default
    person icon (when logged out) or a user avatar (when logged in). The avatar is
    created using the user's full name initials.

    Parameters
    ----------
    is_logged_in : bool, optional
        Flag indicating whether a user is currently logged in.
        Default is ``False``.
    user_fullname : str or None, optional
        The full name of the logged-in user. Used to create the avatar display.
        Default is ``None``.

    Returns
    -------
    dash_bootstrap_components.NavLink
        A Bootstrap NavLink component containing either:
        - A user avatar (when logged in)
        - A default person icon (when logged out)

    See Also
    --------
    create_avatar : Function used to generate the user avatar display
    """
    if is_logged_in and user_fullname:
        return dbc.NavLink(
            children=create_avatar(user_fullname),
            id="login-avatar-button",
            n_clicks=0
        )
    else:
        return dbc.NavLink(
            children=html.I(className="bi bi-person-bounding-box fs-3"),
            id="login-avatar-button",
            n_clicks=0,
            style={'color': "#f3f3f3"},
        )

disable_logout_button Link

disable_logout_button(username)

Control the enabled/disabled state of the logout button.

This callback toggles the disabled state of the logout button based on whether a user is currently logged in.

Parameters:

Name Type Description Default
username str or None

The username of the logged-in user. None if no user is logged in.

required

Returns:

Type Description
bool

True if the logout button should be disabled (no user logged in), False if the button should be enabled (user is logged in).

Source code in plantimager/webui/login.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
@callback(
    Output("logout-button", "disabled"),
    Input("logged-username", "data"),

)
def disable_logout_button(username: str | None) -> bool:
    """Control the enabled/disabled state of the logout button.

    This callback toggles the disabled state of the logout button based on whether
    a user is currently logged in.

    Parameters
    ----------
    username : str or None
        The username of the logged-in user. ``None`` if no user is logged in.

    Returns
    -------
    bool
        ``True`` if the logout button should be disabled (no user logged in),
        ``False`` if the button should be enabled (user is logged in).
    """
    if username:
        return False
    return True

login Link

login(username_submit, password_submit, n_clicks, username, password, host, port, prefix)

Handle user authentication through the REST API.

This callback function processes login attempts by sending credentials to a REST API endpoint and handling the response appropriately. It manages both successful and failed login attempts, including various error conditions.

Parameters:

Name Type Description Default
username_submit int or None

Number of times the username input has been submitted via Enter key.

required
password_submit int or None

Number of times the password input has been submitted via Enter key.

required
n_clicks int or None

Number of times the login button has been clicked.

required
username str

Username entered in the login form.

required
password str

Password entered in the login form.

required
host str

The hostname or IP address of the PlantDB REST API server.

required
port int

The port number of the PlantDB REST API server.

required
prefix str

The prefix of the PlantDB REST API server.

required

Returns:

Type Description
str or None

The authenticated username if login successful, None otherwise.

str or None

The user's full name if login successful, None otherwise.

dict

CSS style dictionary for the message display.

Alert

Bootstrap alert component containing success or error message.

Raises:

Type Description
RequestException

If there are network connectivity issues or server communication problems.

JSONDecodeError

If the server response cannot be parsed as JSON.

Notes

Authentication state is maintained through Dash Store components in the application layout.

Source code in plantimager/webui/login.py
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
@callback(Output('logged-username', 'data', allow_duplicate=True),
          Output('logged-fullname', 'data', allow_duplicate=True),
          Output('login-attempt-message', 'style'),
          Output('login-attempt-message', 'children'),
          Input('username-input', 'n_submit'),
          Input('password-input', 'n_submit'),
          Input('login-button', 'n_clicks'),
          State('username-input', 'value'),
          State('password-input', 'value'),
          State('rest-api-host', 'data'),
          State('rest-api-port', 'data'),
          State('rest-api-prefix', 'data'),
          prevent_initial_call=True)
def login(
        username_submit: int,
        password_submit: int,
        n_clicks: int,
        username: str,
        password: str,
        host: str,
        port: int | str,
        prefix: str,
) -> tuple[str | None, str | None, dict, dbc.Alert]:
    """Handle user authentication through the REST API.

    This callback function processes login attempts by sending credentials to a REST API endpoint
    and handling the response appropriately. It manages both successful and failed login attempts,
    including various error conditions.

    Parameters
    ----------
    username_submit : int or None
        Number of times the username input has been submitted via Enter key.
    password_submit : int or None
        Number of times the password input has been submitted via Enter key.
    n_clicks : int or None
        Number of times the login button has been clicked.
    username : str
        Username entered in the login form.
    password : str
        Password entered in the login form.
    host : str
       The hostname or IP address of the PlantDB REST API server.
    port : int
        The port number of the PlantDB REST API server.
    prefix : str
        The prefix of the PlantDB REST API server.

    Returns
    -------
    str or None
        The authenticated username if login successful, None otherwise.
    str or None
        The user's full name if login successful, None otherwise.
    dict
        CSS style dictionary for the message display.
    dash_bootstrap_components.Alert
        Bootstrap alert component containing success or error message.

    Raises
    ------
    requests.exceptions.RequestException
        If there are network connectivity issues or server communication problems.
    json.JSONDecodeError
        If the server response cannot be parsed as JSON.

    Notes
    -----
    Authentication state is maintained through Dash Store components in the application layout.
    """
    message_style = {'display': 'block', 'margin-top': '10px'}

    try:
        # Send login request to REST API endpoint
        response = requests.post(
            urljoin(base_url(host, port, prefix), 'login'),
            data=json.dumps({'username': username, 'password': password}),
            headers={'Content-Type': 'application/json'}
        )

        if response.ok:
            # Parse successful response
            loggin_attempt = response.json()
            is_logged_in = loggin_attempt['authenticated']
            fullname = loggin_attempt['fullname']
            login_msg = loggin_attempt['message']
            if is_logged_in:
                # Setup success message display
                alert = dbc.Alert(login_msg, color="success", class_name="mb-0")
                return username, fullname, message_style, alert

        # Handle failed login attempts
        error_msg = "Login failed. Please check your credentials."
        if response.text:
            try:
                # Attempt to extract error message from response
                error_data = response.json()
                if 'message' in error_data:
                    error_msg = error_data['message']
            except json.JSONDecodeError:
                # Use raw response text if JSON parsing fails
                error_msg = response.text

        alert = dbc.Alert(error_msg, color="danger", class_name="mb-0")
        return None, None, message_style, alert

    except requests.exceptions.RequestException as e:
        # Handle connection errors (network issues, server down, etc.)
        alert = dbc.Alert(f"Connection error: {str(e)}", color="danger", class_name="mb-0")
        return None, None, message_style, alert

login_title Link

login_title(fullname=None, username=None)

Create a title for the login modal based on user login status.

Parameters:

Name Type Description Default
fullname str or None

The full name of the logged-in user, by default None

None
username str or None

The username of the logged-in user, by default None

None

Returns:

Type Description
list

A list of components for the modal title, either showing the user's name and username or a default login icon and text

Source code in plantimager/webui/login.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def login_title(fullname: str | None = None, username: str | None = None) -> list:
    """Create a title for the login modal based on user login status.

    Parameters
    ----------
    fullname : str or None, optional
        The full name of the logged-in user, by default None
    username : str or None, optional
        The username of the logged-in user, by default None

    Returns
    -------
    list
        A list of components for the modal title, either showing the user's name and username
        or a default login icon and text
    """
    icon = html.I(className="bi bi-person-bounding-box me-2")
    if fullname:
        return [f"{fullname} (@{username})"]
    else:
        return [icon, "Login"]

logout Link

logout(_)

Handle user logout functionality.

This callback clears the user session data when the logout button is clicked.

Parameters:

Name Type Description Default
_ int

Placeholder for the click event of the 'logout-button' (unused).

required

Returns:

Type Description
None

Clears the logged username.

None

Clears the logged full name.

str

Empty string for a login attempt message.

Source code in plantimager/webui/login.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
@callback(
    Output('logged-username', 'data', allow_duplicate=True),
    Output('logged-fullname', 'data', allow_duplicate=True),
    Output("login-attempt-message", "children", allow_duplicate=True),
    Input('logout-button', 'n_clicks'),
    prevent_initial_call=True
)
def logout(_: int) -> tuple[None, None, str]:
    """Handle user logout functionality.

    This callback clears the user session data when the logout button is clicked.

    Parameters
    ----------
    _ : int
        Placeholder for the click event of the 'logout-button' (unused).

    Returns
    -------
    None
        Clears the logged username.
    None
        Clears the logged full name.
    str
        Empty string for a login attempt message.
    """
    return None, None, ""

timeout_modal Link

timeout_modal(username)

Control the visibility of the login-modal with a timeout.

This callback automatically closes the login-modal after a 1-second delay when a user successfully logs in.

Parameters:

Name Type Description Default
username str or None

The username of the logged-in user. None if no user is logged in.

required

Returns:

Type Description
bool

False if a user is logged in (closes modal), True otherwise (keeps modal open)

Notes

The function includes a 1-second sleep delay to provide time for the logout callback to unset the username.

Source code in plantimager/webui/login.py
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
555
556
557
558
@callback(
    Output("login-modal", "is_open", allow_duplicate=True),
    Input("logged-username", "data"),
    prevent_initial_call=True,
)
def timeout_modal(username: str | None) -> bool:
    """Control the visibility of the login-modal with a timeout.

    This callback automatically closes the login-modal after a 1-second delay
    when a user successfully logs in.

    Parameters
    ----------
    username : str or None
        The username of the logged-in user. None if no user is logged in.

    Returns
    -------
    bool
        ``False`` if a user is logged in (closes modal), ``True`` otherwise (keeps modal open)

    Notes
    -----
    The function includes a 1-second sleep delay to provide time for the logout callback to unset the username.
    """
    time.sleep(1)
    if username:
        return False  # close the login modal
    else:
        return True  # keep the login modal open

toggle_login_modal Link

toggle_login_modal(_, is_open)

Toggle the visibility of the login modal.

This callback function controls the visibility of the login modal when the login avatar button is clicked.

Parameters:

Name Type Description Default
_ int

Number of clicks on the login avatar button (unused parameter)

required
is_open bool

Current state of the login modal visibility

required

Returns:

Type Description
bool

True to open the modal, False otherwise

Notes

The function only handles opening the modal. Closing is handled by other modal mechanisms

Source code in plantimager/webui/login.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@callback(Output("login-modal", "is_open", allow_duplicate=True),
          Input('login-avatar-button', 'n_clicks'),
          State('login-modal', 'is_open'),
          prevent_initial_call=True)
def toggle_login_modal(_: int, is_open: bool) -> bool | None:
    """Toggle the visibility of the login modal.

    This callback function controls the visibility of the login modal when the login avatar button is clicked.

    Parameters
    ----------
    _ : int
        Number of clicks on the login avatar button (unused parameter)
    is_open : bool
        Current state of the login modal visibility

    Returns
    -------
    bool
        ``True`` to open the modal, ``False`` otherwise

    Notes
    -----
    The function only handles opening the modal. Closing is handled by other modal mechanisms
    """
    if not is_open:
        return True
    return False

update_login_avatar_button Link

update_login_avatar_button(fullname)

Update the login avatar button display based on user login status.

This callback function modifies the login button appearance in the navigation bar to reflect whether a user is logged in or not. When logged in, it displays the user's full name; when logged out, it shows the default login button.

Parameters:

Name Type Description Default
fullname str or None

The full name of the logged-in user. None if no user is logged in.

required

Returns:

Type Description
list

A list of Dash components representing the children of the login button. The content varies based on login status.

See Also

create_login_button : The underlying function that creates the button components

Source code in plantimager/webui/login.py
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
450
451
452
453
454
@callback(
    Output("login-avatar-button", "children"),
    Input("logged-fullname", "data")
)
def update_login_avatar_button(fullname: str | None) -> list:
    """Update the login avatar button display based on user login status.

    This callback function modifies the login button appearance in the navigation bar
    to reflect whether a user is logged in or not. When logged in, it displays the
    user's full name; when logged out, it shows the default login button.

    Parameters
    ----------
    fullname : str or None
        The full name of the logged-in user. None if no user is logged in.

    Returns
    -------
    list
        A list of Dash components representing the children of the login button.
        The content varies based on login status.

    See Also
    --------
    create_login_button : The underlying function that creates the button components
    """
    if fullname:
        return create_login_button(
            is_logged_in=True,
            user_fullname=fullname
        ).children
    return create_login_button(is_logged_in=False).children

update_login_modal_body Link

update_login_modal_body(fullname)

Update the visibility of login modal components based on login status.

This callback controls the display of username and password input groups in the login modal, as well as any login attempt messages, based on whether a user is logged in.

Parameters:

Name Type Description Default
fullname str or None

The full name of the logged-in user. None if no user is logged in.

required

Returns:

Type Description
dict

Style dictionary for username-input-group component

dict

Style dictionary for password-input-group component

str

Login-attempt-message component (empty string in this case)

Examples:

>>> update_login_modal_body(None)
({'display': 'flex'}, {'display': 'flex'}, "")
>>> update_login_modal_body("John Doe")
({'display': 'none'}, {'display': 'none'}, "")
Source code in plantimager/webui/login.py
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
520
521
522
523
524
525
526
@callback(
    Output("username-input-group", "style", allow_duplicate=True),
    Output("password-input-group", "style", allow_duplicate=True),
    Output("login-attempt-message", "children", allow_duplicate=True),
    Input("logged-fullname", "data"),
    prevent_initial_call=True,
)
def update_login_modal_body(fullname: str | None) -> tuple[dict, dict, str]:
    """Update the visibility of login modal components based on login status.

    This callback controls the display of username and password input groups in the login modal,
    as well as any login attempt messages, based on whether a user is logged in.

    Parameters
    ----------
    fullname : str or None
        The full name of the logged-in user. ``None`` if no user is logged in.

    Returns
    -------
    dict
        Style dictionary for username-input-group component
    dict
        Style dictionary for password-input-group component
    str
        Login-attempt-message component (empty string in this case)

    Examples
    --------
    >>> update_login_modal_body(None)
    ({'display': 'flex'}, {'display': 'flex'}, "")
    >>> update_login_modal_body("John Doe")
    ({'display': 'none'}, {'display': 'none'}, "")
    """
    if not fullname:
        return {'display': 'flex'}, {'display': 'flex'}, ""
    return {'display': 'none'}, {'display': 'none'}, ""

update_login_modal_title Link

update_login_modal_title(fullname, username)

Updates the title of the login modal window dynamically based on the logged-in user's information. If the logged-in user's full name is available, it uses the provided full name and username to generate the title. Otherwise, it defaults to a generic title.

Parameters:

Name Type Description Default
fullname str or None

The full name of the logged-in user. If None, the default title is used instead.

required
username str or None

The username of the logged-in user. Used in combination with the full name to generate the title. If None, the default title is used.

required

Returns:

Type Description
str

The dynamically generated title for the login modal window. This either includes the logged-in user's full name and username or a default message if no user information is provided.

Source code in plantimager/webui/login.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@callback(
    Output("login-modal-title", "children"),
    Input("logged-fullname", "data"),
    Input("logged-username", "data"),
)
def update_login_modal_title(fullname: str | None, username: str | None) -> list:
    """Updates the title of the login modal window dynamically based on the logged-in
    user's information. If the logged-in user's full name is available, it uses the
    provided full name and username to generate the title. Otherwise, it defaults
    to a generic title.

    Parameters
    ----------
    fullname : str or None
        The full name of the logged-in user.
        If ``None``, the default title is used instead.
    username : str or None
        The username of the logged-in user.
        Used in combination with the full name to generate the title.
        If ``None``, the default title is used.

    Returns
    -------
    str
        The dynamically generated title for the login modal window. This either
        includes the logged-in user's full name and username or a default message
        if no user information is provided.
    """
    if fullname:
        return login_title(fullname, username)
    return login_title()

validate_username Link

validate_username(username, is_modal_open, host, port, prefix)

Validate a username by checking if it exists in the database.

Parameters:

Name Type Description Default
username str or None

The username to validate

required
is_modal_open bool

Whether the login modal is currently open

required
host str

The hostname or IP address of the PlantDB REST API server.

required
port int

The port number of the PlantDB REST API server.

required
prefix str

The prefix of the PlantDB REST API server.

required

Returns:

Type Description
tuple[bool, bool]

A tuple of (valid, invalid) flags for the username input field

Raises:

Type Description
RequestException

If there are network connectivity issues or server communication problems

Source code in plantimager/webui/login.py
261
262
263
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
308
@callback(
    Output('username-input', 'valid'),
    Output('username-input', 'invalid'),
    Input('username-input', 'value'),
    State('login-modal', 'is_open'),
    State('rest-api-host', 'data'),
    State('rest-api-port', 'data'),
    State('rest-api-prefix', 'data'),
)
def validate_username(username: str | None, is_modal_open: bool, host: str, port: int | str, prefix: str) -> tuple[
    bool, bool]:
    """Validate a username by checking if it exists in the database.

    Parameters
    ----------
    username : str or None
        The username to validate
    is_modal_open : bool
        Whether the login modal is currently open
    host : str
       The hostname or IP address of the PlantDB REST API server.
    port : int
        The port number of the PlantDB REST API server.
    prefix : str
        The prefix of the PlantDB REST API server.

    Returns
    -------
    tuple[bool, bool]
        A tuple of (valid, invalid) flags for the username input field

    Raises
    ------
    requests.exceptions.RequestException
        If there are network connectivity issues or server communication problems
    """
    if not is_modal_open or not username:
        return False, False
    # Make request to the login API endpoint
    try:
        response = requests.get(urljoin(base_url(host, port, prefix), f'login?username={username}'))
        user_exists = response.json().get('exists', False)
        if user_exists:
            return True, False  # Valid username
        else:
            return False, True  # Invalid username
    except Exception as e:
        return False, True