def test_send_login_emails_if_send_login_email_setting_is_true( self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.assertTrue(settings.SEND_LOGIN_EMAILS) # we don't use the self.login method since we spoof the user-agent user = self.example_user('hamlet') user.timezone = 'US/Pacific' user.save() password = initial_password(user.email) firefox_windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" utc = get_timezone('utc') user_tz = get_timezone(user.timezone) mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) utc_offset = mock_time.astimezone(user_tz).strftime('%z') reference_time = mock_time.astimezone(user_tz).strftime( '%A, %B %d, %Y at %I:%M%p ') + utc_offset with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={ "username": user.email, "password": password }, HTTP_USER_AGENT=firefox_windows) # email is sent and correct subject self.assertEqual(len(mail.outbox), 1) subject = 'New login from Firefox on Windows' self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body self.assertIn(reference_time, mail.outbox[0].body)
def test_send_login_emails_if_send_login_email_setting_is_true( self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.assertTrue(settings.SEND_LOGIN_EMAILS) # we don't use the self.login method since we spoof the user-agent utc = get_timezone('utc') mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) user = self.example_user('hamlet') user.timezone = 'US/Pacific' user.twenty_four_hour_time = False user.date_joined = mock_time - datetime.timedelta( seconds=JUST_CREATED_THRESHOLD + 1) user.save() password = initial_password(user.email) firefox_windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" user_tz = get_timezone(user.timezone) mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) reference_time = mock_time.astimezone(user_tz).strftime( '%A, %B %d, %Y at %I:%M%p %Z') with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={ "username": user.email, "password": password }, HTTP_USER_AGENT=firefox_windows) # email is sent and correct subject self.assertEqual(len(mail.outbox), 1) subject = 'New login from Firefox on Windows' self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body self.assertIn(reference_time, mail.outbox[0].body) # Try again with the 24h time format setting enabled for this user self.logout() # We just logged in, we'd be redirected without this user.twenty_four_hour_time = True user.save() with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={ "username": user.email, "password": password }, HTTP_USER_AGENT=firefox_windows) reference_time = mock_time.astimezone(user_tz).strftime( '%A, %B %d, %Y at %H:%M %Z') self.assertIn(reference_time, mail.outbox[1].body)
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None: # We import here to minimize the dependencies of this module, # since it runs as part of `manage.py` initialization from zerver.context_processors import common_context if not settings.SEND_LOGIN_EMAILS: return if request: # If the user's account was just created, avoid sending an email. if getattr(user, "just_registered", False): return user_agent = request.META.get('HTTP_USER_AGENT', "").lower() context = common_context(user) context['user_email'] = user.email user_tz = user.timezone if user_tz == '': user_tz = timezone_get_current_timezone_name() local_time = timezone_now().astimezone(get_timezone(user_tz)) context['login_time'] = local_time.strftime('%A, %B %d, %Y at %I:%M%p ') + user_tz context['device_ip'] = request.META.get('REMOTE_ADDR') or _("Unknown IP address") context['device_os'] = get_device_os(user_agent) context['device_browser'] = get_device_browser(user_agent) email_dict = { 'template_prefix': 'zerver/emails/notify_new_login', 'to_user_id': user.id, 'from_name': 'Zulip Account Security', 'from_address': FromAddress.NOREPLY, 'context': context} queue_json_publish("email_senders", email_dict)
def handle_deferred_message(sender: UserProfile, client: Client, message_type_name: str, message_to: Union[Sequence[str], Sequence[int]], topic_name: Optional[str], message_content: str, delivery_type: str, defer_until: str, tz_guess: Optional[str], forwarder_user_profile: UserProfile, realm: Optional[Realm]) -> HttpResponse: deliver_at = None local_tz = 'UTC' if tz_guess: local_tz = tz_guess elif sender.timezone: local_tz = sender.timezone try: deliver_at = dateparser(defer_until) except ValueError: return json_error(_("Invalid time format")) deliver_at_usertz = deliver_at if deliver_at_usertz.tzinfo is None: user_tz = get_timezone(local_tz) deliver_at_usertz = user_tz.normalize(user_tz.localize(deliver_at)) deliver_at = convert_to_UTC(deliver_at_usertz) if deliver_at <= timezone_now(): return json_error(_("Time must be in the future.")) check_schedule_message(sender, client, message_type_name, message_to, topic_name, message_content, delivery_type, deliver_at, realm=realm, forwarder_user_profile=forwarder_user_profile) return json_success({"deliver_at": str(deliver_at_usertz)})
def test_send_login_emails_if_send_login_email_setting_is_true(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.assertTrue(settings.SEND_LOGIN_EMAILS) # we don't use the self.login method since we spoof the user-agent utc = get_timezone('utc') mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) user = self.example_user('hamlet') user.timezone = 'US/Pacific' user.twenty_four_hour_time = False user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) user.save() password = initial_password(user.email) firefox_windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" user_tz = get_timezone(user.timezone) mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %I:%M%p %Z') with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={"username": user.email, "password": password}, HTTP_USER_AGENT=firefox_windows) # email is sent and correct subject self.assertEqual(len(mail.outbox), 1) subject = 'New login from Firefox on Windows' self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body self.assertIn(reference_time, mail.outbox[0].body) # Try again with the 24h time format setting enabled for this user self.logout() # We just logged in, we'd be redirected without this user.twenty_four_hour_time = True user.save() with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={"username": user.email, "password": password}, HTTP_USER_AGENT=firefox_windows) reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %H:%M %Z') self.assertIn(reference_time, mail.outbox[1].body)
def test_send_login_emails_if_send_login_email_setting_is_true(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): self.assertTrue(settings.SEND_LOGIN_EMAILS) # we don't use the self.login method since we spoof the user-agent user = self.example_user('hamlet') user.timezone = 'US/Pacific' user.save() password = initial_password(user.email) firefox_windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" utc = get_timezone('utc') user_tz = get_timezone(user.timezone) mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) reference_time = mock_time.astimezone(user_tz).strftime('%A, %B %d, %Y at %I:%M%p ') + user.timezone with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.client_post("/accounts/login/", info={"username": user.email, "password": password}, HTTP_USER_AGENT=firefox_windows) # email is sent and correct subject self.assertEqual(len(mail.outbox), 1) subject = 'New login from Firefox on Windows' self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body self.assertIn(reference_time, mail.outbox[0].body)
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None: if not user.enable_login_emails: return # We import here to minimize the dependencies of this module, # since it runs as part of `manage.py` initialization from zerver.context_processors import common_context if not settings.SEND_LOGIN_EMAILS: return if request: # If the user's account was just created, avoid sending an email. if (timezone_now() - user.date_joined).total_seconds() <= JUST_CREATED_THRESHOLD: return user_agent = request.META.get('HTTP_USER_AGENT', "").lower() context = common_context(user) context['user_email'] = user.delivery_email user_tz = user.timezone if user_tz == '': user_tz = timezone_get_current_timezone_name() local_time = timezone_now().astimezone(get_timezone(user_tz)) if user.twenty_four_hour_time: hhmm_string = local_time.strftime('%H:%M') else: hhmm_string = local_time.strftime('%I:%M%p') context['login_time'] = local_time.strftime( '%A, %B %d, %Y at {} %Z'.format(hhmm_string)) context['device_ip'] = request.META.get('REMOTE_ADDR') or _( "Unknown IP address") context['device_os'] = get_device_os(user_agent) or _( "an unknown operating system") context['device_browser'] = get_device_browser(user_agent) or _( "An unknown browser") context['unsubscribe_link'] = one_click_unsubscribe_link(user, 'login') email_dict = { 'template_prefix': 'zerver/emails/notify_new_login', 'to_user_ids': [user.id], 'from_name': FromAddress.security_email_from_name(user_profile=user), 'from_address': FromAddress.NOREPLY, 'context': context } queue_json_publish("email_senders", email_dict)
def test_enable_login_emails_user_setting(self) -> None: user = self.example_user('hamlet') utc = get_timezone('utc') mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=utc) user.timezone = 'US/Pacific' user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1) user.save() do_change_notification_settings(user, "enable_login_emails", False) self.assertFalse(user.enable_login_emails) with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.login(user.email) self.assertEqual(len(mail.outbox), 0) do_change_notification_settings(user, "enable_login_emails", True) self.assertTrue(user.enable_login_emails) with mock.patch('zerver.signals.timezone_now', return_value=mock_time): self.login(user.email) self.assertEqual(len(mail.outbox), 1)
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None: if not user.enable_login_emails: return # We import here to minimize the dependencies of this module, # since it runs as part of `manage.py` initialization from zerver.context_processors import common_context if not settings.SEND_LOGIN_EMAILS: return if request: # If the user's account was just created, avoid sending an email. if (timezone_now() - user.date_joined).total_seconds() <= JUST_CREATED_THRESHOLD: return user_agent = request.META.get('HTTP_USER_AGENT', "").lower() context = common_context(user) context['user_email'] = user.email user_tz = user.timezone if user_tz == '': user_tz = timezone_get_current_timezone_name() local_time = timezone_now().astimezone(get_timezone(user_tz)) if user.twenty_four_hour_time: hhmm_string = local_time.strftime('%H:%M') else: hhmm_string = local_time.strftime('%I:%M%p') context['login_time'] = local_time.strftime('%A, %B %d, %Y at {} %Z'.format(hhmm_string)) context['device_ip'] = request.META.get('REMOTE_ADDR') or _("Unknown IP address") context['device_os'] = get_device_os(user_agent) or _("an unknown operating system") context['device_browser'] = get_device_browser(user_agent) or _("An unknown browser") context['unsubscribe_link'] = one_click_unsubscribe_link(user, 'login') email_dict = { 'template_prefix': 'zerver/emails/notify_new_login', 'to_user_ids': [user.id], 'from_name': 'Zulip Account Security', 'from_address': FromAddress.NOREPLY, 'context': context} queue_json_publish("email_senders", email_dict)
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None: # We import here to minimize the dependencies of this module, # since it runs as part of `manage.py` initialization from zerver.context_processors import common_context if not settings.SEND_LOGIN_EMAILS: return if request: # If the user's account was just created, avoid sending an email. if getattr(user, "just_registered", False): return user_agent = request.META.get('HTTP_USER_AGENT', "").lower() context = common_context(user) context['user_email'] = user.email user_tz = user.timezone if user_tz == '': user_tz = timezone_get_current_timezone_name() local_time = timezone_now().astimezone(get_timezone(user_tz)) utc_offset = local_time.strftime('%z') context['login_time'] = local_time.strftime( '%A, %B %d, %Y at %I:%M%p ') + utc_offset context['device_ip'] = request.META.get('REMOTE_ADDR') or _( "Unknown IP address") context['device_os'] = get_device_os(user_agent) context['device_browser'] = get_device_browser(user_agent) email_dict = { 'template_prefix': 'zerver/emails/notify_new_login', 'to_user_id': user.id, 'from_name': 'Zulip Account Security', 'from_address': FromAddress.NOREPLY, 'context': context } queue_json_publish("email_senders", email_dict)