def test_zinnia_entry_detail_login_password(self): user_logged_in.disconnect(update_last_login) setup_test_template_loader( {'zinnia/entry_detail.html': '', 'zinnia/login.html': '', 'zinnia/password.html': ''}) entry = self.create_published_entry() entry.password = '******' entry.login_required = True entry.save() with self.assertNumQueries(4): response = self.client.get('/2010/01/01/my-test-entry/') self.assertTemplateUsed(response, 'zinnia/login.html') with self.assertNumQueries(9): response = self.client.post('/2010/01/01/my-test-entry/', {'username': '******', 'password': '******'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/password.html') self.assertEquals(response.context['error'], False) with self.assertNumQueries(6): response = self.client.post('/2010/01/01/my-test-entry/', {'entry_password': '******'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/entry_detail.html') restore_template_loaders() user_logged_in.connect(update_last_login)
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
def test_zinnia_entry_detail_login_password(self): user_logged_in.disconnect(update_last_login) self.inhibit_templates('zinnia/entry_detail.html', 'zinnia/login.html', 'zinnia/password.html') entry = self.create_published_entry() entry.password = '******' entry.login_required = True entry.save() with self.assertNumQueries(1): response = self.client.get(entry.get_absolute_url()) self.assertTemplateUsed(response, 'zinnia/login.html') with self.assertNumQueries(12): response = self.client.post(entry.get_absolute_url(), {'username': '******', 'password': '******'}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/password.html') self.assertEqual(response.context['error'], False) with self.assertNumQueries(7): response = self.client.post(entry.get_absolute_url(), {'entry_password': '******'}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'zinnia/entry_detail.html') user_logged_in.connect(update_last_login)
def login_user(request, hijacked): ''' hijack mechanism ''' hijacker = request.user hijack_history = [request.user._meta.pk.value_to_string(hijacker)] if request.session.get('hijack_history'): hijack_history = request.session['hijack_history'] + hijack_history check_hijack_authorization(request, hijacked) backend = get_used_backend(request) hijacked.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) # Prevent update of hijacked user last_login signal_was_connected = user_logged_in.disconnect(update_last_login) # Actually log user in login(request, hijacked) # Restore signal if needed if signal_was_connected: user_logged_in.connect(update_last_login) post_superuser_login.send(sender=None, user_id=hijacked.pk) # Send legacy signal hijack_started.send(sender=None, hijacker_id=hijacker.pk, hijacked_id=hijacked.pk, request=request) # Send official, documented signal request.session['hijack_history'] = hijack_history request.session['is_hijacked_user'] = True request.session['display_hijack_warning'] = True request.session.modified = True return redirect_to_next(request, default_url=hijack_settings.HIJACK_LOGIN_REDIRECT_URL)
def setUp(self): self.client = Client(enforce_csrf_checks=True) self.client.get('/') # To get the CSRF token for next request assert django_settings.CSRF_COOKIE_NAME in self.client.cookies self.target_user = User.objects.create(username='******') # setup listener user_logged_in.connect(update_last_login)
def test_logged_in(self): signal_user = set() def login_signal_handler(sender, request, user, **kwargs): signal_user.add(user) user_logged_in.connect(login_signal_handler) u = self.b.register(self.req, email='*****@*****.**') self.assertIn(u, signal_user)
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 user_logged_in_handler(sender, request, user, **kwargs): UserSession.objects.get_or_create(user = user, session_id = request.session.session_key) user_logged_in.connect(user_logged_in_handler) # session = Session.objects.get(session_key=session_key) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) lock = System_status.objects.all()[:1].get() if lock.status : return render(request,'blog/locked.html') return HttpResponse(user)
def test_login_with_user(self): """Login should send user_logged_in signal on successful login.""" def listener(*args, **kwargs): listener.executed = True listener.executed = False user_logged_in.connect(listener) self.client.login(username='******', password='******') user_logged_out.disconnect(listener) self.assertTrue(listener.executed)
def test_login_without_signal(self): """Login shouldn't send signal if user wasn't logged in""" def listener(*args, **kwargs): listener.executed = True listener.executed = False user_logged_in.connect(listener) self.client.login(username='******', password='******') user_logged_in.disconnect(listener) self.assertFalse(listener.executed)
def capture_users_metrics(statsd_client): gauge_user_count() gauge_active_users() if not getattr(User, '__metrics_registered', False): post_delete.connect(sender=User, receiver=user_deleted) post_save.connect(sender=User, receiver=user_created) user_logged_in.connect(receiver=logged_in) user_logged_out.connect(receiver=logged_out) User.__metrics_registered = True
def test_last_seen(self): self.editor.last_seen = None self.editor.save() self.client.cookies.clear() # login sends dud request without REQUEST dict user_logged_in.disconnect(views.set_session_expiry) self.client.login(username="******", password="******") user_logged_in.connect(views.set_session_expiry) self.client.get("/") last_seen = Member.objects.get(pk=self.editor.pk).last_seen self.assertTrue(last_seen) self.client.get("/") self.assertEqual(Member.objects.get(pk=self.editor.pk).last_seen, last_seen)
def no_update_last_login(): """ Disconnect any signals to update_last_login() for the scope of the context manager, then restore. """ kw = {'receiver': update_last_login} kw_id = {'receiver': update_last_login, 'dispatch_uid': 'update_last_login'} was_connected = user_logged_in.disconnect(**kw) was_connected_id = not was_connected and user_logged_in.disconnect(**kw_id) yield # Restore signal if needed if was_connected: user_logged_in.connect(**kw) elif was_connected_id: user_logged_in.connect(**kw_id)
def test_login(self): # stuff for detecting if the user got authenticated from django.contrib.auth.signals import user_logged_in u = User.objects.get(pk=1) u.passed = False def logged_in(sender, user, **kwargs): if user.id == u.id: u.passed = True user_logged_in.connect(logged_in) # The test procedure self.login() time.sleep(2) # Check the results self.assertTrue(u.passed, "The user should be logged in after we finish the login test!")
def test_post_should_not_login_when_wrong_credentials(self): user = create_user() data = { 'username': '******', 'password': '******', 'client': 'my-device', } 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) with self.assertRaises(models.Token.DoesNotExist): user.auth_tokens.get() self.assertFalse(self.signal_sent)
def test_post_should_login_user(self): user = create_user() data = { 'username': user.username, 'password': user.raw_password, 'client': 'my-device', } 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) token = user.auth_tokens.get() self.assertEqual(response.data['auth_token'], token.key) self.assertEqual(data['client'], token.client) self.assertTrue(self.signal_sent)
def ready(self): from django.contrib.auth.models import update_last_login as django_update_last_login user_logged_in.disconnect(django_update_last_login) from .signals.receivers import update_last_login user_logged_in.connect(update_last_login) from django.contrib.auth.models import User from .signals.receivers import on_user_updated pre_save.connect(on_user_updated, sender=User) # The django-simple-history model on CourseEnrollment creates performance # problems in testing, we mock it here so that the mock impacts all tests. if os.environ.get('DISABLE_COURSEENROLLMENT_HISTORY', False): import student.models as student_models from mock import MagicMock student_models.CourseEnrollment.history = MagicMock()
def test_logout_user(self): user_logged_in.connect(self.record_user_logged_in) user_logged_out.connect(self.record_user_logged_out) user, _ = do_authenticate() new_user = User(username='******') new_user.backend = 'django.contrib.auth.backends.ModelBackend' new_user.save() request = RequestFactory().get('/') request.session = Client().session login(request, new_user) user2, _ = do_authenticate(new_user) self.assertIsNotNone(user, 'Processed user should not have been None.') self.assertEqual(user, user2, 'No new user should have been created.') self.assertNotEqual(self.logged_in_user, new_user, 'Second user should have been logged out.') self.assertEqual(self.logged_out_user, new_user, 'Second user should have been logged out.') self.assertEqual(self.logged_in_user, user, 'First user should have been logged out.') self.assertNotEqual(self.logged_out_user, user, 'First user should have been logged out.')
def login_as(user, request, store_original_user=True): """ Utility function for forcing a login as specific user -- be careful about calling this carelessly :) """ # Save the original user pk before it is replaced in the login method original_user_pk = request.user.pk # Find a suitable backend. if not hasattr(user, 'backend'): for backend in django_settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break # Log the user in. if hasattr(user, 'backend'): signal_was_connected = False if not la_settings.UPDATE_LAST_LOGIN: # Prevent update of user last_login signal_was_connected = user_logged_in.disconnect(update_last_login) try: # Actually log user in login(request, user) finally: # Restore signal if needed if signal_was_connected: user_logged_in.connect(update_last_login) else: return # Set a flag on the session if store_original_user: messages.warning(request, la_settings.MESSAGE_LOGIN_SWITCH.format(username=user.__dict__[username_field]), extra_tags=la_settings.MESSAGE_EXTRA_TAGS) request.session[la_settings.USER_SESSION_FLAG] = signer.sign(original_user_pk)
def test_zinnia_entry_detail_login_password(self): user_logged_in.disconnect(update_last_login) setup_test_template_loader( {"zinnia/entry_detail.html": "", "zinnia/login.html": "", "zinnia/password.html": ""} ) entry = self.create_published_entry() entry.password = "******" entry.login_required = True entry.save() with self.assertNumQueries(4): response = self.client.get("/2010/01/01/my-test-entry/") self.assertTemplateUsed(response, "zinnia/login.html") with self.assertNumQueries(9): response = self.client.post("/2010/01/01/my-test-entry/", {"username": "******", "password": "******"}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "zinnia/password.html") self.assertEquals(response.context["error"], False) with self.assertNumQueries(6): response = self.client.post("/2010/01/01/my-test-entry/", {"entry_password": "******"}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "zinnia/entry_detail.html") restore_template_loaders() user_logged_in.connect(update_last_login)
'''When user logged in then check user membership status and perform action accordig to it''' membership = user.membership if user.on_free_trial: #membership end date has passed if membership.end_date < timezone.now(): user.on_free_trial = False #update the membership membership.type = 'N' elif user.is_member: sub = stripe.Subscription.retrieve(membership.stripe_subscription_id) if sub.status == 'active': membership.end_date = datetime.datetime.fromtimestamp( sub.current_period_end ) #already true but again set it true if in some case it becomes false user.is_member = True else: user.is_member = False #update the membership membership.type = 'N' else: pass user.save() membership.save() #link this receiver to the post_save_signal post_save.connect(post_save_user_receiver, sender=User) user_logged_in.connect(user_logged_in_receiver)
def user_login_time(request, **kwargs): x = datetime.now() try: user = UserLoginLogout.objects.get(USER = request.user, DATE = x.date()) except: user = UserLoginLogout.objects.create(USER = request.user, DATE = x.date(), LOGIN = x.time()) return user def user_location_view(request): x = datetime.now() if request.is_ajax(): queryDict = request.GET data = dict(queryDict) latitude = float(data['latitude'][0]) longitude = float(data['longitude'][0]) user_location = UserLocation.objects.create(USER = request.user, DATE = x.date(), LATITUDE = latitude,\ LONGITUDE = longitude) return HttpResponse(content_type='json') def user_logout_time(request, **kwargs): x = datetime.now() user = UserLoginLogout.objects.get(USER = request.user, DATE = x.date()) user.LOGOUT = x.time() user.save() return user user_logged_in.connect(user_login_time) user_logged_out.connect(user_logout_time)
from_email='*****@*****.**', to_emails=reset_password_token.user.email, ) message.dynamic_template_data = { 'subject': 'Usamodzielnieni: resetowanie hasła', 'name': reset_password_token.user.first_name, 'part1': part1, 'part2': reset_url, 'part3': part2 } send_mail_via_sendgrid(message) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def commit_date_joined(sender, instance, created, **kwargs): if created: instance.date_joined = timezone.now() def commit_last_login(sender, user, request, **kwargs): user.last_login = timezone.now() user_logged_in.connect(commit_last_login) @receiver(pre_delete, sender=Account) def delete_category_header(sender, instance, using, **kwargs): instance.delete_image_if_exists()
def on_post_save_for_user(sender, **kwargs): if kwargs['created']: user = kwargs['instance'] # 환영 이메일 보내기 send_mail( '가입 환영 메일 제목.', '가입 환영 메일 내용', '*****@*****.**', [user.email], fail_silently=False, ) post_save.connect(on_post_save_for_user, sender=settings.AUTH_USER_MODEL) class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False) session_key = models.CharField(max_length=40, editable=False) created_at = models.DateTimeField(auto_now_add=True) def on_user_logged_in(sender, request, user, **kwargs): user.is_user_logged_in = True user_logged_in.connect(on_user_logged_in)
from tastypie.models import ApiKey from trees.models import Tree, Image from django.contrib.auth.signals import user_logged_in from django.http import HttpResponse from tastypie.exceptions import ImmediateHttpResponse from tastypie import http import pdb def generate_api_key(sender, user, request, **kwargs): ApiKey.objects.get_or_create(user=user)[0].save() user_logged_in.connect(generate_api_key) class UnauthenticatedGetAllowedAuthentication(ApiKeyAuthentication): """ Allows GET requests read-only access """ def is_authenticated(self, request, **kwargs): if request.method == 'GET': return True return super(UnauthenicatedGetAllowedAuthentication, self).is_authenticated(request, kwargs) class CORSResource(object): """
""" sets a new one if it doesn't exist """ except UserStripe.DoesNotExist : customer=stripe.Customer.create( name=user.username, #email=user.email ) new_user_stripe=UserStripe.objects.create( #the customer json response is where we got the id user=user, stripe_id=customer.id ) except: pass user_logged_in.connect(get_or_create_stripe) """ make customers default address""" class UserDefaultAddress(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE) shipping_address=models.ForeignKey("UserAddress", null=True,on_delete=models.CASCADE, related_name='user_default_shipping_address') billing_address=models.ForeignKey("UserAddress", null=True,on_delete=models.CASCADE, related_name='user_default_billing_address') def __str__(self): return self.user.username
def is_owner(self, instance): if self.user in instance.users: return True else: for group in self.user.groups.all(): if group in instance.groups: return True return False def __str__(self): return "%s profile" % self.user # Signals def create_user_profile(sender, instance, created, **kwargs): if created and not kwargs.get('raw', False): UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User, dispatch_uid='create_UserProfile') def update_session_last_login(sender, user, request, **kwargs): if request: request.session['LAST_LOGIN_DATE'] = datetime.datetime.now() user_logged_in.connect(update_session_last_login)
from registration.signals import user_activated @receiver(user_activated) def create_user_profile(sender, user, request, **kwargs): user_profile = UserProfile.objects.create(user=user) from guardian.shortcuts import assign_perm assign_perm('change_userprofile', user, user_profile) assign_perm('delete_userprofile', user, user_profile) assign_perm('change_user', user, user) def check_userprofile_details(sender, request, user, **kwargs): if not user.first_name: request.session['no_name'] = True topic_list = TopicFollow.objects.filter(user=user) if not topic_list: request.session['no_topic'] = True def create_project_permission(sender, instance, created, **kwargs): if created: assign_perm('change_project', instance.user, instance) assign_perm('delete_project', instance.user, instance) def create_snippet_permission(sender, instance, created, **kwargs): if created: assign_perm('change_snippet', instance.user, instance) assign_perm('delete_snippet', instance.user, instance) user_logged_in.connect(check_userprofile_details) post_save.connect(create_snippet_permission, sender=Snippet) post_save.connect(create_project_permission, sender=Project)
dispatch_uid="create_team_and_keys_for_project", weak=False, ) post_save.connect( create_team_member_for_owner, sender=Team, dispatch_uid="create_team_member_for_owner", weak=False, ) post_save.connect( update_document, sender=Group, dispatch_uid="update_document", weak=False, ) post_save.connect( create_key_for_team_member, sender=TeamMember, dispatch_uid="create_key_for_team_member", weak=False, ) pre_delete.connect( remove_key_for_team_member, sender=TeamMember, dispatch_uid="remove_key_for_team_member", weak=False, ) user_logged_in.connect(set_language_on_logon) add_introspection_rules([], ["^social_auth\.fields\.JSONField"])
if (user is not None) and (device is not None) and (device.user_id == user.pk): request.session[DEVICE_ID_SESSION_KEY] = device.persistent_id request.user.otp_device = device def _handle_auth_login(sender, request, user, **kwargs): """ Automatically persists an OTP device that was set by an OTP-aware AuthenticationForm. """ if hasattr(user, 'otp_device'): login(request, user.otp_device) user_logged_in.connect(_handle_auth_login) def verify_token(user, device_id, token): """ Attempts to verify a :term:`token` against a specific device, identified by :attr:`~django_otp.models.Device.persistent_id`. This wraps the verification process in a transaction to ensure that things like throttling polices are properly enforced. :param user: The user supplying the token. :type user: :class:`~django.contrib.auth.models.User` :param str device_id: A device's persistent_id value.
class Meta: verbose_name = 'IpAddress' verbose_name_plural = 'IpAddresses' ##SAVE IP-ADDRESS FOR SIGN IN USER def save_login_user_ip_address(sender, user, request, **kwargs): try: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') if ipaddress: activity_name = 'Sign-in' customer_user = Customer.objects.get(user=user) ip_add = IpAddress() ip_add.customer = customer_user ip_add.ip_address = ipaddress ip_add.comments = "saved sign-in user %s IP-Address" % user.username ip_add.activity = activity_name ip_add.save() except: pass user_logged_in.connect(save_login_user_ip_address)
from django.contrib.auth.signals import user_logged_in def test(sender, user, request, **kwargs): print 'in test' request.session['test'] = 'Tested OK' print 'outsde test' user_logged_in.connect(test)
login(request, user) return redirect('dashboard') else: return render(request, 'account_activation_invalid.html') log = logging.getLogger(__name__) @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') log.info('login user: {user} via ip: {ip}'.format(user=user, ip=ip)) user_logged_in.connect(user_logged_in_callback) @receiver(user_logged_out) def user_logged_out_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') log.info('logout user: {user} via ip: {ip}'.format(user=user, ip=ip)) user_logged_out.connect(user_logged_out_callback) @receiver(user_login_failed) def user_login_failed_callback(sender, request, credentials, **kwargs): log.warning(
date=timezone.now().date()) daily_ledger.login_count += 1 daily_ledger.save() if profile.last_login.date() != timezone.now().date(): daily_ledger.dau += 1 daily_ledger.save() profile.last_login = timezone.now() profile.save() if profile.userkey == '0': profile.userkey_gen() user_logged_in.connect(updateLastLogin) def stats(request): ''' This view extracts all the app data for viewing. ''' context = dict() context['user_count'] = len(User.objects.all()) context['todays_uploads_count'] = 0 context['todays_file_count'] = 0 context['todays_s_count'] = 0 context['todays_u_count'] = 0 context['dau'] = 0
from django.db.models.manager import EmptyManager from django.utils import six, timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ 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) class PermissionManager(models.Manager): use_in_migrations = True def get_by_natural_key(self, codename, app_label, model): return self.get( codename=codename, content_type=ContentType.objects.db_manager( self.db).get_by_natural_key(app_label, model), ) @python_2_unicode_compatible class Permission(models.Model):
# after each loogin it will look for a match and create one def login_user_mataches(sender, user, request, **kwargs): obj = Match.objects.filter(from_user=user) for abc in obj: if abc.to_user != user: if Match.objects.good_match(abc.to_user, user): add_to_list, created = MatchList.objects.get_or_create(user=user, match=abc.to_user) obj2 = Match.objects.filter(to_user=user) for abc in obj2: if abc.from_user != user: if Match.objects.good_match(abc.from_user, user): add_to_list, created = MatchList.objects.get_or_create(user=user, match=abc.from_user) request.session["new_matches_count"] = MatchList.objects.filter(user=user).filter(read=False).count() user_logged_in.connect(login_user_mataches) class MatchManager(models.Manager): # here the ordere for user it doesn't matter def are_matched(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count()>0: obj = Match.objects.get(from_user=user1, to_user=user2) perc = obj.percent * 100 return perc if self.filter(from_user=user2, to_user=user1).count()>0: obj = Match.objects.get(from_user=user2, to_user=user1) perc = obj.percent * 100 return perc else: return False
def deprecated(message): """ Mark function as deprecated. >>> @deprecated("thenineties is deprecated") ... def thenineties(): ... print 'hi' """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.warn(message, DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return wrapper return decorator def block_if_not_staff(sender, user, request, **kwargs): staff_only_login = BoolSetting.get('setting-staff-only-login').get_value() if staff_only_login and not user.is_staff: messages.error(request, _('Only staff members can log in')) logout(request) if not 'test' in sys.argv: user_logged_in.connect(block_if_not_staff)
logger = logging.getLogger(__name__) def user_logged_in_handler(sender, request, user, **kwargs): """ in authenticate method, the request is not available so, the session engine is either not available. By using this signal binding, we can get the special attributes added to the object by the authenticate method and save them in the current session """ if 'dn' in user.__dict__ and user.dn is not None: request.session['LDAP_USER_DN'] = user.dn if 'bu' in user.__dict__ and user.bu is not None: request.session['LDAP_USER_BU'] = user.bu user_logged_in.connect(user_logged_in_handler) def create_password(): # generate password chars = string.ascii_letters + string.digits + '!@#$%&*' random.seed = (os.urandom(1024)) families = 0 passwd = '' while families < 3: passwd = ''.join(random.choice(chars) for i in range(10)) lowercase = [c for c in passwd if c.islower()] uppercase = [c for c in passwd if c.isupper()] digits = [c for c in passwd if c.isdigit()] ponctuation = [c for c in passwd if not c.isalnum()]
form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def makeNewMember(sender,user,request,**kwargs): messages.add_message(request,messages.INFO, "Successful login!") print("A user has logged in, checking if they have a member") q = Member.objects.filter(user=user) if len(q) > 0: print("profile exists") else: print("making a new member profile ") z = Member(user=user,permission=0) z.save() # yep user_logged_in.connect(makeNewMember) # this checks if you have a member account every time a user logs in def allo(user): z = Member.objects.filter(user=user) print(z) if int(z[0].permission) == 1: print("successful allo test") return True return False @login_required def me(request): m = Member.objects.filter(user=request.user) return render(request,"userPage.html",{"member":m[0]}) @login_required
url, params = apiclient.normalize_url(course_api) apiclient.update_params(params) course_obj = apiclient.load_data(url) course = Course.objects.get_new_or_updated(course_obj, namespace=site) # add course membership for permissions user.courses.add(course) # Redirect to notresponded page after login oauth.redirect_url = reverse('feedback:notresponded-course', kwargs={'course_id': course.id}) # List LTI params in debug log logger.debug("LTI login for user %s on course %s", user, course) for k, v in sorted(oauth.params): logger.debug(" \w param -- %s: %s", k, v) if request and user: # add courses to users session courses = list(user.courses.all()) request.session[SITES_SESSION_KEY] = [ course.namespace_id for course in courses ] request.session[COURSES_SESSION_KEY] = [ course.id for course in courses ] user_logged_in.connect(add_course_permissions)
def update_profile_weight(sender=None, user=None, request=None, **kwargs): """ # mugshot = 100 # biography = 50 # email = 25 """ # TODO: add the year of the last sign on to the weight weight = 0 # mugshot if user.profile.mugshot: weight = weight + 100 # biography if user.profile.profile_type == 'm': if user.profile.artist_profile.biography: weight = weight + 50 elif user.profile.profile_type == 'v': if user.profile.venueProfile.biography: weight = weight + 50 # email if user.email: weight = weight + 25 user.profile.weight = weight user.profile.save() user_logged_in.connect(update_profile_weight) def update_profiles(): """ update the weight of all profiles """ for profile in Profile.objects.all(): update_profile_weight(user=profile.user)
def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin def user_logged_in_signal(sender, signal, request, user, **kwargs): request.session.set_expiry(28800) #expire session in 8 hrs membership_obj, created = Membership.objects.get_or_create(user=user) if created: membership_obj.save() else: user.membership.update_status() user_logged_in.connect(user_logged_in_signal) class UserProfile(models.Model): user = models.OneToOneField(MyUser) bio = models.TextField(null=True, blank=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) facebook = models.CharField(max_length=320, null=True, blank=True, verbose_name='Facebook profile URL') twitter = models.CharField(max_length=320, null=True, blank=True,
cart = None try: old_cart = Cart.objects.get(user=user) new_cart = Cart.objects.get(id=cart_id) # We check if there was an old cart. # If there is, we iterate through the items in the cart to know if the user has added a clone of an old item in the new cart if old_cart: for item in new_cart.items.all(): if old_cart.items.all( ).filter(item__slug=item.item.slug).exists( ): # If the item exists, we delete that item from the new cart else we add it to the old cart. item.delete() else: item.user_id = user.id item.save() old_cart.items.add(item) cart = old_cart new_cart.delete( ) # we delete the cart that was created with session after adding new items to user's cart else: new_cart.user_id = user.id new_cart.save() cart = new_cart except Cart.DoesNotExist: cart = Cart.objects.get(id=cart_id) cart.user_id = user.id cart.save() user_logged_in.connect(attach_cart)
# Anything that relies on default objects that may not exist with default # fields should be wrapped in handle_db_failure post_syncdb.connect( handle_db_failure(create_default_projects), dispatch_uid="create_default_project", weak=False, ) post_save.connect( handle_db_failure(create_keys_for_project), sender=Project, dispatch_uid="create_keys_for_project", weak=False, ) post_save.connect( handle_db_failure(create_org_member_for_owner), sender=Organization, dispatch_uid="create_org_member_for_owner", weak=False, ) user_logged_in.connect( set_language_on_logon, dispatch_uid="set_language_on_logon", weak=False ) post_save.connect( on_alert_creation, sender=Alert, dispatch_uid="on_alert_creation", weak=False, )
if maintenance_response: return maintenance_response def _get_maintenance_response(self, request, view_func): if settings.DEBUG: # Allow media and static accesses in debug mode if request.path.startswith("/media") or request.path.startswith( "/static"): return None if getattr(view_func, "maintenance_mode_exempt", False): return None if "login" in view_func.__name__: return None resolver_match = getattr(request, "resolver_match", None) if resolver_match and resolver_match.app_name == "shuup_admin": return None if request.shop.maintenance_mode and not is_admin_user(request): return HttpResponse(loader.render_to_string( "shuup/front/maintenance.jinja", request=request), status=503) if ("django.contrib.auth" in settings.INSTALLED_APPS and "shuup.front.middleware.ShuupFrontMiddleware" in settings.MIDDLEWARE_CLASSES): user_logged_in.connect(ShuupFrontMiddleware.refresh_on_user_change, dispatch_uid="shuup_front_refresh_on_login") user_logged_out.connect(ShuupFrontMiddleware.refresh_on_logout, dispatch_uid="shuup_front_refresh_on_logout")
__all__ = ( 'AbstractBaseUser', 'BaseUser', 'AbstractAnonymousUser', 'AnonymousUser', ) 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() user_logged_in.connect(update_last_login) class UserManager(models.Manager): def create_user(self, username, email=None, password=None): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() # Normalize the address by lowercasing the domain part of the email # address. email = email or '' try: email_name, domain_part = email.strip().split('@', 1) except ValueError:
event.description = description event.user = request.user.username event.event_type = event_type event.save() def set_status_online(sender, user, request, **kwargs): new_event(description='User logging in', request=request, event_type='access') def redirect(request): if request.method == 'GET': url_to_redirect = request.GET['next_url'] print(url_to_redirect) new_event('Redirecting to %s' % url_to_redirect, request, 'redirect') return HttpResponseRedirect(url_to_redirect) @login_required() @permission_required('is_superuser') def events(request): event_objects = models.Event.objects.all().order_by('-timestamp') return render(request, "app_160/events.html", context={"events": event_objects}) user_logged_in.connect(set_status_online)
LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale, ) def set_language_session(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ kwargs['request'].session['_language'] = user.lang_code user_logged_in.connect(set_language_session) @login_required def set_lang(request): next = request.META.get('HTTP_REFERER', None) if not next: next = '/' response = HttpResponseRedirect(next) lang_code = request.POST.get('language_code', None) if not lang_code: lang_code = request.LANGUAGE_CODE if not lang_code or lang_code not in ('en', 'zh-cn'): lang_code = settings.LANGUAGE_CODE if lang_code and check_for_language(lang_code): if hasattr(request, 'session'):
if len(UserProfile.objects.filter(user=user)) == 0: UserProfile.objects.create(user=user, bio='') class SongComment(models.Model): song = models.ForeignKey(Song) author = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) text = models.TextField() markdown = MarkdownField(text) history = HistoricalRecords() def __unicode__(self): return self.author.username + " - " + self.song.name class Meta: ordering = ['-created'] from django.contrib.auth.signals import user_logged_in, user_logged_out def logged_in(sender, user, request, **kwargs): logger.info('User %d (%s) logged in' % (user.id, user.username)) def logged_out(sender, user, request, **kwargs): if user is not None: logger.info('User %d (%s) logged out' % (user.id, user.username)) user_logged_in.connect(logged_in) user_logged_out.connect(logged_out)
extra_context = {'logged_out': True} template_name = "nt_training/index.html" # Already have login_required inherently class NTUserEdit(auth_views.PasswordChangeView): template_name = "nt_training/user-edit.html" def get_success_url(self): return reverse_lazy('nt_training:ntUserEditDone') class NTUserEditDone(auth_views.PasswordChangeDoneView): template_name = "nt_training/user-edit-done.html" # Flash Messages def logged_in_message(sender, user, request, **kwargs): # Add a welcome message when the user logs in messages.success(request, "Login successful!") def logged_out_message(sender, user, request, **kwargs): # Add a welcome message when the user logs in messages.info(request, "You have logged out.") user_logged_in.connect(logged_in_message) user_logged_out.connect(logged_out_message)
) if language and hasattr(request, 'session'): request.session['django_language'] = language def safe_update_last_login(sender, user, **kwargs): """ Identical to Django's built-in handler except that we gracefully handle database failures. tl;dr logging in should not fail when a db is read-only """ try: update_last_login(sender, user, **kwargs) except DatabaseError as exc: logging.warn(six.text_type(exc), exc_info=True) user_logged_in.disconnect(update_last_login) user_logged_in.connect( safe_update_last_login, dispatch_uid="safe_update_last_login", weak=False, ) user_logged_in.connect( set_language_on_logon, dispatch_uid="set_language_on_logon", weak=False )
# ----------------------------------------------------------------------------- # Signal handlers # ----------------------------------------------------------------------------- # Connected to user_logged_in def create_session(sender, request, user, **kwargs): Session.objects.create_session(request, user) # Connected to user_logged_out def deactivate_session(sender, request, user, **kwargs): try: key = request.session.session_key instance = Session.objects.get(user=user, session_key=key) instance.active = False instance.save() except Session.DoesNotExist: pass # Connected to post_delete for Session model def post_delete_session(sender, instance, **kwargs): instance.delete_store_session() user_logged_in.connect(create_session) user_logged_out.connect(deactivate_session) post_delete.connect(post_delete_session, sender=Session)
def post_event(event_cls, request, user): payload = make_event_payload(user) if not payload: return metadata = EventMetadata(event_cls.event_type, request=make_event_metadata_request(request), tags=event_cls.tags) 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,
# Signal Observe # def logged_in_handle(sender, user, request, **kwargs): # # Check if TU login prov = user.social_auth.filter(provider='tu') if prov.exists(): data = prov[0].extra_data headers = {"Authorization": "Bearer {}".format(data['access_token'])} res = requests.get('https://api.tu.ac.th/api/me/', headers=headers).json() refs = RefereeMapping.objects.filter(natid=res['description']) if refs.exists(): ref = refs[0] ref.user = user ref.save() is_sci = False if res['company'] == 'คณะวิทยาศาสตร์และเทคโนโลยี': is_sci = True elif res['username'].isdigit() and res['username'][2:4] == '09': is_sci = True user.is_sci_member = is_sci if res['role']: user.role = res['role'] user.save() user_logged_in.connect(logged_in_handle)
user_referrer = User.objects.get(id=request.session.get('ur')) except: user_referrer = None del request.session['ur'] source_referrer = request.session.get('sr') if source_referrer: del request.session['sr'] profile = Profile(user=user,) if user_referrer: profile.user_referrer = user_referrer if source_referrer: profile.source_referrer = source_referrer profile.save() if not profile.hex_digi: m = hashlib.md5(datetime.datetime.utcnow().isoformat() + profile.user.username) profile.hex_digi = m.hexdigest() profile.save() if not profile.social_data_completed: profile.social_data_process() if not profile.email_opt_in_sent and user.email: profile.send_opt_in_email() profile.email_opt_in_sent = True profile.save() user_logged_in.connect(user_signed_in)
try: cont_objs = Container.objects.filter(user__exact=user) if len(cont_objs) == 0: print('No containers assigned to user.') for cont in cont_objs: removeContainer(cont) scaleAllChallenges() except: print('Container does not exist for user.') # if none exists, log out user_logged_in.connect(perform_some_action_on_login) user_logged_out.connect(perform_some_action_on_logout) class Me(DjangoObjectType): class Meta: model = User # only_fields = ('id', 'username', 'is_superuser') # filter_fields = ('id', 'username', 'is_superuser') class TeamType(DjangoObjectType): class Meta: model = Team
finally: request.user = current_user def process_view(self, request, view_func, *view_args, **view_kwargs): maintenance_response = self._get_maintenance_response(request, view_func) if maintenance_response: return maintenance_response def _get_maintenance_response(self, request, view_func): if settings.DEBUG: # Allow media and static accesses in debug mode if request.path.startswith("/media") or request.path.startswith("/static"): return None if getattr(view_func, "maintenance_mode_exempt", False): return None if "login" in view_func.__name__: return None resolver_match = getattr(request, "resolver_match", None) if resolver_match and resolver_match.app_name == "shoop_admin": return None if request.shop.maintenance_mode and not getattr(request.user, 'is_superuser', False): return HttpResponse(loader.render_to_string("shoop/front/maintenance.jinja", request=request), status=503) if ( "django.contrib.auth" in settings.INSTALLED_APPS and "shoop.front.middleware.ShoopFrontMiddleware" in settings.MIDDLEWARE_CLASSES ): user_logged_in.connect(ShoopFrontMiddleware.refresh_on_user_change, dispatch_uid="shoop_front_refresh_on_login") user_logged_out.connect(ShoopFrontMiddleware.refresh_on_logout, dispatch_uid="shoop_front_refresh_on_logout")
) post_save.connect( create_team_member_for_owner, sender=Team, dispatch_uid="create_team_member_for_owner", weak=False, ) post_save.connect( update_document, sender=Group, dispatch_uid="update_document", weak=False, ) pre_delete.connect( remove_key_for_team_member, sender=TeamMember, dispatch_uid="remove_key_for_team_member", weak=False, ) user_logged_in.connect(set_language_on_logon, dispatch_uid="set_language_on_logon", weak=False) post_save.connect( on_alert_creation, sender=Alert, dispatch_uid="on_alert_creation", weak=False, ) add_introspection_rules([], ["^social_auth\.fields\.JSONField"])
dataspaces = api.get_dataspace() dprojects = {} for d in dataspaces: if d['name'].startswith('nte_'): name=d['name'][4:] dprojects[name] = d try: project, created=Project.objects.get_or_create(slug=name, defaults={'name': name }) if created and not user.superuser_or_belongs_to(project): logger.debug('Adding editor role in local project: %s', pname) role = project.roles.get(role='Editor') # TODO get privileges from API role.users.add(user) except: logger.error("Unexpected error creating group '%s': %s", name, sys.exc_info()[0]) logger.info('dataspace with nte projects: %s', dprojects) for p in user.get_authorized_projects(): pname = cendari_clean_name(p.name) if pname not in dprojects: logger.debug('creating remote project: %s', pname) try: api.create_dataspace('nte_'+pname,title=p.name) except CendariDataAPIException as e: logger.error('Problem creating project "%s" with DATA Api: %s', pname, e) except CendariDataAPIException as e: logger.error('Problem synchonizing projects with DATA Api: %s', e) except: logger.error("Unexpected error: %s", exc_info()[0]) user_logged_in.connect(login_user_synchronize)
'email': self.email, 'inviter': self, } email_template = 'pinax/notifications/account_active/account_active' adapter = get_invitations_adapter() adapter.send_invitation_email(email_template, self.email, ctx) except Exception: import traceback traceback.print_exc() def send_mail(self, template_prefix, context): if self.email: get_adapter().send_mail(template_prefix, self.email, context) def get_anonymous_user_instance(user_model): return user_model(pk=-1, username='******') """ Connect relevant signals to their corresponding handlers. """ user_logged_in.connect(do_login) user_logged_out.connect(do_logout) social_account_added.connect(update_user_email_addresses, dispatch_uid=str(uuid4()), weak=False) user_signed_up.connect(notify_admins_new_signup, dispatch_uid=str(uuid4()), weak=False) signals.post_save.connect(profile_post_save, sender=settings.AUTH_USER_MODEL)