Ejemplo n.º 1
0
 def form_valid(self, form):
     user_model = get_user_model()
     user = user_model.objects.get(username=form.cleaned_data['username'])
     update_user = {
         'is_superuser': form.cleaned_data['is_superuser'],
         'is_staff': form.cleaned_data['is_staff']
     }
     user.objects.update_user(**update_user)
     user.save()
     return super(Update, self).form_valid(form)
Ejemplo n.º 2
0
    def dispatch(self, request, *args, **kwargs):
        username = request.user
        logout(request)

        if getattr(settings, 'CLEAR_USER_ON_LOGOUT', False):
            user_model = get_user_model()
            db_user = user_model.objects.get(username=username)
            db_user.delete()

        return HttpResponseRedirect(self.get_next_page() or '/')
        return super().dispatch(request, *args, **kwargs)
Ejemplo n.º 3
0
    def form_valid(self, form):
        user_model = get_user_model()
        create_user = {
            'password': form.cleaned_data['password1'],
            'is_superuser': False,
            'is_staff': False,
            'email': form.cleaned_data['email']
        }
        # Register with cognito
        user_model.objects.create_user(**create_user)

        return super(Register, self).form_valid(form)
Ejemplo n.º 4
0
    def dispatch(self, request, *args, **kwargs):
        username = request.user.username
        logout(request)

        if getattr(settings, 'CLEAR_USER_ON_LOGOUT', False):
            user_model = get_user_model()
            db_user = user_model.objects.get(username=username)
            db_user.delete()

        next_page = self.get_next_page()
        if next_page:
            # Redirect to this page until the session has been cleared.
            return HttpResponseRedirect(next_page)
        return super().dispatch(request, *args, **kwargs)
Ejemplo n.º 5
0
    def form_valid(self, form):
        user_model = get_user_model()
        create_user = {
            'username': form.cleaned_data['username'],
            'password': form.cleaned_data['password1'],
            'is_superuser': form.cleaned_data['is_superuser'],
            'is_staff': form.cleaned_data['is_staff']
        }

        # Register with cognito
        register(self.request, create_user)
        user_model.objects.create_user(**create_user)
        new_user = authenticate(username=create_user['username'],
                                password=create_user['password'])
        barrier_field_login(self.request, new_user)
        return super(Register, self).form_valid(form)
Ejemplo n.º 6
0
    def form_valid(self, form):
        cognito = cognito_client()
        email_address = form.cleaned_data['email_address']
        verification_code = form.cleaned_data['verification_code']
        new_password = form.cleaned_data['password2']
        user_model = get_user_model()
        db_user = user_model.objects.get(email=email_address)
        cognito.username = email_address
        try:
            db_user.set_password(new_password)
            db_user.save()
            response = cognito.confirm_forgot_password(verification_code,
                                                       new_password)

        except Exception as ex:
            form.add_error(field='verification_code',
                           error=f'Something went wrong: {ex} ->  Resp:')
        return redirect(reverse('cognito-login'))
Ejemplo n.º 7
0
    def form_valid(self, form):
        cognito = cognito_client()
        current_password = form.cleaned_data['current_password']
        new_password = form.cleaned_data['password1']
        user_model = get_user_model()
        db_user = user_model.objects.get(email=self.request.user)

        try:
            db_user.set_password(new_password)
            db_user.save()
            cognito.change_password(self.request, current_password,
                                    new_password)
        except Exception as e:
            try:
                error = e.response['Error']
            except AttributeError:
                raise AttributeError('Something went wrong there...')
            if error['Code'] == 'InvalidPasswordException':
                form.add_error(field='new_password1', error=error['Message'])
                return super(ChangePassword, self).form_invalid(form)
        else:
            return redirect(getattr(settings, 'PASSWORD_CHANGE_REDIRECT_URL'),
                            '/')
Ejemplo n.º 8
0
    def sync_cache(self, cognito_user, deactivate=False):
        """
        Check and update local user data, and sync with cognito data if needed
        :param cognito_user:
        :param deactivate: if True, is_active of local user will be set to
        False. This will be run in the case of the cognito user being disabled.
        :return:
        """
        Users = get_user_model()

        if deactivate:
            local_user = Users.objects.get(
                username=cognito_user['username']
            )
            local_user.is_active = False
            local_user.save()
        else:
            try:
                local_user = Users.objects.get(email=cognito_user.pk)
                if not local_user.is_active:
                    # Reactive user
                    local_user.is_active = True

                cognito_data = cognito_user._data

                user_data_fields = get_user_data_model_fields()
                if user_data_fields:
                    user_data_update = {}
                    for field in [*cognito_data.keys()].copy():
                        if field in user_data_fields:
                            user_data_update[field] = cognito_data.pop(field)

                    # Update user data
                    user_data_object = get_user_data_model().objects.filter(
                        pk=local_user.user_data_id
                    )
                    user_data_object.update(**user_data_update)

                for field in cognito_data.keys():
                    cognito_field_value = getattr(cognito_user, field)
                    if isinstance(getattr(local_user, field), bool):
                        cognito_field_value = bool(int(cognito_field_value))
                    setattr(local_user, field, cognito_field_value)

                local_user.save()
            except Users.DoesNotExist:
                # Create new cached user

                # First check whether a custom data model exists
                user_data_fields = get_user_data_model_fields()
                if user_data_fields:
                    compiled_user_data = {}
                    for field in user_data_fields:
                        if field in cognito_user._data.keys():
                            user_data = cognito_user._data.pop(field)
                            compiled_user_data[field] = user_data
                    user_data = get_user_data_model().objects.create(
                        **compiled_user_data
                    )

                    Users.objects.create_user(
                        username=cognito_user.username, password=None,
                        user_data=user_data, **cognito_user._data
                    )
                else:
                    Users.objects.create_user(
                        username=cognito_user.username, password=None,
                        **cognito_user._data
                    )
Ejemplo n.º 9
0
class CognitoAuth:
    Users = get_user_model()
    cognito = cognito_client()
    cognito_mapping = get_attr_map()

    def get_user(self, request):
        return self.Users.objects.get(pk=request)

    def authenticate(self, request, username=None, password=None,
                     cognito_auth=None):
        """
        Authenticate with cognito. If authentication is success the cognito
        user will be sync'ed with local cache.
        :param request:
        :param username:
        :param password:
        :param cognito_auth: If cognito user has already been authorised,
        and you are completing authentication (for example, force changing
        password or completeing MFA), send the authorised cognito token
        :return:
        """
        self.cognito.username = username

        if not is_enabled():
            return None

        if not cognito_auth:
            # New user session authentication
            try:
                self.cognito.authenticate(password, request)
            except Exception as e:
                resp = self.cognito.auth_error_handler(e)
                return resp
        else:
            # Validate authentication
            self.cognito.verify_token(
                cognito_auth['AuthenticationResult']['IdToken'],
                'id_token','id'
            )
            self.cognito.verify_token(
                cognito_auth['AuthenticationResult']['AccessToken'],
                'access_token', 'access'
            )

        self.update_session(request)
        user = self.cognito.get_user(self.cognito_mapping)
        self.cognito.sync_cache(user)
        cache_user = self.Users.objects.get(username=user.pk)
        return cache_user

    def update_session(self, request):
        """
            Add refresh token to the session so it can be accessed
        """
        if getattr(request, 'session', False):
            request.session['cognito_auth'] = {
                'access_token': self.cognito.access_token,
                'refresh_token': self.cognito.refresh_token,
                'token_type': self.cognito.token_type,
                'id_token': self.cognito.id_token
            }