8 Commits

7 changed files with 30 additions and 22 deletions

View File

@ -379,9 +379,9 @@ A pytest Test
def test_admin(app: Flask, client: Client): def test_admin(app: Flask, client: Client):
with app.app_context(): with app.app_context():
response = self.client.get("/admin") response = client.get("/admin")
assert response.status_code == 401 assert response.status_code == 401
response = self.client.get( response = client.get(
"/admin", digest_auth=("my_name", "my_pass")) "/admin", digest_auth=("my_name", "my_pass"))
assert response.status_code == 200 assert response.status_code == 200

View File

@ -22,7 +22,7 @@ copyright = '2022, imacat'
author = 'imacat' author = 'imacat'
# The full version, including alpha/beta/rc tags # The full version, including alpha/beta/rc tags
release = '0.2.3' release = '0.2.4'
# -- General configuration --------------------------------------------------- # -- General configuration ---------------------------------------------------

View File

@ -261,8 +261,8 @@ A pytest Test
def test_admin(app: Flask, client: Client): def test_admin(app: Flask, client: Client):
with app.app_context(): with app.app_context():
response = self.client.get("/admin") response = client.get("/admin")
assert response.status_code == 401 assert response.status_code == 401
response = self.client.get( response = client.get(
"/admin", digest_auth=("my_name", "my_pass")) "/admin", digest_auth=("my_name", "my_pass"))
assert response.status_code == 200 assert response.status_code == 200

View File

@ -26,7 +26,6 @@ Indices and tables
================== ==================
* :ref:`genindex` * :ref:`genindex`
* :ref:`modindex`
* :ref:`search` * :ref:`search`
.. _HTTP Digest Authentication: https://en.wikipedia.org/wiki/Digest_access_authentication .. _HTTP Digest Authentication: https://en.wikipedia.org/wiki/Digest_access_authentication

View File

@ -17,7 +17,7 @@
[metadata] [metadata]
name = flask-digest-auth name = flask-digest-auth
version = 0.2.3 version = 0.2.4
author = imacat author = imacat
author_email = imacat@mail.imacat.idv.tw author_email = imacat@mail.imacat.idv.tw
description = The Flask HTTP Digest Authentication project. description = The Flask HTTP Digest Authentication project.

View File

@ -41,15 +41,23 @@ class DigestAuth:
:param realm: The realm. :param realm: The realm.
""" """
self.secret_key: str = token_urlsafe(32) self.__serializer: URLSafeTimedSerializer \
self.serializer: URLSafeTimedSerializer \ = URLSafeTimedSerializer(token_urlsafe(32))
= URLSafeTimedSerializer(self.secret_key)
self.realm: str = "" if realm is None else realm self.realm: str = "" if realm is None else realm
"""The realm. Default is an empty string."""
self.algorithm: t.Optional[str] = None self.algorithm: t.Optional[str] = None
"""The algorithm, either None, ``MD5``, or ``MD5-sess``. Default is
None."""
self.use_opaque: bool = True self.use_opaque: bool = True
self.domain: t.List[str] = [] """Whether to use an opaque. Default is True."""
self.qop: t.List[str] = ["auth", "auth-int"] self.__domain: t.List[str] = []
"""A list of directories that this username and password applies to.
Default is empty."""
self.__qop: t.List[str] = ["auth", "auth-int"]
"""A list of supported quality of protection supported, either
``qop``, ``auth-int``, both, or empty. Default is both."""
self.app: t.Optional[Flask] = None self.app: t.Optional[Flask] = None
"""The current Flask application."""
self.__get_password_hash: BasePasswordHashGetter \ self.__get_password_hash: BasePasswordHashGetter \
= BasePasswordHashGetter() = BasePasswordHashGetter()
self.__get_user: BaseUserGetter = BaseUserGetter() self.__get_user: BaseUserGetter = BaseUserGetter()
@ -62,6 +70,7 @@ class DigestAuth:
:: ::
@app.get("/admin")
@auth.login_required @auth.login_required
def admin(): def admin():
return f"Hello, {g.user.username}!" return f"Hello, {g.user.username}!"
@ -152,7 +161,7 @@ class DigestAuth:
raise UnauthorizedException( raise UnauthorizedException(
"Missing \"opaque\" in the Authorization header") "Missing \"opaque\" in the Authorization header")
try: try:
self.serializer.loads( self.__serializer.loads(
authorization.opaque, salt="opaque", max_age=1800) authorization.opaque, salt="opaque", max_age=1800)
except BadData: except BadData:
raise UnauthorizedException("Invalid opaque") raise UnauthorizedException("Invalid opaque")
@ -173,7 +182,7 @@ class DigestAuth:
state.stale = False state.stale = False
raise UnauthorizedException("Incorrect response value") raise UnauthorizedException("Incorrect response value")
try: try:
self.serializer.loads( self.__serializer.loads(
authorization.nonce, authorization.nonce,
salt="nonce" if authorization.opaque is None salt="nonce" if authorization.opaque is None
else f"nonce-{authorization.opaque}") else f"nonce-{authorization.opaque}")
@ -197,16 +206,16 @@ class DigestAuth:
return None return None
if state.opaque is not None: if state.opaque is not None:
return state.opaque return state.opaque
return self.serializer.dumps(randbits(32), salt="opaque") return self.__serializer.dumps(randbits(32), salt="opaque")
opaque: t.Optional[str] = get_opaque() opaque: t.Optional[str] = get_opaque()
nonce: str = self.serializer.dumps( nonce: str = self.__serializer.dumps(
randbits(32), randbits(32),
salt="nonce" if opaque is None else f"nonce-{opaque}") salt="nonce" if opaque is None else f"nonce-{opaque}")
header: str = f"Digest realm=\"{self.realm}\"" header: str = f"Digest realm=\"{self.realm}\""
if len(self.domain) > 0: if len(self.__domain) > 0:
domain_list: str = ",".join(self.domain) domain_list: str = ",".join(self.__domain)
header += f", domain=\"{domain_list}\"" header += f", domain=\"{domain_list}\""
header += f", nonce=\"{nonce}\"" header += f", nonce=\"{nonce}\""
if opaque is not None: if opaque is not None:
@ -215,8 +224,8 @@ class DigestAuth:
header += f", stale=TRUE" if state.stale else f", stale=FALSE" header += f", stale=TRUE" if state.stale else f", stale=FALSE"
if self.algorithm is not None: if self.algorithm is not None:
header += f", algorithm=\"{self.algorithm}\"" header += f", algorithm=\"{self.algorithm}\""
if len(self.qop) > 0: if len(self.__qop) > 0:
qop_list: str = ",".join(self.qop) qop_list: str = ",".join(self.__qop)
header += f", qop=\"{qop_list}\"" header += f", qop=\"{qop_list}\""
return header return header

View File

@ -71,9 +71,9 @@ class Client(WerkzeugClient):
def test_admin(app: Flask, client: Client): def test_admin(app: Flask, client: Client):
with app.app_context(): with app.app_context():
response = self.client.get("/admin") response = client.get("/admin")
assert response.status_code == 401 assert response.status_code == 401
response = self.client.get( response = client.get(
"/admin", digest_auth=("my_name", "my_pass")) "/admin", digest_auth=("my_name", "my_pass"))
assert response.status_code == 200 assert response.status_code == 200
""" """