def register_signals():
    user_logged_in.connect(log_user_logged_in, dispatch_uid="log_user_logged_in")
    user_logged_out.connect(log_user_logged_out, dispatch_uid="log_user_logged_out")
    user_login_failed.connect(
        log_user_login_failed, dispatch_uid="log_user_login_failed"
    )
    post_save.connect(log_user_created, sender=User, dispatch_uid="log_user_created")
 def connect(self):
   if not self.started:
     user_logged_in.connect(self.logged_in)
     user_logged_out.connect(self.logged_out)
     user_login_failed.connect(self.login_failed)
     self.started = True
   return self
Exemple #3
0
 def connect(self):
   if not self.started:
     user_logged_in.connect(self.logged_in, weak=False, dispatch_uid="dsl-logged-in")
     user_logged_out.connect(self.logged_out, weak=False, dispatch_uid="dsl-logged-out")
     user_login_failed.connect(self.login_failed, weak=False, dispatch_uid="dsl-logged-failed")
     self.started = True
   return self
Exemple #4
0
def init_watchers(w):
    for w in WATCH:
        if w == "login":
            user_logged_in.connect(login_action)
        elif w == "logout":
            user_logged_out.connect(logout_action)
        elif w == "login_failed":
            user_login_failed.connect(login_failed)
    return
Exemple #5
0
def init_watchers(w):
    for w in WATCH:
        if w == "login":
            user_logged_in.connect(login_action)
        elif w == "logout":
            user_logged_out.connect(logout_action)
        elif w == "login_failed":
            user_login_failed.connect(login_failed)
    return
    def __init__(self, request):
        """
        Doberman initialize...
        """

        self.request = request
        self.username = request.POST.get(configuration.username_form_field)
        self.configuration = configuration

        if self.username:
            self.user_hash = hashlib.md5(str(self.username)).hexdigest()  # Hash username
            user_login_failed.connect(login_failed, dispatch_uid=self.user_hash)

        else:
            # generate Doberman Exception..
            pass
    def test_login_failed(self):
        signal_calls = []

        def signal_handler(**kwargs):
            signal_calls.append(kwargs)

        user_login_failed.connect(signal_handler)
        fake_request = object()
        try:
            form = AuthenticationForm(fake_request, {
                'username': '******',
                'password': '******',
            })
            self.assertFalse(form.is_valid())
            self.assertIs(signal_calls[0]['request'], fake_request)
        finally:
            user_login_failed.disconnect(signal_handler)
Exemple #8
0
    def test_login_failed(self):
        signal_calls = []

        def signal_handler(**kwargs):
            signal_calls.append(kwargs)

        user_login_failed.connect(signal_handler)
        fake_request = object()
        try:
            form = AuthenticationForm(fake_request, {
                'username': '******',
                'password': '******',
            })
            self.assertFalse(form.is_valid())
            self.assertIs(signal_calls[0]['request'], fake_request)
        finally:
            user_login_failed.disconnect(signal_handler)
Exemple #9
0
    def test_login_failed(self):
        signal_calls = []

        def signal_handler(**kwargs):
            signal_calls.append(kwargs)

        user_login_failed.connect(signal_handler)
        fake_request = object()
        try:
            form = AuthenticationForm(
                fake_request,
                {
                    "username": "******",
                    "password": "******",
                },
            )
            self.assertFalse(form.is_valid())
            self.assertIs(signal_calls[0]["request"], fake_request)
        finally:
            user_login_failed.disconnect(signal_handler)
Exemple #10
0
def setup_signals():
    from django.contrib.auth.models import User, Group
    from django.contrib.admin.models import LogEntry

    user_logged_in.connect(successful_login,
                           dispatch_uid="tock_successful_login")
    user_logged_out.connect(successful_logout,
                            dispatch_uid="tock_successful_logout")
    user_login_failed.connect(failed_login, dispatch_uid="tock_failed_login")
    post_save.connect(adminlog_post_save,
                      sender=LogEntry,
                      dispatch_uid="tock_adminlog_post_save")
    m2m_changed.connect(log_m2m_change,
                        sender=User.groups.through,
                        dispatch_uid="tock_log_m2m_changed_user_groups")
    m2m_changed.connect(log_m2m_change,
                        sender=User.user_permissions.through,
                        dispatch_uid="tock_log_m2m_changed_user_permissions")
    m2m_changed.connect(log_m2m_change,
                        sender=Group.permissions.through,
                        dispatch_uid="tock_log_m2m_changed_groups_permissions")
Exemple #11
0
 def ready(self):
     user_logged_in.connect(send_logged_in)
     user_login_failed.connect(send_login_failed)
Exemple #12
0
############################################################################################

def auth_log(message, user = None):
  if user == None:
    user = User.objects.get(pk = 1)

  entry = LogEntry(user = user, object_repr = message, action_flag = 4)
  entry.save()

on_login = lambda **kwargs: auth_log(u'Вход в систему', kwargs['user'])
on_logout = lambda **kwargs: auth_log(u'Выход из системы', kwargs['user'])
on_login_error = lambda **kwargs: auth_log(u'Ошибка входа пользователя %s' % kwargs['credentials']['username']) 

user_logged_in.connect(on_login)
user_logged_out.connect(on_logout)
user_login_failed.connect(on_login_error)

def construct_log_entry(**kwargs):
    instance = kwargs['instance']
    content_type = ContentType.objects.get_for_model(instance)
    user = get_request().user
    log_entry = {}
    log_entry['user'] = user
    log_entry['object_repr'] = str(instance)
    log_entry['content_type'] = content_type 
    log_entry['object_id'] = instance.id if hasattr(instance, 'id') else -1
    return log_entry

@receiver(post_save)
def after_save(*args, **kwargs):
    instance = kwargs['instance']
Exemple #13
0
    ``authenticate()`` method from the ``contrib.auth`` package is broken by design.
    See https://code.djangoproject.com/ticket/23155 for details.
    This signal remain useful because we can keep monitor failed attempt on a specific account.
    :param sender: The sender class.
    :param credentials: Credentials passed to the ``authenticate()`` method.
    :param kwargs: Extra keywords arguments.
    :return: None
    """

    # Log the event
    LogEvent.objects.create(type=LOG_EVENT_LOGIN_FAILED,
                            username=credentials['username'],
                            ip_address=None)


user_login_failed.connect(_handle_user_login_failed)


def _handle_user_logout(sender, request, user, **kwargs):
    """
    Handle user logout.
    :param sender: The sender class.
    :param request: The current request.
    :param user: The logged-out user.
    :param kwargs: Extra keywords arguments.
    :return: None
    """

    # Do nothing if the user was not logged-in
    if user is None:
        return
Exemple #14
0
              description="Logged in",
              type=LOG_TYPE_LOGIN_OUT)
    log.save()


def create_logged_out_log_entry(sender, user, request, **kwargs):
    # log the logout!
    log = Log(ip_address=get_remote_ip(request),
              action=LOG_LOGOUT,
              description="Logged out",
              type=LOG_TYPE_LOGIN_OUT)
    if isinstance(request.user, User):
        log.user = request.user
    log.save()


def create_login_failed_log_entry(sender, credentials, request, **kwargs):
    # log the failed login!
    log = Log(user=None,
              ip_address=get_remote_ip(request),
              action=LOG_LOGIN_FAILED,
              description=f"Login failed: user={credentials['username']}",
              type=LOG_TYPE_LOGIN_OUT)
    log.save()


# hook into the user-logged-in/out/failed signal:
user_logged_in.connect(create_logged_in_log_entry)
user_logged_out.connect(create_logged_out_log_entry)
user_login_failed.connect(create_login_failed_log_entry)
Exemple #15
0
def auth_log(message, user=None):
    if user == None:
        user = User.objects.get(pk=1)

    entry = LogEntry(user=user, object_repr=message, action_flag=4)
    entry.save()


on_login = lambda **kwargs: auth_log(u'Вход в систему', kwargs['user'])
on_logout = lambda **kwargs: auth_log(u'Выход из системы', kwargs['user'])
on_login_error = lambda **kwargs: auth_log(u'Ошибка входа пользователя %s' %
                                           kwargs['credentials']['username'])

user_logged_in.connect(on_login)
user_logged_out.connect(on_logout)
user_login_failed.connect(on_login_error)


def construct_log_entry(**kwargs):
    instance = kwargs['instance']
    content_type = ContentType.objects.get_for_model(instance)
    user = get_request().user
    log_entry = {}
    log_entry['user'] = user
    log_entry['object_repr'] = str(instance)
    log_entry['content_type'] = content_type
    log_entry['object_id'] = instance.id if hasattr(instance, 'id') else -1
    return log_entry


@receiver(post_save)
Exemple #16
0
 def __init__(self, get_response=None):
     user_login_failed.connect(register_and_limit_failed_login_attempt)
     user_logged_in.connect(reset_user_ratelimit_on_login_success)
     super(LoginRateLimitMiddleware, self).__init__(get_response)
Exemple #17
0
    # Increase statsd counter.
    statsd.incr('models.%s.%s.delete' % (
        instance._meta.app_label,
        instance._meta.object_name,
    ))


if getattr(settings, 'STATSD_MODEL_SIGNALS', False):  # pragma: no cover
    post_save.connect(model_save)
    post_delete.connect(model_delete)


def logged_in(sender, request, user, **kwargs):
    statsd.incr('auth.login.success')
    statsd.incr('auth.backends.%s' % user.backend.replace('.', '_'))


def logged_out(sender, request, user, **kwargs):
    statsd.incr('auth.logout.success')


def login_failed(sender, credentials, **kwargs):
    statsd.incr('auth.login.failed')


if getattr(settings, 'STATSD_AUTH_SIGNALS', False):  # pragma: no cover
    user_logged_in.connect(logged_in)
    user_logged_out.connect(logged_out)
    user_login_failed.connect(login_failed)
Exemple #18
0
from django.contrib.auth.signals import user_logged_out, user_login_failed
from django.contrib import messages


def show_message_logout_succes(sender, user, request, **kwargs):
    messages.success(request, 'You have been successfully logged out.')


def show_message_login_fail(sender, credentials, request, **kwargs):
    messages.success(request, 'Login failed. Incorrect username or password.')


user_logged_out.connect(show_message_logout_succes)
user_login_failed.connect(show_message_login_fail)
Exemple #19
0
import logging

from django.contrib.auth.signals import user_login_failed

from .signals import get_request

logger = logging.getLogger(__name__)


def log_login_failure(sender, credentials, **kwargs):
    http_request = get_request()

    msg = "Login failure {}".format(http_request.META['REMOTE_ADDR'])
    logger.error(msg)


user_login_failed.connect(log_login_failure)
Exemple #20
0
def log_logout(sender, user, request, **kwargs):
    log.info("User {0} logged out.".format(user),
             extra={
                 'user': str(user),
                 'type': "logout"
             })


def log_logfail(sender, credentials, **kwargs):
    log.info("Failed login attempt.", extra={'user': 0, 'type': "login"})


user_logged_in.connect(log_login)
user_logged_out.connect(log_logout)
user_login_failed.connect(log_logfail)

# Create your views here.


# View user will see when first accessing website
def index(request):
    return render(request, 'index.html')


# View that a user will see when registering as a patient
def register(request):
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':

def handle_user_logged_in(sender, request, user, **kwargs):
    ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
    if ipaddr:
        # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
        ipaddr = [x.strip() for x in ipaddr.split(",")][0]
    else:
        ipaddr = request.META.get("REMOTE_ADDR", "")

    UserLogin.objects.create(remote_addr=ipaddr, user=user)
    
def handle_user_login_failed(sender, credentials, request, **kwargs):
    # Get IP
    ipaddr = "-unknown-"
    if request:
        ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
        if ipaddr:
            # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
            ipaddr = [x.strip() for x in ipaddr.split(",")][0]
        else:
            ipaddr = request.META.get("REMOTE_ADDR", "-unknown-")

    UserLogin.objects.create(remote_addr=ipaddr, credentials=credentials)

user_logged_in.connect(handle_user_logged_in,
    dispatch_uid='forallbackpack.signals.handle_user_logged_in')

user_login_failed.connect(handle_user_login_failed,
    dispatch_uid='forallbackpack.signals.handle_user_login_failed')
Exemple #22
0
        remaining_logins = MAX_FAILED_LOGINS - failed_logins
        raise forms.ValidationError(
            ungettext_lazy(
                u'%(error)s You only have one more login attempt before login is disabled '
                u'for %(time)d minutes. '
                u'Make sure to enter your password correctly.',
                # Plural
                u'%(error)s You have %(count)d login attempts before login is disabled '
                u'for %(time)d minutes.',
                # Count
                remaining_logins) %
            {
                'error': AuthenticationForm.error_messages['invalid_login'],
                'count': remaining_logins,
                'time': LOGIN_DISABLE_TIME / 60.0
            },
            code='invalid_login',
            params={'username': '******'},
        )


user_login_failed.connect(log_failed_login)


def log_succeeded_login(sender, user, **kwargs):
    """A signal receiver to log succeeded login"""
    LoginLog.objects.create(success=True, email=user.email)


user_logged_in.connect(log_succeeded_login)
Exemple #23
0
from django.dispatch import receiver

from .models import BIFUser

def logUserLogin(sender, user, request, **kwargs):
    logInfo(request, 'logged in')

def logUserLogout(sender, user, request, **kwargs):
    logInfo(request, 'logged out')

def logLoginFail(sender, credentials, request, **kwargs):
    logInfo(request, 'login failed (%s)' % credentials['username'])

user_logged_in.connect(logUserLogin)
user_logged_out.connect(logUserLogout)
user_login_failed.connect(logLoginFail)

import logging

def logInfo(request, message):
    logger = logging.getLogger(__name__)
    logger.info(logMessage(request,message))


def logError(request, message):
    logger = logging.getLogger(__name__)
    logger.error(logMessage(request,message))


def logMessage(request, message):
    from datetime import datetime
Exemple #24
0
        CreateUserEmotionRecordsForUserTask().delay(instance.pk, trace_id=trace_id)


post_save.connect(
    create_user_emotion_records,
    sender=settings.AUTH_USER_MODEL,
    dispatch_uid=settings.CREATE_USER_EMOTION_RECORDS_SIGNAL_UID
)


def update_user_emotion_attributes(sender, instance, created, *args, **kwargs):
    trace_id = getattr(instance, '_trace_id', '')

    if created and instance.vote:
        UpdateUserEmotionRecordAttributeTask().delay(instance.user_id, instance.emotion_id, trace_id=trace_id)
    elif not created:
        UpdateUserEmotionRecordAttributeTask().delay(instance.user_id, instance.emotion_id, trace_id=trace_id)


post_save.connect(
    update_user_emotion_attributes,
    sender=UserSongVote,
    dispatch_uid=settings.UPDATE_USER_EMOTION_ATTRIBUTES_SIGNAL_UID
)


user_login_failed.connect(
    log_failed_login_attempt,
    dispatch_uid=settings.LOG_MOODY_USER_FAILED_LOGIN_SIGNAL_UID
)
    """
    pass


def sig_user_login_failed(sender, **kwargs):
    """
    # Using django-axes to manage lockout after failed attempts.
    # This is just to log the event in our web_log table.
    """



    uname = kwargs['credentials']['username']

    # Try to match up with an existing user record
    try:
        user = User.objects.get(username=uname)
    except User.DoesNotExist:
        # activity_logger(-1, 'LOGIN_FAIL', content='user: unknown')
        pass
    else:
        # activity_logger(user.id, 'LOGIN_FAIL', content='user:%s' % (uname))
        pass

#
# Connect signals to functions
#
user_logged_in.connect(sig_user_logged_in)
user_logged_out.connect(sig_user_logged_out)
user_login_failed.connect(sig_user_login_failed)
Exemple #26
0
from django.dispatch import Signal
from django.contrib.auth.signals import user_login_failed

invitation_open = Signal(['username'])
invitation_accept = Signal(['username'])
invitation_expired = Signal(['username'])
auto_logout = Signal(['username'])
login_failure = Signal(['otp_failure'])
rate_limit_exceeded = Signal(['username'])

def _on_login_failure(sender, **kwargs):
    login_failure.send('hoover.contrib.twofactor', otp_failure=False)

user_login_failed.connect(_on_login_failure)
Exemple #27
0
from django.dispatch import Signal
from django.contrib.auth.signals import user_login_failed

invitation_open = Signal(['username'])
invitation_accept = Signal(['username'])
invitation_expired = Signal(['username'])
auto_logout = Signal(['username'])
login_failure = Signal(['otp_failure'])
rate_limit_exceeded = Signal(['username'])


def _on_login_failure(sender, **kwargs):
    login_failure.send('hoover.contrib.twofactor', otp_failure=False)


user_login_failed.connect(_on_login_failure)
Exemple #28
0
""" 
A reusable app that logs failed logins
including the remote IP address.From there
fail2ban takes action.
"""
from django.contrib.auth.signals import user_login_failed

from login_failure.signals import get_request

import logging

logger = logging.getLogger('fail2ban')

def log_login_failure(sender, credentials, **kwargs):
    http_request = get_request()

    msg = "Login failure {}".format(http_request.META.get('HTTP_X_FORWARDED_FOR'))
    logger.error(msg)

user_login_failed.connect(log_login_failure)
Exemple #29
0
 def ready(self):
     if settings.LOGIN_ACTIVATE == 'yes':
         user_login_failed.connect(login_fail)
         user_logged_in.connect(login_success)
Exemple #30
0
        super(CustomUser, self).save(*args, **kwargs)

  

class LogEntry(models.Model):
    doorkey = models.CharField(max_length=32)
    name = models.CharField(max_length=32)
    time = models.DateTimeField(default=timezone.now)
    validentry = models.BooleanField(default=False)



def log_user(sender, request, user, **kwargs):
    if isinstance(user, CustomUser):
        log = LogEntry(doorkey=user.doorkey, name=user.username)
        log.validentry = True
        log.save()

def log_bad_user(sender, **kwargs):
    log = LogEntry(doorkey=kwargs['credentials']['extra'], name='UNKNOWN')
    log.validentry = False
    log.save()

user_login_failed.connect(log_bad_user)
user_logged_in.connect(log_user)

@receiver(post_delete, sender=CustomUser)
def post_delete_user(sender, instance, *args, **kwargs):
    instance.image.delete(save=False)
        
Exemple #31
0
        user = user.first()
        user.unsuccessful_login_attempts += 1
        user.save()

        if user.unsuccessful_login_attempts > 10:
            ActivityStream(customer=user.customer,
                           actor='unknown',
                           verb='Login_fail_exceeded_10times_account_disabled',
                           target=user.username).save()
            user.is_active = False
            user.save()


user_logged_in.connect(login_do_stuff)
user_logged_out.connect(logout_do_stuff)
user_login_failed.connect(login_failed_do_stuff)


class UserManager(BaseUserManager):
    def create_user(self,
                    customer=None,
                    username=None,
                    email=None,
                    password=None,
                    first_name=None,
                    last_name=None,
                    phone=None,
                    is_owner=False,
                    is_team=False,
                    is_client=False,
                    is_clinician=False,
Exemple #32
0
# coding=utf-8
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
import logging

# Definicion de señales
logger = logging.getLogger(__name__)

def log_login(sender, request, user, **kwargs):
    logger.info("<%s> ha iniciado sesion desde <%s>" % (user.username,request.get_host()))
def log_logout(sender, request, user, **kwargs):
    logger.info("<%s> ha cerrado sesion correctamente" % user.username)
def log_failed(sender, credentials, **kwargs):
    print sender, credentials, kwargs 
    logger.error("<%s> fallo al iniciar sesion" % (credentials['username']))   

user_logged_in.connect(log_login)
user_logged_out.connect(log_logout)
user_login_failed.connect(log_failed)
Exemple #33
0
            else:
                logger.warning("user not found in AD")
                return None
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


def post_logged_in(sender, request, user, **kwargs):
    request_info = "%s %s" % (request.path, get_ip(request))
    logger.info("Log In Success %s %s" % (user.username, request_info))


def post_logged_out(sender, request, user, **kwargs):
    request_info = "%s %s" % (request.path, get_ip(request))
    logger.info("Log Out %s %s" % (user and user.username or "none", request_info))


def post_login_failed(sender, request, credentials, **kwargs):
    request_info = "%s %s" % (request.path, get_ip(request))
    logger.info("Signal Log In Failure %s %s" % (credentials.get("username", "-"), request_info))


user_logged_in.connect(post_logged_in)
user_logged_out.connect(post_logged_out)
user_login_failed.connect(post_login_failed)
Exemple #34
0
    event = event_cls(metadata, payload)
    event.post()


def user_logged_in_callback(sender, request, user, **kwargs):
    post_event(LoginEvent, request, user)


user_logged_in.connect(user_logged_in_callback)


def user_logged_out_callback(sender, request, user, **kwargs):
    post_event(LogoutEvent, request, user)


user_logged_out.connect(user_logged_out_callback)


def user_login_failed_callback(sender, credentials, **kwargs):
    request = kwargs.get("request")  # introduced in django 1.11
    if request:
        request = make_event_metadata_request(request)
    metadata = EventMetadata(FailedLoginEvent.event_type,
                             request=request,
                             tags=FailedLoginEvent.tags)
    event = FailedLoginEvent(metadata, credentials)
    event.post()


user_login_failed.connect(user_login_failed_callback)
Exemple #35
0
 def __init__(self):
     user_login_failed.connect(register_and_limit_failed_login_attempt)
     user_logged_in.connect(reset_user_ratelimit_on_login_success)
Exemple #36
0

def user_login_failed_callback(sender, credentials, **kwargs):
    request = kwargs.get("request")  # introduced in django 1.11
    if request:
        request = EventRequest.build_from_request(request)
    metadata = EventMetadata(FailedLoginEvent.event_type,
                             request=request,
                             tags=FailedLoginEvent.tags)
    event = FailedLoginEvent(metadata,
                             {k: str(v)
                              for k, v in credentials.items()})
    event.post()


user_login_failed.connect(user_login_failed_callback)


def post_failed_verification_event(request, user):
    post_event(FailedVerificationEvent, request, user)


def post_verification_device_event(request,
                                   user,
                                   action,
                                   verification_device=None):
    if verification_device is None:
        payload = {}
    else:
        payload = {"device": verification_device.serialize_for_event()}
    payload["action"] = action
Exemple #37
0
        ugettext_lazy("Notes"),
        null=True,
    )

    class Meta:
        verbose_name = ugettext_lazy("Action")
        verbose_name_plural = ugettext_lazy("Actions")


def user_in(sender, user, request, **kwargs):
    UserAuthAction.objects.create(
        user=user,
        action_type=LOGIN_ACTION
    )
user_logged_in.connect(user_in)


def user_out(sender, user, request, **kwargs):
    UserAuthAction.objects.create(
        user=user,
        action_type=LOGOUT_ACTION
    )
user_logged_out.connect(user_out)


def user_fail(sender, credentials, **kwargs):
    UserAuthAction.objects.create(
        action_type=FAIL_ACTION
    )
user_login_failed.connect(user_fail)