# !/usr/bin/env python# -*- coding: utf-8 -*-## Filename: htpass.py# Project: auth# Author: Brian Cherinka# Created: Wednesday, 21st October 2020 2:52:25 pm# License: BSD 3-clause "New" or "Revised" License# Copyright (c) 2020 Brian Cherinka# Last Modified: Wednesday, 21st October 2020 2:52:25 pm# Modified By: Brian Cherinkafrom__future__importprint_function,division,absolute_importimportpathlibimportwarningsfromsdss_brainimportcfg_paramsfromsdss_brain.exceptionsimportBrainErrortry:importpasslibexceptImportError:passlib=Noneelse:frompasslib.apacheimportHtpasswdFile
[docs]classHtpass(object):""" Class representing a htpasswd file This class represents a local .htpasswd file, used for authenticating users against the Apache password file used for HTTP Basic Authentication. This class validates a htpasswd file for existence. It allows one to list the user entries found in a local htpasswd file, as well as validate a user against the htpasswd file. Parameters ---------- path : str The path to a .htpasswd file. Defaults to custom "htpass_path" config path or ~/.htpasswd """def__init__(self,path:str=None):path=pathorcfg_params.get('htpass_path',None)or'~/.htpasswd'self.path=pathlib.Path(path).expanduser()self.htpass=Noneself._check_htpass()def__repr__(self)->str:returnf'<Htpass(path="{self.path}", valid={self.is_valid})>'@propertydefis_valid(self)->bool:""" Checks if the htpass file exists and htpass object is loaded """returnself.path.is_file()andself.htpassisnotNone
[docs]defvalidate_user(self,username:str,password:str)->bool:""" Validate a user entry in the htpass file Checks the provided username and password against the entry in the htpass file. Parameters ---------- username : str A valid htpass username entry password : str The password for the provided username Returns ------- bool True when the username/password validates successfully """ifnotself.is_valid:warnings.warn('htpass is not valid. Cannot validate user. Check file path.')returnFalsereturnself.htpass.check_password(username,password)
def_check_htpass(self)->None:""" Check existence of the htpasswd file Reads in the htpass file with passlib.apache.HtpasswdFile Raises ------ ImportError when passlib package not installed BrainError when the provided htpass file path does not exist """ifnotpasslib:raiseImportError('passlib package not installed. Cannot use Htpass.')ifnotself.path.is_file():raiseBrainError(f'No .htpasswd file found at {self.path}!')self.htpass=HtpasswdFile(self.path)
[docs]deflist_users(self)->list:""" Return a list of users in the htpasswd file Returns ------- list list of users in the htpasswd file """ifnotself.is_valid:warnings.warn('htpass is not valid. Cannot list users. Check file path.')returnNonereturnself.htpass.users()