How to use the djangosaml2.backends.Saml2Backend function in djangosaml2

To help you get started, we’ve selected a few djangosaml2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github knaperek / djangosaml2 / tests / testprofiles / tests.py View on Github external
)

    def test_get_or_create_user_create(self):
        with self.assertLogs('djangosaml2', level='DEBUG') as logs:
            with override_settings(SAML_USER_MODEL='testprofiles.TestUser'):
                user, created = self.backend.get_or_create_user(self.backend._user_lookup_attribute, 'paul', True, None, None, None, None)

        self.assertTrue(isinstance(user, TestUser))
        self.assertTrue(created)
        self.assertIn(
            "DEBUG:djangosaml2:New user created: {}".format(user),
            logs.output,
        )


class CustomizedBackend(Saml2Backend):
    """ Override the available methods with some customized implementation to test customization
    """
    def is_authorized(self, attributes, attribute_mapping):
        ''' Allow only staff users from the IDP '''
        return attributes.get('is_staff', (None, ))[0] == True
    
    def clean_attributes(self, attributes: dict) -> dict:
        ''' Keep only age attribute '''
        return {
            'age': attributes.get('age', (None, )),
            'is_staff': attributes.get('is_staff', (None, )),
            'uid': attributes.get('uid', (None, )),
        }

    def clean_user_main_attribute(self, main_attribute):
        ''' Replace all spaces an dashes by underscores '''
github OpenMOOC / askbot-openmooc / askbotopenmooc / app / backends.py View on Github external
rjson = response.json()
    except:
        logger.debug("SAML_AUTORIZATION_URL response for %s is not json" % (
                     response.url))
        return False

    if expected_value in rjson.get(attribute_name, []):
        logger.debug("Permission Verified - list type, after attributes "
                     "request")
        return True
    else:
        logger.debug("Permission Denied - list type, after attributes request")
        return False


class Saml2RestrictedForumAccess(Saml2Backend):

    def is_authorized(self, attributes, attribute_mapping):
        attribute_name = getattr(settings, "SAML_AUTHORIZATION_ATTRIBUTE",
                                 None)
        expected_value = getattr(settings, "SAML_AUTHORIZATION_EXPECTED_VALUE",
                                 None)

        if not attribute_name:
            return True

        attribute_value = attributes.get(attribute_name, None)

        # expected_value not in attribute_value
        # expected_value != attribute_value
        # Then return PermissionDenied
        if (isinstance(attribute_value, list) and
github opennode / waldur-mastermind / src / waldur_auth_saml2 / auth.py View on Github external
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from djangosaml2.backends import Saml2Backend

User = get_user_model()


class WaldurSaml2Backend(Saml2Backend):
    def is_authorized(self, attributes, attribute_mapping):
        email = self.get_attribute_value('email', attributes, attribute_mapping)
        username = self.get_attribute_value('username', attributes, attribute_mapping)
        if (
            email
            and User.objects.filter(email=email).exclude(username=username).exists()
        ):
            raise ValidationError('User with this email already exists')
        return True
github cloudera / hue / desktop / libs / libsaml / src / libsaml / backend.py View on Github external
from django.contrib.auth import logout as auth_logout
from djangosaml2.backends import Saml2Backend as _Saml2Backend
from djangosaml2.views import logout as saml_logout
from libsaml import conf
from libsaml import metrics

from useradmin.models import get_profile, get_default_user_group, UserProfile, User

from desktop.auth.backend import force_username_case, rewrite_user
from desktop.conf import AUTH


LOG = logging.getLogger(__name__)


class SAML2Backend(_Saml2Backend):
  """
  Wrapper around djangosaml2 backend.
  """

  @classmethod
  def manages_passwords_externally(cls):
    return True


  @metrics.saml2_authentication_time
  def authenticate(self, *args, **kwargs):
    return super(SAML2Backend, self).authenticate(*args, **kwargs)


  def clean_user_main_attribute(self, main_attribute):
    """
github tl-its-umich-edu / student_explorer / student_explorer / backends.py View on Github external
from djangosaml2.backends import Saml2Backend
from django.core.exceptions import PermissionDenied

import logging

logger = logging.getLogger(__name__)


class ActiveUserOnlySAML2Backend(Saml2Backend):
    def authenticate(self, **kwargs):
        user = None
        try:
            user = super(ActiveUserOnlySAML2Backend, self).authenticate(**kwargs)
        except Exception:
            # If there's any exception with this authenticate just return PermisisonDenied
            logger.exception("Exception thrown from authenticate")
            raise PermissionDenied
        # If the user returned is None then we should also give raise PermissionDenied
        if not user:
            raise PermissionDenied
        # The user should be made active if they exist and aren't active
        if not user.is_active:
           user.is_active = True
           user.save()
        return user
github knaperek / djangosaml2 / djangosaml2 / backends.py View on Github external
def get_saml_user_model():
    warnings.warn("_set_attribute() is deprecated, look at the Saml2Backend on how to subclass it", DeprecationWarning)
    return Saml2Backend()._user_model
github OpenMOOC / moocng / moocng / courses / backends.py View on Github external
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.contrib.auth.models import Group
from django.contrib.auth.models import SiteProfileNotAvailable
from django.core.exceptions import ObjectDoesNotExist
from djangosaml2.backends import Saml2Backend
from moocng.courses.models import CourseTeacher
from moocng.teacheradmin.models import Invitation


class Saml2BackendExtension(Saml2Backend):

    """
    Extend the SAML2 backend for the integration with OpenMOOC.

    .. versionadded:: 0.1
    """
    # This function is called when a new user is created
    # we will check here if a pending teacher invitation
    # exists for this user
    def configure_user(self, user, attributes, attribute_mapping):
        """Configures a user after creation and returns the updated user.

        By default, returns the user with his attributes updated.
        """
        user.set_unusable_password()
        user = self.update_user(user, attributes, attribute_mapping,