Skip to content

sshfsdb

plantdb.commons.sshfsdb Link

This module implement a database as a file structure on a remote server using SSHFS.

SSHFSDB Link

SSHFSDB(basedir, remotedir=None)

Bases: FSDB

Subclass of FSDB that first mounts a remote directory using SSHFS.

Implementation of a database on a remote file system.

Attributes:

Name Type Description
basedir str

Path to the local directory where to mount the remote directory.

remotedir (str, optional)

Path to the remote directory containing the database. Should be in the format user@server:path

scans list

The list of Scan objects found in the database

is_connected bool

True if the DB is connected (locked the directory), else False.

Database constructor.

Mount remotedir directory on the basedir directory and load accessible Scan objects.

Parameters:

Name Type Description Default
basedir str

Path to local directory of the database

required
remotedir str

Path to the remote directory containing the database. Should be in the format user@server:path

None

Examples:

>>> # EXAMPLE 1: Use a temporary dummy database:
>>> from plantdb.commons.sshfsdb import SSHFSDB
>>> db = SSHFSDB("db", "someone@example.com:/data")
>>> print(db.basedir)
db
>>> print(db.remotedir)
someone@example.com:/data
>>> # Now connecting to this remote DB...
>>> db.connect()
>>> # ...allows to create new `Scan` in it:
>>> new_scan = db.create_scan("007")
>>> print(type(new_scan))
<class 'plantdb.commons.fsdb.Scan'>
>>> db.disconnect()
Source code in plantdb/commons/sshfsdb.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __init__(self, basedir, remotedir=None):
    """Database constructor.

    Mount ``remotedir`` directory on the ``basedir`` directory and load accessible ``Scan`` objects.

    Parameters
    ----------
    basedir : str
        Path to local directory of the database
    remotedir : str, optional
        Path to the remote directory containing the database.
        Should be in the format ``user@server:path``

    Examples
    --------
    >>> # EXAMPLE 1: Use a temporary dummy database:
    >>> from plantdb.commons.sshfsdb import SSHFSDB
    >>> db = SSHFSDB("db", "someone@example.com:/data")
    >>> print(db.basedir)
    db
    >>> print(db.remotedir)
    someone@example.com:/data
    >>> # Now connecting to this remote DB...
    >>> db.connect()
    >>> # ...allows to create new `Scan` in it:
    >>> new_scan = db.create_scan("007")
    >>> print(type(new_scan))
    <class 'plantdb.commons.fsdb.Scan'>
    >>> db.disconnect()
    """
    super().__init__(basedir)
    self.remotedir = remotedir

connect Link

connect(login=None, unsafe=False)

Connect to the remote database.

Handle DB "locking" system by adding a LOCK_FILE_NAME file in the DB.

Parameters:

Name Type Description Default
login bool

UNUSED

None

Examples:

>>> from plantdb.commons.sshfsdb import SSHFSDB
>>> db = SSHFSDB("db", "someone@example.com:/data")
>>> print(db.is_connected)
False
>>> db.connect()
>>> print(db.is_connected)
True
Source code in plantdb/commons/sshfsdb.py
 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
def connect(self, login=None, unsafe=False):
    """Connect to the remote database.

    Handle DB "locking" system by adding a ``LOCK_FILE_NAME`` file in the DB.

    Parameters
    ----------
    login : bool
        UNUSED

    Examples
    --------
    >>> from plantdb.commons.sshfsdb import SSHFSDB
    >>> db = SSHFSDB("db", "someone@example.com:/data")
    >>> print(db.is_connected)
    False
    >>> db.connect()
    >>> print(db.is_connected)
    True
    """
    if not self.path().is_dir():
        self.path().mkdir(exist_ok=True)
    if self.remotedir is not None:
        cmd = ["sshfs", "-o", "idmap=user", self.remotedir, self.path()]
        logger.info(f"Connecting with: '{cmd}'")
        p = subprocess.run(cmd)
        logger.debug(f"The exit code was: {p.returncode}")
    super().connect()

create_scan Link

create_scan(scan_id, metadata=None)

Create a new Scan instance in the local database.

Parameters:

Name Type Description Default
scan_id str

The identifier of the scan to create. It should contain only alphanumeric characters, underscores, dashes and dots. It should be non-empty and not longer than 255 characters It should not exist in the local database

required
metadata dict

A dictionary of metadata to append to the new Scan instance. The key 'owner' will be added/updated using the currently connected user. Default is None.

None

Returns:

Type Description
Scan

The Scan instance created in the local database.

Raises:

Type Description
OSError

If the scan_id is not valid or already exists in the local database.

See Also

plantdb.commons.fsdb._is_valid_id plantdb.commons.fsdb._make_scan

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db()
>>> new_scan = db.create_scan('007', metadata={'project': 'GoldenEye'})  # create a new scan dataset
>>> print(new_scan.get_metadata('owner'))  # default user 'anonymous' for dummy database
anonymous
>>> print(new_scan.get_metadata('project'))
GoldenEye
>>> scan = db.create_scan('007')  # attempt to create an existing scan dataset
OSError: Given scan identifier '007' already exists!
>>> scan = db.create_scan('0/07')  # attempt to create a scan dataset using invalid characters
OSError: Invalid scan identifier '0/07'!
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def create_scan(self, scan_id, metadata=None):
    """Create a new ``Scan`` instance in the local database.

    Parameters
    ----------
    scan_id : str
        The identifier of the scan to create.
        It should contain only alphanumeric characters, underscores, dashes and dots.
        It should be non-empty and not longer than 255 characters
        It should not exist in the local database
    metadata : dict, optional
        A dictionary of metadata to append to the new ``Scan`` instance.
        The key 'owner' will be added/updated using the currently connected user.
        Default is ``None``.

    Returns
    -------
    plantdb.commons.fsdb.Scan
        The ``Scan`` instance created in the local database.

    Raises
    ------
    OSError
        If the `scan_id` is not valid or already exists in the local database.

    See Also
    --------
    plantdb.commons.fsdb._is_valid_id
    plantdb.commons.fsdb._make_scan

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db()
    >>> new_scan = db.create_scan('007', metadata={'project': 'GoldenEye'})  # create a new scan dataset
    >>> print(new_scan.get_metadata('owner'))  # default user 'anonymous' for dummy database
    anonymous
    >>> print(new_scan.get_metadata('project'))
    GoldenEye
    >>> scan = db.create_scan('007')  # attempt to create an existing scan dataset
    OSError: Given scan identifier '007' already exists!
    >>> scan = db.create_scan('0/07')  # attempt to create a scan dataset using invalid characters
    OSError: Invalid scan identifier '0/07'!
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    # Verify if the given `scan_id` is valid
    if not _is_valid_id(scan_id):
        raise IOError(f"Invalid scan identifier '{scan_id}'!")
    # Verify if the given `scan_id` already exists in the local database
    if self.scan_exists(scan_id):
        raise IOError(f"Given scan identifier '{scan_id}' already exists!")

    scan = Scan(self, scan_id)
    _make_scan(scan)
    self.scans[scan_id] = scan

    if metadata is None:
        metadata = {}
    metadata.update({'owner': self.user})  # add/update 'owner' metadata to the new scan
    scan.set_metadata(metadata)  # add metadata dictionary to the new scan
    return scan

create_user Link

create_user(username, fullname, password)

Create a new user and store the user information in a file.

Parameters:

Name Type Description Default
username str

The username of the user to be created. This will be converted to lowercase.

required
fullname str

The full name of the user to be created.

required
password str

The password of the user to be created.

required

Examples:

>>> from plantdb.commons.fsdb import FSDB
>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db()
>>> db.create_user('batman', "Bruce Wayne", "joker")
>>> db.connect('batman', 'joker')
>>> print(db.user)
batman
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
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
421
422
423
def create_user(self, username, fullname, password):
    """Create a new user and store the user information in a file.

    Parameters
    ----------
    username : str
        The username of the user to be created.
        This will be converted to lowercase.
    fullname : str
        The full name of the user to be created.
    password : str
        The password of the user to be created.

    Examples
    --------
    >>> from plantdb.commons.fsdb import FSDB
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db()
    >>> db.create_user('batman', "Bruce Wayne", "joker")
    >>> db.connect('batman', 'joker')
    >>> print(db.user)
    batman
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    from datetime import datetime
    username = username.lower()  # Convert the username to lowercase to maintain uniformity.
    now = datetime.now()  # Get the current timestamp for tracking user creation time.
    timestamp = now.strftime("%y%m%d_%H%M%S")  # Format the timestamp as 'YYMMDD_HHMMSS'.

    # Verify if the login is available
    try:
        assert username not in self.users
    except AssertionError:
        logger.error(f"User '{username}' already exists!")
        return

    # Generate salt and hash password
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)

    # Add the new user's data to the `self.users` dictionary.
    self.users[username] = {
        'password': hashed.decode('utf-8'),  # Store the hashed password as a string.
        'fullname': fullname,  # Store the provided full name of the user.
        'created': timestamp,  # Store the formatted timestamp to record when the user was created.
        'last_login': None,  # Store the timestamp of the last login.
        'failed_attempts': 0,  # Store the number of failed login attempts.
    }

    # Save all user data (including the newly created user) to 'users.json' file.
    with open(self.basedir / 'users.json', "w") as f:
        json.dump(self.users, f, indent=2)
    logger.info(f"Created user '{username}' with fullname '{fullname}'.")

    return f"Welcome {self.users[username]['fullname']}!'"

delete_scan Link

delete_scan(scan_id)

Delete an existing Scan from the local database.

Parameters:

Name Type Description Default
scan_id str

The name of the scan to delete from the local database.

required

Raises:

Type Description
IOError

If the id do not exist in the local database.

See Also

plantdb.commons.fsdb._delete_scan

Examples:

>>> from plantdb.commons.fsdb import FSDB
>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db()
>>> new_scan = db.create_scan('007')
>>> print(new_scan)
<plantdb.commons.fsdb.Scan object at 0x7f0730b1e390>
>>> db.delete_scan('007')
>>> scan = db.get_scan('007')
>>> print(scan)
None
>>> db.delete_scan('008')
OSError: Invalid id
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
def delete_scan(self, scan_id):
    """Delete an existing `Scan` from the local database.

    Parameters
    ----------
    scan_id : str
        The name of the scan to delete from the local database.

    Raises
    ------
    IOError
        If the `id` do not exist in the local database.

    See Also
    --------
    plantdb.commons.fsdb._delete_scan

    Examples
    --------
    >>> from plantdb.commons.fsdb import FSDB
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db()
    >>> new_scan = db.create_scan('007')
    >>> print(new_scan)
    <plantdb.commons.fsdb.Scan object at 0x7f0730b1e390>
    >>> db.delete_scan('007')
    >>> scan = db.get_scan('007')
    >>> print(scan)
    None
    >>> db.delete_scan('008')
    OSError: Invalid id
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    # Verify if the given `scan_id` exists in the local database
    if not self.scan_exists(scan_id):
        logging.warning(f"Given scan identifier '{scan_id}' does NOT exists!")
        return

    _delete_scan(self.get_scan(scan_id))  # delete the Scan instance
    self.scans.pop(scan_id)  # remove the scan from the local database
    return

disconnect Link

disconnect()

Disconnect from the database.

Handle DB "locking" system by removing the LOCK_FILE_NAME file from the DB.

Examples:

>>> from plantdb.commons.sshfsdb import SSHFSDB
>>> db = SSHFSDB("db", "someone@example.com:/data")
>>> print(db.is_connected)
False
>>> db.connect()
>>> print(db.is_connected)
True
>>> db.disconnect()
>>> print(db.is_connected)
False
Source code in plantdb/commons/sshfsdb.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def disconnect(self):
    """Disconnect from the database.

    Handle DB "locking" system by removing the ``LOCK_FILE_NAME`` file from the DB.

    Examples
    --------
    >>> from plantdb.commons.sshfsdb import SSHFSDB
    >>> db = SSHFSDB("db", "someone@example.com:/data")
    >>> print(db.is_connected)
    False
    >>> db.connect()
    >>> print(db.is_connected)
    True
    >>> db.disconnect()
    >>> print(db.is_connected)
    False
    """
    super().disconnect()
    p = subprocess.run(["fusermount", "-u", self.path()])
    print(f"The exit code was: {p.returncode}")

get_scan Link

get_scan(scan_id, create=False)

Get or create a Scan instance in the local database.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to get/create. It should exist if create is False.

required
create bool

If False (default), the given id should exist in the local database. Else the given id should NOT exist as they are unique.

False

Raises:

Type Description
ScanNotFoundError

If the scan_id do not exist in the local database and create is False.

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db()
>>> db.list_scans()
[]
>>> new_scan = db.get_scan('007', create=True)
>>> print(new_scan)
<plantdb.commons.fsdb.Scan object at **************>
>>> db.list_scans()
['007']
>>> unknown_scan = db.get_scan('unknown')
plantdb.commons.fsdb.ScanNotFoundError: Unknown scan id 'unknown'!
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
721
722
723
724
725
726
727
728
729
730
731
732
733
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
def get_scan(self, scan_id, create=False):
    """Get or create a `Scan` instance in the local database.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to get/create.
        It should exist if `create` is `False`.
    create : bool, optional
        If ``False`` (default), the given `id` should exist in the local database.
        Else the given `id` should NOT exist as they are unique.

    Raises
    ------
    plantdb.commons.fsdb.ScanNotFoundError
        If the `scan_id` do not exist in the local database and `create` is ``False``.

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db()
    >>> db.list_scans()
    []
    >>> new_scan = db.get_scan('007', create=True)
    >>> print(new_scan)
    <plantdb.commons.fsdb.Scan object at **************>
    >>> db.list_scans()
    ['007']
    >>> unknown_scan = db.get_scan('unknown')
    plantdb.commons.fsdb.ScanNotFoundError: Unknown scan id 'unknown'!
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    if self.scan_exists(scan_id):
        return self.scans[scan_id]
    else:
        if create:
            return self.create_scan(scan_id)
        else:
            raise ScanNotFoundError(self, scan_id)

get_scans Link

get_scans(query=None, fuzzy=False, owner_only=True)

Get the list of Scan instances defined in the local database, possibly filtered using a query.

Parameters:

Name Type Description Default
query dict

A query to use to filter the returned list of scans. The metadata must match given key and value from the query dictionary.

None
fuzzy bool

Whether to use fuzzy matching or not, that is the use of regular expressions.

False
owner_only bool

Whether to filter the returned list of scans to only include scans owned by the current user. Default is True.

True

Returns:

Type Description
list of plantdb.commons.fsdb.Scan

List of Scans, filtered by the query if any.

See Also

plantdb.commons.fsdb._filter_query

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db(with_file=True)
>>> db.get_scans()
[<plantdb.commons.fsdb.Scan at *x************>]
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
def get_scans(self, query=None, fuzzy=False, owner_only=True):
    """Get the list of `Scan` instances defined in the local database, possibly filtered using a `query`.

    Parameters
    ----------
    query : dict, optional
        A query to use to filter the returned list of scans.
        The metadata must match given ``key`` and ``value`` from the `query` dictionary.
    fuzzy : bool, optional
        Whether to use fuzzy matching or not, that is the use of regular expressions.
    owner_only : bool, optional
        Whether to filter the returned list of scans to only include scans owned by the current user.
        Default is ``True``.

    Returns
    -------
    list of plantdb.commons.fsdb.Scan
        List of `Scan`s, filtered by the `query` if any.

    See Also
    --------
    plantdb.commons.fsdb._filter_query

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db(with_file=True)
    >>> db.get_scans()
    [<plantdb.commons.fsdb.Scan at *x************>]
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    if owner_only:
        if query is None:
            query = {'owner': self.user}
        else:
            query.update({'owner': self.user})
    return _filter_query(list(self.scans.values()), query, fuzzy)

list_scans Link

list_scans(query=None, fuzzy=False, owner_only=True)

Get the list of scans in identifiers the local database.

Parameters:

Name Type Description Default
query dict

A query to use to filter the returned list of scans. The metadata must match given key and value from the query dictionary.

None
fuzzy bool

Whether to use fuzzy matching or not, that is the use of regular expressions.

False

Returns:

Type Description
list[str]

The list of scan identifiers in the local database.

See Also

plantdb.commons.fsdb._filter_query

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db(with_scan=True)
>>> db.list_scans()
['myscan_001']
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
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
def list_scans(self, query=None, fuzzy=False, owner_only=True) -> list:
    """Get the list of scans in identifiers the local database.

    Parameters
    ----------
    query : dict, optional
        A query to use to filter the returned list of scans.
        The metadata must match given ``key`` and ``value`` from the `query` dictionary.
    fuzzy : bool
        Whether to use fuzzy matching or not, that is the use of regular expressions.

    Returns
    -------
    list[str]
        The list of scan identifiers in the local database.

    See Also
    --------
    plantdb.commons.fsdb._filter_query

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db(with_scan=True)
    >>> db.list_scans()
    ['myscan_001']
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    if owner_only:
        if query is None:
            query = {'owner': self.user}
        else:
            query.update({'owner': self.user})

    if query is None:
        return list(self.scans.keys())
    else:
        return [scan.id for scan in self.get_scans(query, fuzzy, owner_only)]

path Link

path()

Get the path to the local database root directory.

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db()
>>> print(db.path())
/tmp/romidb_********
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
865
866
867
868
869
870
871
872
873
874
875
876
def path(self) -> pathlib.Path:
    """Get the path to the local database root directory.

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db()
    >>> print(db.path())
    /tmp/romidb_********
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    return copy.deepcopy(self.basedir)

reload Link

reload(scan_id=None)

Reload the database by scanning datasets.

Parameters:

Name Type Description Default
scan_id str or list of str

The name of the scan(s) to reload.

None
Source code in plantdb/commons/fsdb/core.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def reload(self, scan_id=None):
    """Reload the database by scanning datasets.

    Parameters
    ----------
    scan_id : str or list of str, optional
        The name of the scan(s) to reload.
    """
    if self.is_connected:
        if scan_id is None:
            logger.info("Reloading the database...")
            self.scans = _load_scans(self)
        elif isinstance(scan_id, str):
            logger.info(f"Reloading scan '{scan_id}'...")
            self.scans[scan_id] = _load_scan(self, scan_id)
        elif isinstance(scan_id, Iterable):
            [self.reload(scan_i) for scan_i in scan_id]
        else:
            logger.error(f"Wrong parameter `scan_name`, expected a string or list of string but got '{scan_id}'!")
        logger.info("Done!")
    else:
        logger.error(f"You are not connected to the database!")

scan_exists Link

scan_exists(scan_id)

Check if a given scan ID exists in the database.

Parameters:

Name Type Description Default
scan_id str

The ID of the scan to check.

required

Returns:

Type Description
bool

True if the scan exists, False otherwise.

Examples:

>>> from plantdb.commons.fsdb import dummy_db
>>> db = dummy_db(with_scan=True)
>>> db.scan_exists("myscan_001")
True
>>> db.scan_exists("nonexistent_id")
False
>>> db.disconnect()  # clean up (delete) the temporary dummy database
Source code in plantdb/commons/fsdb/core.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def scan_exists(self, scan_id: str) -> bool:
    """Check if a given scan ID exists in the database.

    Parameters
    ----------
    scan_id : str
        The ID of the scan to check.

    Returns
    -------
    bool
        ``True`` if the scan exists, ``False`` otherwise.

    Examples
    --------
    >>> from plantdb.commons.fsdb import dummy_db
    >>> db = dummy_db(with_scan=True)
    >>> db.scan_exists("myscan_001")
    True
    >>> db.scan_exists("nonexistent_id")
    False
    >>> db.disconnect()  # clean up (delete) the temporary dummy database
    """
    return scan_id in self.scans

user_exists Link

user_exists(username)

Check if the user exists in the local database.

Source code in plantdb/commons/fsdb/core.py
551
552
553
def user_exists(self, username: str) -> bool:
    """Check if the user exists in the local database."""
    return username in self.users

validate_user Link

validate_user(username, password)

Validate the user login.

Parameters:

Name Type Description Default
username str

The username provided by the user attempting to log in.

required
password str

The password provided by the user attempting to log in.

required

Returns:

Type Description
bool

True if the login attempt is successful, False otherwise.

Raises:

Type Description
KeyError

If there is an issue accessing necessary user data.

Source code in plantdb/commons/fsdb/core.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
def validate_user(self, username: str, password: str) -> bool:
    """Validate the user login.

    Parameters
    ----------
    username : str
        The username provided by the user attempting to log in.
    password : str
        The password provided by the user attempting to log in.

    Returns
    -------
    bool
        ``True`` if the login attempt is successful, ``False`` otherwise.

    Raises
    ------
    KeyError
        If there is an issue accessing necessary user data.
    """
    if self._is_account_locked(username):
        logger.warning(f"Account locked: {username}")
        return False

    if username not in self.users:
        logger.warning(f"Login attempt for non-existent user: {username}")
        return False

    # Verify password
    stored_hash = self.users[username]['password']
    if bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')):
        # Reset failed attempts on successful login
        self.failed_login_attempts[username] = 0
        self.users[username]['last_login'] = datetime.now().strftime("%y%m%d_%H%M%S")
        return True

    # Handle failed login attempt
    self._record_failed_attempt(username)
    return False