Add 'none' authentication type option
authorAdam Dullage <redacted>
Tue, 11 Oct 2022 11:59:15 +0000 (12:59 +0100)
committerAdam Dullage <redacted>
Tue, 11 Oct 2022 11:59:15 +0000 (12:59 +0100)
flatnotes/auth.py
flatnotes/auth_type.py [new file with mode: 0644]
flatnotes/config.py

index 6c4d7a342a7ac498ecebd5a825ad28a2b55e3268..cfb052bb841e1b3d5bfb2a8aee6ca83006376f6a 100644 (file)
@@ -3,6 +3,7 @@ from datetime import datetime, timedelta
 from fastapi import Depends, HTTPException
 from fastapi.security import OAuth2PasswordBearer
 from jose import JWTError, jwt
+from auth_type import AuthType
 
 from config import config
 
@@ -24,6 +25,8 @@ def create_access_token(data: dict):
 
 
 async def validate_token(token: str = Depends(oauth2_scheme)):
+    if config.auth_type == AuthType.NONE:
+        return
     try:
         payload = jwt.decode(
             token, config.session_key, algorithms=[JWT_ALGORITHM]
@@ -31,7 +34,7 @@ async def validate_token(token: str = Depends(oauth2_scheme)):
         username = payload.get("sub")
         if username is None or username.lower() != config.username.lower():
             raise ValueError
-        return config.username
+        return
     except (JWTError, ValueError):
         raise HTTPException(
             status_code=401,
diff --git a/flatnotes/auth_type.py b/flatnotes/auth_type.py
new file mode 100644 (file)
index 0000000..c3ad958
--- /dev/null
@@ -0,0 +1,7 @@
+from enum import Enum
+
+
+class AuthType(Enum):
+    NONE = "none"
+    PASSWORD = "password"
+    # TOTP = "totp"  # Not yet implemented
index 1f94856294b3521aa9359d4b15c3a5c2c1ef1e5a..8e9afd99dad0c49f9e3432d05086fbadcbbb146b 100644 (file)
@@ -1,5 +1,7 @@
 import os
+import sys
 
+from auth_type import AuthType
 from logger import logger
 
 
@@ -7,6 +9,8 @@ class Config:
     def __init__(self) -> None:
         self.data_path = self.get_data_path()
 
+        self.auth_type = self.get_auth_type()
+
         self.username = self.get_username()
         self.password = self.get_password()
 
@@ -15,10 +19,11 @@ class Config:
 
     @classmethod
     def get_env(cls, key, mandatory=False, default=None, cast_int=False):
+        """Get an environment variable."""
         value = os.environ.get(key)
         if mandatory and not value:
             logger.error(f"Environment variable {key} must be set.")
-            exit(1)
+            sys.exit(1)
         if not mandatory and not value:
             return default
         if cast_int:
@@ -26,20 +31,43 @@ class Config:
                 value = int(value)
             except (TypeError, ValueError):
                 logger.error(f"Invalid value '{value}' for {key}.")
-                exit(1)
+                sys.exit(1)
         return value
 
     def get_data_path(self):
         return self.get_env("FLATNOTES_PATH", mandatory=True)
 
+    def get_auth_type(self):
+        key = "FLATNOTES_AUTH_TYPE"
+        auth_type = self.get_env(
+            key, mandatory=False, default=AuthType.PASSWORD.value
+        )
+        try:
+            auth_type = AuthType(auth_type.lower())
+        except ValueError:
+            logger.error(
+                f"Invalid value '{auth_type}' for {key}. "
+                + "Must be one of: "
+                + ", ".join([auth_type.value for auth_type in AuthType])
+                + "."
+            )
+            sys.exit(1)
+        return auth_type
+
     def get_username(self):
-        return self.get_env("FLATNOTES_USERNAME", mandatory=True)
+        return self.get_env(
+            "FLATNOTES_USERNAME", mandatory=self.auth_type != AuthType.NONE
+        )
 
     def get_password(self):
-        return self.get_env("FLATNOTES_PASSWORD", mandatory=True)
+        return self.get_env(
+            "FLATNOTES_PASSWORD", mandatory=self.auth_type != AuthType.NONE
+        )
 
     def get_session_key(self):
-        return self.get_env("FLATNOTES_SECRET_KEY", mandatory=True)
+        return self.get_env(
+            "FLATNOTES_SECRET_KEY", mandatory=self.auth_type != AuthType.NONE
+        )
 
     def get_session_expiry_days(self):
         return self.get_env(
git clone https://git.99rst.org/PROJECT