Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
users: Update date_joined field when user logs in for the first time.
Sahil Batrafc1fc42134fe
diff --git a/api_docs/unmerged.d/ZF-658515.md b/api_docs/unmerged.d/ZF-658515.mdnew file mode 100644index 00000000000..c1a37a06d06--- /dev/null+++ b/api_docs/unmerged.d/ZF-658515.md@@ -0,0 +1,8 @@+* [`GET /events`](/api/get-events): `realm_user` events with `op: "update"`+ are now sent when the `date_joined` field is updated after an imported+ stub user or a user created via the API logs in for the first time.+* [`GET /users`](/api/get-users), [`GET /users/{user_id}`](/api/get-user),+ [`GET /users/{email}`](/api/get-user-by-email),+ [`GET /users/me`](/api/get-own-user): The `date_joined` field is initially+ set to the account creation time and is updated to the time of first login+ for imported stub users and users created via the API.diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.pyindex d8a90d75880..5a2de2aac8b 100644--- a/zerver/actions/user_settings.py+++ b/zerver/actions/user_settings.py@@ -1,5 +1,5 @@from collections.abc import Iterable-from datetime import timedelta+from datetime import datetime, timedeltafrom enum import Enumfrom django.conf import settings@@ -690,3 +690,30 @@ def bulk_change_user_setting(force_send_update=True,))++[email protected](durable=True)+def do_change_user_date_joined(user_profile: UserProfile, date_joined: datetime) -> None:+ old_date_joined = user_profile.date_joined+ user_profile.date_joined = date_joined+ user_profile.save(update_fields=["date_joined"])++ event_time = timezone_now()+ RealmAuditLog.objects.create(+ realm=user_profile.realm,+ acting_user=user_profile,+ modified_user=user_profile,+ event_type=AuditLogEventType.USER_DATE_JOINED_CHANGED,+ event_time=event_time,+ extra_data={+ RealmAuditLog.OLD_VALUE: old_date_joined.isoformat(),+ RealmAuditLog.NEW_VALUE: date_joined.isoformat(),+ },+ )++ payload = dict(user_id=user_profile.id, date_joined=date_joined.isoformat(timespec="minutes"))+ send_event_on_commit(+ user_profile.realm,+ dict(type="realm_user", op="update", person=payload),+ get_user_ids_who_can_access_user(user_profile),+ )diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.pyindex 6fce093cdfa..a9e35e89a40 100644--- a/zerver/lib/event_schema.py+++ b/zerver/lib/event_schema.py@@ -113,6 +113,7 @@ from zerver.lib.event_types import (PersonAvatarFields,PersonBotOwnerId,PersonCustomProfileField,+ PersonDateJoined,PersonDeliveryEmail,PersonEmail,PersonFullName,@@ -274,6 +275,7 @@ PERSON_TYPES: dict[str, type[BaseModel]] = dict(avatar_fields=PersonAvatarFields,bot_owner_id=PersonBotOwnerId,custom_profile_field=PersonCustomProfileField,+ date_joined=PersonDateJoined,delivery_email=PersonDeliveryEmail,email=PersonEmail,full_name=PersonFullName,diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.pyindex beb9f0dc066..5c2fe811065 100644--- a/zerver/lib/event_types.py+++ b/zerver/lib/event_types.py@@ -765,6 +765,11 @@ class PersonIsImportedStub(BaseModel):is_imported_stub: bool+class PersonDateJoined(BaseModel):+ user_id: int+ date_joined: str++class EventRealmUserUpdate(BaseEvent):type: Literal["realm_user"]op: Literal["update"]@@ -772,6 +777,7 @@ class EventRealmUserUpdate(BaseEvent):PersonAvatarFields| PersonBotOwnerId| PersonCustomProfileField+ | PersonDateJoined| PersonDeliveryEmail| PersonEmail| PersonFullNamediff --git a/zerver/models/realm_audit_logs.py b/zerver/models/realm_audit_logs.pyindex a0c660843f7..d1285fa3e31 100644--- a/zerver/models/realm_audit_logs.py+++ b/zerver/models/realm_audit_logs.py@@ -38,6 +38,7 @@ class AuditLogEventType(IntEnum):USER_SETTING_CHANGED = 132USER_DIGEST_EMAIL_CREATED = 133USER_IS_IMPORTED_STUB_CHANGED = 134+ USER_DATE_JOINED_CHANGED = 135REALM_DEACTIVATED = 201REALM_REACTIVATED = 202diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 260ecf3fb86..f3e1e6e2e50 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -562,6 +562,24 @@ paths:is_imported_stub:type: booleandescription: This value is always `false`.+ - type: object+ additionalProperties: false+ description: |+ Sent when the `date_joined` value is updated after an+ imported stub user or a user created via the API logs+ in for the first time.++ **Changes**: New in Zulip 12.0 (feature level ZF-658515).+ properties:+ user_id:+ type: integer+ description: |+ The ID of the user affected by this change.+ date_joined:+ type: string+ description: |+ The time when the user logged in to their account+ for the first time.additionalProperties: falseexample:{@@ -11203,9 +11221,22 @@ paths:date_joined:type: stringdescription: |- The time the requesting user's account was created.+ The time when the user joined. For users imported from other+ applications and users created via the API, this is set to the+ account creation time until the user logs in for the first time,+ after which it is updated to that login time.- **Changes**: New in Zulip 3.0 (feature level 10).+ For imported users, clients can use the `is_imported_stub` flag+ to determine how to display this field: when `is_imported_stub`+ is `true`, the user has not yet logged in and this value is the+ account creation time during import; when `is_imported_stub` is+ `false`, this value reflects when the user first logged in.++ **Changes**: Starting with Zulip 12.0 (feature level ZF-658515),+ this field is updated when an imported stub user or a user created+ via the API logs in for the first time.++ New in Zulip 3.0 (feature level 10).example: "2019-10-20T07:50:53.728864+00:00"max_message_id:type: integer@@ -28465,7 +28496,20 @@ components:date_joined:type: stringdescription: |- The time the user account was created.+ The time when the user joined. For users imported from other+ applications and users created via the API, this is set to the+ account creation time until the user logs in for the first time,+ after which it is updated to that login time.++ For imported users, clients can use the `is_imported_stub` flag+ to determine how to display this field: when `is_imported_stub`+ is `true`, the user has not yet logged in and this value is the+ account creation time during import; when `is_imported_stub` is+ `false`, this value reflects when the user first logged in.++ **Changes**: Starting with Zulip 12.0 (feature level ZF-658515),+ this field is updated when an imported stub user or a user created+ via the API logs in for the first time.is_active:type: booleandescription: |diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.pyindex d8b46339d6f..ffc99ee1145 100644--- a/zerver/tests/test_audit_log.py+++ b/zerver/tests/test_audit_log.py@@ -78,6 +78,7 @@ from zerver.actions.user_settings import (do_change_avatar_fields,do_change_password,do_change_tos_version,+ do_change_user_date_joined,do_change_user_delivery_email,do_change_user_setting,do_regenerate_api_key,@@ -1846,3 +1847,26 @@ class TestRealmAuditLog(ZulipTestCase):self.assert_length(audit_log_entries, 1)self.assertEqual(audit_log_entries[0].modified_user, hamlet)self.assertEqual(audit_log_entries[0].extra_data, {})++ def test_updating_date_joined(self) -> None:+ hamlet = self.example_user("hamlet")+ old_value = hamlet.date_joined++ now = timezone_now()++ do_change_user_date_joined(hamlet, now)+ audit_log_entries = RealmAuditLog.objects.filter(+ acting_user=hamlet,+ realm=hamlet.realm,+ event_time__gte=now,+ event_type=AuditLogEventType.USER_DATE_JOINED_CHANGED,+ )+ self.assert_length(audit_log_entries, 1)+ self.assertEqual(audit_log_entries[0].modified_user, hamlet)+ self.assertEqual(+ audit_log_entries[0].extra_data,+ {+ RealmAuditLog.OLD_VALUE: old_value.isoformat(),+ RealmAuditLog.NEW_VALUE: now.isoformat(),+ },+ )diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 011f15db0d0..288e120dcc7 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -151,6 +151,7 @@ from zerver.actions.user_groups import (from zerver.actions.user_settings import (do_change_avatar_fields,do_change_full_name,+ do_change_user_date_joined,do_change_user_delivery_email,do_change_user_setting,do_regenerate_api_key,@@ -2640,6 +2641,12 @@ class NormalActionsTest(BaseAction):with self.verify_action(num_events=0, state_change_expected=False):do_change_full_name(cordelia, "Cordelia", self.user_profile, notify=False)+ def test_change_date_joined(self) -> None:+ now = timezone_now()+ with self.verify_action() as events:+ do_change_user_date_joined(self.user_profile, now)+ check_realm_user_update("events[0]", events[0], "date_joined")+def test_change_user_delivery_email_email_address_visibility_admins(self) -> None:do_change_user_setting(self.user_profile,diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 258345b7094..8c52f7f8d4d 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -758,6 +758,22 @@ class HomeTest(ZulipTestCase):user = self.example_user("hamlet")self.assertFalse(user.is_imported_stub)+ # Test date_joined is set to the current time when user logs in for the+ # first time.+ user.tos_version = UserProfile.TOS_VERSION_BEFORE_FIRST_LOGIN+ user.save()++ now = timezone_now()+ with time_machine.travel(now, tick=False):+ result = self.client_post("/accounts/accept_terms/", {"terms": True})+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result["Location"], "/")++ user = self.example_user("hamlet")+ # Check that date_joined is updated to the time when user accepts ToS+ # when logging in for the first time.+ self.assertEqual(user.date_joined, now)+def test_set_email_address_visibility_without_terms_of_service(self) -> None:self.login("hamlet")user = self.example_user("hamlet")diff --git a/zerver/views/home.py b/zerver/views/home.pyindex e1dff6701cf..8467b138558 100644--- a/zerver/views/home.py+++ b/zerver/views/home.py@@ -6,8 +6,13 @@ from django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.shortcuts import redirect, renderfrom django.urls import reversefrom django.utils.cache import patch_cache_control+from django.utils.timezone import now as timezone_now-from zerver.actions.user_settings import do_change_tos_version, do_change_user_setting+from zerver.actions.user_settings import (+ do_change_tos_version,+ do_change_user_date_joined,+ do_change_user_setting,+)from zerver.actions.users import do_change_is_imported_stubfrom zerver.context_processors import get_realm_from_request, get_valid_realm_from_requestfrom zerver.decorator import web_public_view, zulip_login_required@@ -41,6 +46,9 @@ def accounts_accept_terms(request: HttpRequest) -> HttpResponse:if request.method == "POST":form = ToSForm(request.POST)if form.is_valid():+ first_time_login = (+ request.user.tos_version == UserProfile.TOS_VERSION_BEFORE_FIRST_LOGIN+ )assert (settings.TERMS_OF_SERVICE_VERSION is not Noneor request.user.tos_version == UserProfile.TOS_VERSION_BEFORE_FIRST_LOGIN@@ -74,6 +82,9 @@ def accounts_accept_terms(request: HttpRequest) -> HttpResponse:if request.user.is_imported_stub:do_change_is_imported_stub(request.user)+ if first_time_login:+ do_change_user_date_joined(request.user, timezone_now())+return redirect(home)else:form = ToSForm()