1- import bcrypt
2-
1+ try :
2+ from passlib .apache import HtpasswdFile
3+ except ImportError :
4+ HtpasswdFile : None
35class BasePlugin ():
46 def __init__ (self , src = None ):
57 self .source = src
@@ -25,10 +27,9 @@ def __init__(self, expected, actual):
2527 self .expected_origin = expected
2628 self .actual_origin = actual
2729
28- super ().__init__ (
29- response_msg = 'Invalid Origin' ,
30- log_msg = "Invalid Origin Header: Expected one of "
31- "%s, got '%s'" % (expected , actual ))
30+ super ().__init__ (response_msg = 'Invalid Origin' ,
31+ log_msg = "Invalid Origin Header: Expected one of "
32+ "%s, got '%s'" % (expected , actual ))
3233
3334
3435class BasicHTTPAuth ():
@@ -78,21 +79,25 @@ def demand_auth(self):
7879 raise AuthenticationError (response_code = 401 ,
7980 response_headers = {'WWW-Authenticate' : 'Basic realm="Websockify"' })
8081
81- class HtPasswdAuth (BasicHTTPAuth ):
82+ class HtpasswdAuth (BasicHTTPAuth ):
8283 """Verifies Basic Auth headers against a htpasswd database. Specify src as the path to the htpasswd file"""
8384
8485 def __init__ (self , src = None ):
8586 self .src = src
87+ if HtpasswdFile is None :
88+ raise AuthenticationError (response_code = 500 , response_msg = f"Internal Server Error" )
8689
8790 def validate_creds (self , username , password ):
8891 if self .src == None :
8992 return False
9093 try :
91- with open (self .src , 'r' ) as file :
92- for line in file :
93- stored_user , stored_hash = line .strip ().split (':' , 1 )
94- if stored_user == username :
95- return bcrypt .checkpw (password .encode ('utf-8' ), stored_hash .encode ('utf-8' ))
94+ #TODO: Add a argument or config to change the HtpasswdFile scheme
95+ htfile = HtpasswdFile (self .src , new = False , default_scheme = "bcrypt" , encoding = "utf-8" )
96+ isvalid_hash = htfile .check_password (username , password )
97+ if isvalid_hash == None :
98+ #log user not found
99+ raise AuthenticationError (response_code = 403 )
100+ return isvalid_hash
96101 except (FileNotFoundError , PermissionError , OSError , ValueError ) as e :
97102 #log error "%s: %s" % (type(e).__name__, e)
98103 raise AuthenticationError (response_code = 500 , response_msg = f"Internal Server Error" )
0 commit comments