From 9152c524b3dc827d450a8db700162999d113ac5a Mon Sep 17 00:00:00 2001
From: Art Lukyanchyk <artiom.lukyanchyk@hs-hannover.de>
Date: Thu, 31 Jan 2019 16:53:56 +0100
Subject: [PATCH] Replace some assertions (those which shouldn't be assertions)
 with proper exceptions

---
 ssoauth/__init__.py   |  2 +-
 ssoauth/auth_utils.py | 15 ++++++++-------
 ssoauth/sso_utils.py  | 13 +++++++++----
 3 files changed, 18 insertions(+), 12 deletions(-)

diff --git a/ssoauth/__init__.py b/ssoauth/__init__.py
index 4e93af4..76976b9 100644
--- a/ssoauth/__init__.py
+++ b/ssoauth/__init__.py
@@ -1,7 +1,7 @@
 import logging
 
 from . import checks  # As for Django 1.11 it still doesn't auto-import checks >.<
-assert checks
+assert checks  # must be imported
 
 
 logger = logging.getLogger("ssoauth")
diff --git a/ssoauth/auth_utils.py b/ssoauth/auth_utils.py
index cf5b0ae..1acfa8b 100644
--- a/ssoauth/auth_utils.py
+++ b/ssoauth/auth_utils.py
@@ -11,8 +11,10 @@ import importlib
 
 
 def _validate_username(username):
-    assert isinstance(username, str)
-    assert username == username.lower()  # because .islower() returns False when no letters present
+    if not isinstance(username, str):
+        raise TypeError
+    if not username == username.lower():  # weird check because .islower() returns False when no letters present
+        raise ValueError("Username must be lowere case")
 
 
 def get_user(uuid=None, username=None):
@@ -70,10 +72,10 @@ def get_or_create_user(uuid, username):
         logger.info("Created user: {username} {uuid}".format(**locals()))
         return user
 
-    # checks and casts
+    # prepare
     if isinstance(uuid, str):
         uuid = UUID(uuid)
-    assert isinstance(uuid, UUID) and isinstance(username, str), "Bad arguments"
+    assert isinstance(uuid, UUID) and isinstance(username, str)
     username = username.lower()
     # get or create
     user = get_user_by_uuid(uuid, username)  # best case scenario
@@ -109,12 +111,11 @@ def set_user_groups(user, saml2_groups):
         raise ImportError("Could not import {r}. {e.__class__.__name__}: {e}".format(r=app_settings.GROUP_RESOLVER, e=e))
     # resolve the groups
     groups = resolver_method(user, saml2_groups)
-    assert isinstance(groups, (list, tuple, set,)) and all(isinstance(g, Group) for g in groups), \
-        "{r} instead of a list/tuple/set of Group objects returned: {garbage}".format(r=app_settings.GROUP_RESOLVER, garbage=groups)
+    assert isinstance(groups, (list, tuple, set,)) and all(isinstance(g, Group) for g in groups)
     # update user groups
     if set(user.groups.all()) != set(groups):
         user.groups.set(groups)
-        assert set(user.groups.all()) == set(groups)  # dunno how relation.set() behaves, better safe than sorry
+        assert set(user.groups.all()) == set(groups)
         logger.info("Groups for {user} were updated.".format(user=user))
     # done
     logger.info("User {user} is member of: {groups}".format(user=user, groups=set(str(g) for g in groups)))
diff --git a/ssoauth/sso_utils.py b/ssoauth/sso_utils.py
index 1a5b987..3e6a429 100644
--- a/ssoauth/sso_utils.py
+++ b/ssoauth/sso_utils.py
@@ -58,8 +58,11 @@ def get_idp_runtime_info(meta_url):
     logger.debug("From the IDP metadata received {s} signing certs, {e} encryption certs, {sso} SSO bindings, {slo} SLO bindings.".format(
         s=len(signing), e=len(encryption), sso=len(bindings_sso_redirect), slo=len(bindings_slo_redirect),
     ))
-    assert signing and encryption, "Could not find certificates in IDP meta."
-    assert bindings_sso_redirect is not None, "Could not find SSO HTTP-Redirect binding."
+    if not (signing and encryption):
+        raise RuntimeError("Could not find certificates in IDP meta.")
+    if bindings_sso_redirect is None:
+        raise RuntimeError("Could not find SSO HTTP-Redirect binding.")
+
     # pack the received data
     return {
         "certificates": {
@@ -78,14 +81,16 @@ def create_onelogin_settings(template=app_settings.ONELOGIN_SETTINGS_TEMPLATE):
     # get the template
     settings = copy(template)
     # prepare some values
-    assert app_settings.SP_HOST, "SP_HOST is not set."  # before OneLogin toolkit chokes with "sp_acs_url_invalid,sp_sls_url_invalid"
+    if not app_settings.SP_HOST:
+        raise ValueError("SP_HOST is not set")  # before OneLogin toolkit chokes with "sp_acs_url_invalid,sp_sls_url_invalid"
     host_full = "{protocol}://{host}{port_suffix}".format(
         host=app_settings.SP_HOST,
         protocol="https" if app_settings.SP_SSL else "http",
         port_suffix="" if app_settings.SP_PORT in [80, 443] else ":{0}".format(app_settings.SP_PORT)
     )
     # IDP settings
-    assert app_settings.IDP_META_URL, "IDP_META_URL is not set"  # before get_idp_runtime_info starts logging errors
+    if not app_settings.IDP_META_URL:
+        raise ValueError("IDP_META_URL is not set")  # before get_idp_runtime_info starts logging errors
     idp_info = get_idp_runtime_info(app_settings.IDP_META_URL)
     settings["idp"]["x509certMulti"]["signing"] = idp_info["certificates"]["signing"]
     settings["idp"]["x509certMulti"]["encryption"] = idp_info["certificates"]["encryption"]
-- 
GitLab