def test_post_should_not_login_if_user_is_not_active(self): """ In Django >= 1.10 authenticate() returns None if user is inactive, while in Django < 1.10 authenticate() succeeds if user is inactive. """ user = create_user() data = { 'username': user.username, 'password': user.raw_password, } user.is_active = False user.save() user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) if django.VERSION >= (1, 10): expected_errors = [djoser.constants.INVALID_CREDENTIALS_ERROR] else: expected_errors = [djoser.constants.INACTIVE_ACCOUNT_ERROR] self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data['non_field_errors'], expected_errors) self.assertFalse(self.signal_sent)
def ready(self): from c3nav.editor.models import ChangeSet from c3nav.editor.signals import set_changeset_author_on_login post_save.connect(ChangeSet.object_changed_handler) post_delete.connect(ChangeSet.object_changed_handler) m2m_changed.connect(ChangeSet.object_changed_handler) user_logged_in.connect(set_changeset_author_on_login)
def login_as_user(request, user_id): userobj = authenticate(su=True, user_id=user_id) if not userobj: raise Http404("User not found") exit_users_pk = request.session.get("exit_users_pk", default=[]) exit_users_pk.append( (request.session[SESSION_KEY], request.session[BACKEND_SESSION_KEY])) user_logged_in.disconnect(update_last_login) try: if not custom_login_action(request, userobj): login(request, userobj) finally: user_logged_in.connect(update_last_login) request.session["exit_users_pk"] = exit_users_pk if hasattr(settings, 'SU_REDIRECT_LOGIN'): warnings.warn( "SU_REDIRECT_LOGIN is deprecated, use SU_LOGIN_REDIRECT_URL", DeprecationWarning, ) return HttpResponseRedirect( getattr(settings, "SU_LOGIN_REDIRECT_URL", "/"))
def test_post_should_login_user(self): user = create_user() data = {"username": user.username, "password": user.raw_password} user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_200_OK) self.assertEqual(response.data["auth_token"], user.auth_token.key) self.assertTrue(self.signal_sent)
def test_post_should_not_login_if_user_is_not_active(self): user = create_user() data = {"username": user.username, "password": user.raw_password} user.is_active = False user.save() user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data["non_field_errors"], [djoser.constants.INACTIVE_ACCOUNT_ERROR]) self.assertFalse(self.signal_sent)
def test_post_should_login_user(self): user = create_user() data = { 'username': user.username, 'password': user.raw_password, } user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_200_OK) self.assertEqual(response.data['auth_token'], user.auth_token.key) self.assertTrue(self.signal_sent)
def impersonate(request, user_id): """ Allows a superuser to impersonate another user. """ admin_user = request.user user = User.objects.get(id=user_id) # Login as the specified user user.backend = 'django.contrib.auth.backends.ModelBackend' user_logged_in.disconnect(update_last_login) login(request, user) user_logged_in.connect(update_last_login) request.session[IMPERSONATED_BY_KEY] = admin_user.id request.session[IMPERSONATING_KEY] = user.id messages.success(request, 'Impersonation successful.') return HttpResponseRedirect(reverse('home'))
def test_post_with_sanitizers(self): user = create_user(**{'username': '******'}) data = { 'username': '******', 'password': user.raw_password, } user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_200_OK) self.assertEqual(response.data['auth_token'], user.auth_token.key) self.assertTrue(self.signal_sent)
def test_post_should_not_login_if_user_is_not_active(self): user = create_user() data = { 'username': user.username, 'password': user.raw_password, } user.is_active = False user.save() user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data['non_field_errors'], [djoser.constants.INVALID_CREDENTIALS_ERROR]) self.assertFalse(self.signal_sent)
def test_post_should_not_login_if_user_is_not_active(self): user = create_user() data = { 'username': user.username, 'password': user.raw_password, } user.is_active = False user.save() user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data['non_field_errors'], [djoser.constants.INACTIVE_ACCOUNT_ERROR]) self.assertFalse(self.signal_sent)
def test_post_should_login_user(self): user = create_user() previous_last_login = user.last_login data = { 'username': user.username, 'password': user.raw_password, } user_logged_in.connect(self.signal_receiver) request = self.factory.post(data=data) response = self.view(request) user.refresh_from_db() self.assert_status_equal(response, status.HTTP_200_OK) self.assertEqual(response.data['auth_token'], user.auth_token.key) self.assertNotEqual(user.last_login, previous_last_login) self.assertTrue(self.signal_sent)
def test_login_by_email(self): # starting test without allauth app settings.INSTALLED_APPS.remove('allauth') payload = {"email": self.EMAIL.lower(), "password": self.PASS} # there is no users in db so it should throw error (400) self.post(self.login_url, data=payload, status_code=400) self.post(self.password_change_url, status_code=403) # create user user = get_user_model().objects.create_user(self.USERNAME, self.EMAIL, self.PASS) # test auth by email user_logged_in.connect(self.on_login) self.post(self.login_url, data=payload, status_code=200) self.assertTrue(self.signal_sent) self.assertEqual('key' in self.response.json.keys(), True) self.token = self.response.json['key'] # test auth by email in different case payload = {"email": self.EMAIL.upper(), "password": self.PASS} self.post(self.login_url, data=payload, status_code=200) self.assertEqual('key' in self.response.json.keys(), True) self.token = self.response.json['key'] # test inactive user user.is_active = False user.save() self.post(self.login_url, data=payload, status_code=400) # test wrong email/password payload = {"email": 't' + self.EMAIL, "password": self.PASS} self.post(self.login_url, data=payload, status_code=400) # test empty payload self.post(self.login_url, data={}, status_code=400) # bring back allauth settings.INSTALLED_APPS.append('allauth')
def test_post_should_not_login_if_user_is_not_active(self): """ In Django >= 1.10 authenticate() returns None if user is inactive, while in Django < 1.10 authenticate() succeeds if user is inactive. """ user = create_user() data = {"username": user.username, "password": user.raw_password} user.is_active = False user.save() user_logged_in.connect(self.signal_receiver) response = self.client.post(self.base_url, data) if django.VERSION >= (1, 10): expected_errors = [settings.CONSTANTS.messages.INVALID_CREDENTIALS_ERROR] else: expected_errors = [settings.CONSTANTS.messages.INACTIVE_ACCOUNT_ERROR] self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data["non_field_errors"], expected_errors) self.assertFalse(self.signal_sent)
class UserSession(models.Model): user = models.ForeignKey(Userreg, on_delete=models.CASCADE, related_name='user_id_session') session = models.ForeignKey(Session, on_delete=models.CASCADE) def user_logged_in_handler(request, customuser, **kwargs): if not request.session.session_key: request.session.save() session_id = request.session.session_key UserSession.objects.get_or_create(user=customuser, session_id=session_id) user_logged_in.connect(user_logged_in_handler)
def test_allauth_login_with_username(self): payload = {"username": self.USERNAME, "password": self.PASS} # there is no users in db so it should throw error (400) user_logged_in.connect(self.on_login) self.post(self.login_url, data=payload, status_code=400) self.assertFalse(self.signal_sent) self.post(self.password_change_url, status_code=403) self.assertFalse(self.signal_sent) # create user user = get_user_model().objects.create_user(self.USERNAME, '', self.PASS) self.post(self.login_url, data=payload, status_code=200) self.assertEqual('key' in self.response.json.keys(), True) self.assertTrue(self.signal_sent) self.token = self.response.json['key'] self.signal_sent = False self.post(self.password_change_url, status_code=400) self.assertFalse(self.signal_sent) # test inactive user user.is_active = False user.save() self.post(self.login_url, data=payload, status_code=400) self.assertFalse(self.signal_sent) # test wrong username/password payload = {"username": self.USERNAME + '?', "password": self.PASS} self.post(self.login_url, data=payload, status_code=400) self.assertFalse(self.signal_sent) # test empty payload self.post(self.login_url, data={}, status_code=400) self.assertFalse(self.signal_sent)
class LoggedUser(models.Model): user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE) def __unicode__(self): return self.user.username def login_user(sender, request, user, **kwargs): LoggedUser(user=user).save() def logout_user(sender, request, user, **kwargs): try: u = LoggedUser.objects.get(user=user) u.delete() except LoggedUser.DoesNotExist: pass user_logged_in.connect(login_user) user_logged_out.connect(logout_user)
class UserSession(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.SET_NULL, null=True) loggedin = models.DateTimeField(auto_now_add=True) loggedout = models.DateTimeField(default=None, null=True) headers = JSONField(encoder=SafeEncoder, default=dict) def __str__(self): return self.user.username def login_user(sender, request, user, **kwargs): """Log User Session creation""" UserSession(user=user, session_id=request.session.session_key, headers=request.META).save() def logout_user(sender, request, user, **kwargs): """Log User Session destruction""" try: u = UserSession.objects.get(user=user, session_id=request.session.session_key) u.loggedout = timezone.now() u.save() # u.delete() except UserSession.DoesNotExist: pass # Event binding: user_logged_in.connect(login_user) user_logged_out.connect(logout_user) def elapsed(self): """Elapsed time since logged in""" if self.loggedout: return self.loggedout - self.loggedin else: return timezone.now() - self.loggedin def is_active(self): """Is the session active""" return (self.loggedout is None) or not (self.session_id is None)
class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) login_count = models.PositiveIntegerField(default=0) time_spent = models.FloatField(default=0) # in minutes login_status = models.BooleanField(default=False) def login_user(sender, request, user, **kwargs): user.userprofile.login_count = user.userprofile.login_count + 1 user.userprofile.login_status = True user.userprofile.save() def logout_user(sender, request, user, **kwargs): user.userprofile.login_status = False # time difference between logout time and last login is added to time spent in minutes user.userprofile.time_spent = (timezone.now() - user.last_login).seconds / 60 user.userprofile.save() user_logged_in.connect(login_user) user_logged_out.connect(logout_user)
class Perfiles(models.Model): nombre = models.CharField(max_length=20) apellido = models.CharField(max_length=25) telefono = models.IntegerField() correo = models.EmailField(max_length=70) activation_key = models.CharField(max_length=40, blank=True) date_key_expires = models.DateTimeField(default=timezone.now) usuario = models.OneToOneField(User) def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login']) user_logged_in.connect(update_last_login) def __unicode__(self): return self.usuario.username
'text': json.dumps({ 'username': self.user.username, 'activity_type': 'notification', 'activity': activity }) }) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_user_profile(sender, instance, **kwargs): instance.profile.save() def on_user_login(sender, **kwargs): Profile.objects.get(user=kwargs['user']).notify_login() def on_user_logout(sender, **kwargs): Profile.objects.get(user=kwargs['user']).notify_logout() post_save.connect(create_user_profile, sender=User) post_save.connect(save_user_profile, sender=User) user_logged_in.connect(on_user_login, sender=User) user_logged_out.connect(on_user_logout, sender=User)
""" if created: UserProfile.objects.create(user=instance) Membership.objects.create(user=instance) post_save.connect(post_save_create_user_and_membership_profile, sender=User) def post_membership_save_status_update(sender, instance, created, *args, **kwargs): """ updates membership once profile is created or edited """ user_profile = UserProfile.objects.get(user=instance.user) user_profile.update_user_membership_profile() post_save.connect(post_membership_save_status_update, sender=Membership) def check_user_membership_status(sender, request, user, *args, **kwargs): #if user can log in, then profile was created #update users membership once user logs in loged_in_user_profile = UserProfile.objects.get(user=user) loged_in_user_profile.update_user_membership_profile() user_logged_in.connect(check_user_membership_status)
return user_profile def check_profile(sender, user: str, request, **kwargs): """ On first time log in check if there is a profile and if there are data entries from a person with name user in the profile. :param sender: :param user: :param request: :param kwargs: """ user_obj = User.objects.get(username=user) if Profile.objects.filter(user__username=user).exists(): # if user has a profile user_profile = Profile.objects.get(user__username=user) if user_profile.checkedAssociation: # Profile should be filled, so there is nothing to do. pass elif user_profile.metacatalogPerson_id: # no Association for data checked, so check if there is data now. # TODO: implement this! __assign_data() __assign_data(user_obj, user_profile) pass else: # only user in profile, so assign_person first __assign_data(user_obj, user_profile) # print('\033[91mYour user needs first and last name to associate user with data.\033[0m') else: # there is no profile at all for this user user_profile = __assign_person(user) __assign_data(user_obj, user_profile) user_logged_in.connect(check_profile)
class User(AbstractBaseUser): """Main user model in app""" username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=100, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): """Does the user have a specific permission?""" return self.is_admin def has_module_perms(self, app_label): """Does the user have permissions to view the app `app_label`?""" return self.is_admin @property def is_staff(self): """Is the user a member of staff?""" return self.is_admin user_logged_in.connect(update_last_login, dispatch_uid="update_last_login")
from django.contrib.auth import user_logged_in, user_logged_out from django.contrib.staticfiles import finders from django.contrib.staticfiles.templatetags.staticfiles import static from rest_framework.authtoken.models import Token def login_signal(sender, user, request, **kwargs): token = Token.objects.get_or_create(user=user) request.session['token'] = token[0].key if finders.find('logo/logo.png'): request.session['logo_existe'] = True def logout_signal(sender, user, request, **kwargs): request.session['token'] = None request.session['logo_existe'] = False user_logged_in.connect(login_signal) user_logged_out.disconnect(logout_signal)
logUsuario.tipo_login = "******" logUsuario.dia = hoydia() logUsuario.hora = hoyhora() x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') logUsuario.ip = ip logUsuario.save() request.session['0'] = 'bar' usuario = AuthUser.objects.get(id=userInstance.id) usuario.login = True usuario.save() user_logged_in.connect(do_loginIn) def do_login_failed(sender, **kwargs): print(sender) user_login_failed.connect(do_login_failed) def do_loginOut(sender, user, request, **kwargs): userInstance = AuthUser.objects.get(username=user) logUsuario = LogUsuarios() logUsuario.id_usuario = userInstance.id logUsuario.passw = userInstance.password logUsuario.nombre_usuario = user logUsuario.es_super_usuario = userInstance.is_superuser logUsuario.primer_nombre = userInstance.first_name
class Meta: unique_together = (("usuario", "vista", "opcion"), ) def __str__(self): return "{} en {} del usuario {}".format(self.opcion, self.vista, self.usuario) class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) # ---------------------------------------------- # Este código se dispara cuando el usuario inicia sesión y previene que un mismo usuario # tenga más de una sesión activa simultánea. def eliminar_sesiones_anteriores(sender, user, request, **kwargs): # Eliminar sessiones anteriores Session.objects.filter(usersession__user=user).delete() # guardar la nueva sesión request.session.save() # Crear el vínculo entre la sesión y el usuario, para poder eliminarlos cuando se vuelva a ejecutar esta señal UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key)) user_logged_in.connect(eliminar_sesiones_anteriores) # ---------------------------------------------
def get_last_login_ip(sender, user, request, **kwargs): """ 更新用户最后一次登陆的IP地址 """ ip = get_client_ip_from_request(request) if ip: if RecordIP.objects.filter(last_login_ip=ip, user=user).exists(): record_id = RecordIP.objects.filter(last_login_ip=ip, user=user).first() record_id.user = user record_id.save() else: RecordIP.objects.create(last_login_ip=ip, user=user) user_logged_in.connect(get_last_login_ip) class EmailVerifyRecord(models.Model): """ 邮箱验证表 """ REGISTER = 'register' FORGET = 'forget' UPDATE = 'update' SEND_TYPE_CHOICES = ( (REGISTER, u'注册'), (FORGET, u'找回密码'), (UPDATE, u'修改邮箱'), ) code = models.CharField(verbose_name=u'验证码', max_length=20)
def my_callback0(sender, **kwargs): print("Request finished!+++++") def my_callback1(sender, **kwargs): print("Request Started!+++++") from django.core.signals import request_finished, request_started request_finished.connect(my_callback0) request_started.connect(my_callback1) from django.contrib.auth import user_logged_in user_logged_in.connect(my_callback) ############################################################################### from django import forms class ExamDocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') def list(request): # Handle file upload if request.method == 'POST': form = ExamDocumentForm(request.POST, request.FILES) if form.is_valid():
@classmethod def user_logged_in(cls, sender, request, user, **kwargs): application = getattr(request, 'client', None) if not application: return if user.username in cls.ignored_usernames: return cls.objects.create(user=user, application=application) def __str__(self): return '%s logged into %s' % (self.user.username, self.application.name) user_logged_in.connect(Login.user_logged_in) class FailedLoginAttemptManager(models.Manager): def is_locked_out(self, user, client=None): failed_attempts = self.get_queryset().filter(user=user) if client: failed_attempts = failed_attempts.filter(application=client) failed_attempt_count = failed_attempts.count() if not failed_attempt_count: return False if failed_attempt_count >= settings.MTP_AUTH_LOCKOUT_COUNT: last_failed_attempt = failed_attempts.first() lockout_cutoff = now() - datetime.timedelta( seconds=settings.MTP_AUTH_LOCKOUT_LOCKOUT_PERIOD)
} @classmethod def user_logged_in(cls, sender, request, user, **kwargs): application = getattr(request, 'client', None) if not application: return if user.username in cls.ignored_usernames: return cls.objects.create(user=user, application=application) def __str__(self): return '%s logged into %s' % (self.user.username, self.application.name) user_logged_in.connect(Login.user_logged_in) class FailedLoginAttemptManager(models.Manager): def is_locked_out(self, user, client=None): failed_attempts = self.get_queryset().filter(user=user) if client: failed_attempts = failed_attempts.filter(application=client) failed_attempt_count = failed_attempts.count() if not failed_attempt_count: return False if failed_attempt_count >= settings.MTP_AUTH_LOCKOUT_COUNT: last_failed_attempt = failed_attempts.first() lockout_cutoff = now() - datetime.timedelta( seconds=settings.MTP_AUTH_LOCKOUT_LOCKOUT_PERIOD
def merge_carts(sender, user, request, **kwargs): try: session_cart = Cart.objects.get(session=request.session.session_key) user_cart = Cart.objects.get_or_create(user=user)[0] if user_cart.id != session_cart.id: for item in session_cart.items.all(): item.cart = user_cart item.save() session_cart.delete() user_cart.session = request.session.session_key user_cart.save() except Cart.DoesNotExist: pass user_logged_in.connect(merge_carts) def cart_changed_listener(sender, instance, **kwargs): if not settings.CART_CHANGED_EMAIL_SEND_AFTER and\ instance.user is not None: return for time in settings.CART_CHANGED_EMAIL_SEND_AFTER.split(','): pending_tasks = task_manager.get_pending_tasks( 'checkout.jobs.forgotten_cart_send_email_job') email_jobs_exists = False for task_id in pending_tasks: task = task_manager.get_task_instance(task_id) if task.kwargs.get('run_after') == time: email_jobs_exists = True break
import logging import json from django.contrib.auth import user_logged_in from django.http import QueryDict from rest_framework import status logger = logging.getLogger("project") def listener_logged_in(sender, user=None, **kwargs): VMSRequest.user_id = user.id user_logged_in.connect(listener_logged_in) class VMSRequest(object): ENV_HEADERS = ('X-Varnish', 'X-Request-Start', 'X-Heroku-Queue-Depth', 'X-Real-Ip', 'X-Forwarded-Proto', 'X-Forwarded-Protocol', 'X-Forwarded-Ssl', 'X-Heroku-Queue-Wait-Time', 'X-Forwarded-For', 'X-Heroku-Dynos-In-Use', 'X-Forwarded-For', 'X-Forwarded-Protocol', 'X-Forwarded-Port', 'Runscope-Service') enable_activity_log = True user_id = None request = None url = None view = None response = None
user_settings = user.settings except (AttributeError, ObjectDoesNotExist): return try: tz = user_settings.tz except AttributeError: return if tz: request.session['django_timezone'] = force_text(tz) timezone.activate(tz) user_logged_in.connect( set_user_timezone_on_login, dispatch_uid='aldryn_accounts:set_user_timezone_on_login') def set_username_if_not_exists(sender, **kwargs): user = kwargs.get('instance') if isinstance(user, User): if not user.username: user.username = generate_username() signals.pre_save.connect(set_username_if_not_exists, dispatch_uid='aldryn_accounts:generate_username') # TODO: figure this out. actually we'd need to redirect to a url with the language prefix. # def set_user_preferred_language_on_login(sender, user, request, **kwargs):
from django.contrib.auth import user_logged_in from commerce.models.user import UserSession def user_logged_in_handler(sender, user, request, **kwargs): session, created = UserSession.objects.get_or_create( user=user, session_id=request.session.session_key, ) old_sessions = UserSession.objects.select_related('session').filter( user__phone_number=user.phone_number, user__deleted_at__isnull=True).exclude(id=session.id, ) for row in old_sessions: if hasattr(row, 'session') and row.session: row.session.delete() row.delete() user_logged_in.connect(user_logged_in_handler)
from django.db import models from django.contrib.auth import user_logged_in, user_logged_out from actstream import action def user_action_in(sender, user, request, **kwargs): action.send(user, verb=u'log in') user_logged_in.connect(user_action_in) def user_action_out(sender, user, request, **kwargs): action.send(user, verb=u'log out') user_logged_out.connect(user_action_out) # #sample # def post_save_action(sender, **kwargs): # action.send(kwargs['instance'], verb=u'a user created') # post_save.connect(post_save_action, sender=User) class Player(models.Model): state = models.IntegerField(default=0) def __unicode__(self): return '#%d' % self.pk