Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: track user login timestamps (#15148)

Saurya Velagapudi8dd7d65a596d
diff --git a/enterprise/migrations/versions/131_add_user_login_timestamps.py b/enterprise/migrations/versions/131_add_user_login_timestamps.py
new file mode 100644
index 0000000000..1a944c5550
--- /dev/null
+++ b/enterprise/migrations/versions/131_add_user_login_timestamps.py
@@ -0,0 +1,26 @@
+"""Add user login timestamps.
+
+Revision ID: 131
+Revises: 130
+Create Date: 2026-06-16 00:00:00.000000
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = '131'
+down_revision: Union[str, None] = '130'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column('user', sa.Column('first_login_at', sa.DateTime(), nullable=True))
+ op.add_column('user', sa.Column('last_login_at', sa.DateTime(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column('user', 'last_login_at')
+ op.drop_column('user', 'first_login_at')
diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.py
index 5ee157ee73..535381dcc5 100644
--- a/enterprise/server/routes/auth.py
+++ b/enterprise/server/routes/auth.py
@@ -443,6 +443,8 @@ async def keycloak_callback(
response = RedirectResponse(verification_redirect_url, status_code=302)
return response
+ await UserStore.record_login(user_id)
+
# default to github IDP for now.
# TODO: remove default once Keycloak is updated universally with the new attribute.
idp: str = user_info.identity_provider or ProviderType.GITHUB.value
@@ -465,9 +467,7 @@ async def keycloak_callback(
else True
)
- logger.debug(
- f'keycloakAccessToken: {keycloak_access_token}, keycloakUserId: {user_id}'
- )
+ logger.debug('keycloak_user_authenticated', extra={'user_id': user_id})
# Server-side identity β€” defer to background to avoid blocking auth response
consented = user.user_consents_to_analytics is True
@@ -893,7 +893,12 @@ async def accept_tos(request: Request):
if not access_token or not refresh_token or not user_id:
logger.warning(
- f'accept_tos: One or more is None: access_token {access_token}, refresh_token {refresh_token}, user_id {user_id}'
+ 'accept_tos: missing authentication state',
+ extra={
+ 'has_access_token': bool(access_token),
+ 'has_refresh_token': bool(refresh_token),
+ 'user_id': user_id,
+ },
)
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
diff --git a/enterprise/storage/user.py b/enterprise/storage/user.py
index 154412f3fa..3ad981e4cb 100644
--- a/enterprise/storage/user.py
+++ b/enterprise/storage/user.py
@@ -33,6 +33,8 @@ class User(Base):
# Effective permissions are defined by SUPER_ROLE_PERMISSIONS.
role_id: Mapped[int | None] = mapped_column(ForeignKey('role.id'), nullable=True)
accepted_tos: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
+ first_login_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
+ last_login_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
enable_sound_notifications: Mapped[bool | None] = mapped_column(nullable=True)
language: Mapped[str | None] = mapped_column(String, nullable=True)
user_consents_to_analytics: Mapped[bool | None] = mapped_column(nullable=True)
diff --git a/enterprise/storage/user_store.py b/enterprise/storage/user_store.py
index a2197ac97b..f56a25af3f 100644
--- a/enterprise/storage/user_store.py
+++ b/enterprise/storage/user_store.py
@@ -2,6 +2,7 @@
import asyncio
import uuid
+from datetime import datetime, timezone
from enum import Enum
from typing import Optional
from uuid import UUID
@@ -201,6 +202,19 @@ class UserStore:
await session.refresh(user, ['org_members']) # load org_members
return user
+ @staticmethod
+ async def record_login(user_id: str) -> None:
+ """Record a successful login for a user."""
+ async with a_session_maker() as session:
+ user = await session.get(User, uuid.UUID(user_id))
+ if not user:
+ return
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ if user.first_login_at is None:
+ user.first_login_at = now
+ user.last_login_at = now
+ await session.commit()
+
@staticmethod
def _get_redis_client():
"""Get the shared async Redis client from enterprise storage."""
diff --git a/enterprise/tests/unit/test_auth_routes.py b/enterprise/tests/unit/test_auth_routes.py
index 27e426d0f2..10eb52fd59 100644
--- a/enterprise/tests/unit/test_auth_routes.py
+++ b/enterprise/tests/unit/test_auth_routes.py
@@ -173,6 +173,7 @@ async def test_keycloak_callback_user_not_authorized(
mock_user_store.migrate_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Create mock user authorizer that denies authorization
mock_authorizer = create_mock_user_authorizer(
@@ -242,6 +243,7 @@ async def test_keycloak_callback_success_with_valid_offline_token(
mock_user_store.migrate_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_token_manager.get_keycloak_tokens = AsyncMock(
return_value=('test_access_token', 'test_refresh_token')
@@ -339,6 +341,7 @@ async def test_keycloak_callback_email_not_verified(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -402,6 +405,7 @@ async def test_keycloak_callback_email_not_verified_missing_field(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -468,6 +472,7 @@ async def test_keycloak_callback_email_verification_rate_limited(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -546,6 +551,7 @@ async def test_keycloak_callback_success_without_offline_token(
mock_user_store.migrate_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_token_manager.get_keycloak_tokens = AsyncMock(
return_value=('test_access_token', 'test_refresh_token')
@@ -649,6 +655,7 @@ async def test_keycloak_callback_redirects_to_keycloak_when_offline_token_invali
mock_user_store.get_user_by_id = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_token_manager.get_keycloak_tokens = AsyncMock(
return_value=('test_access_token', 'test_refresh_token')
@@ -1014,6 +1021,7 @@ async def test_keycloak_callback_blocked_email_domain(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Create mock user authorizer that blocks the user
mock_authorizer = create_mock_user_authorizer(
@@ -1094,6 +1102,7 @@ async def test_keycloak_callback_missing_email(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -1145,6 +1154,7 @@ async def test_keycloak_callback_duplicate_email_detected(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Create mock authorizer that returns duplicate_email error
mock_authorizer = create_mock_user_authorizer(
@@ -1318,6 +1328,7 @@ async def test_keycloak_callback_duplicate_check_exception(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -1382,6 +1393,7 @@ async def test_keycloak_callback_no_duplicate_email(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act - use successful authorizer (no duplicate detected)
result = await keycloak_callback(
@@ -1441,6 +1453,7 @@ async def test_keycloak_callback_no_email_in_user_info(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
# Act
result = await keycloak_callback(
@@ -1529,6 +1542,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -1600,6 +1614,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -1692,6 +1707,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -1784,6 +1800,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -1875,6 +1892,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -1963,6 +1981,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -2048,6 +2067,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -2121,6 +2141,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -2200,6 +2221,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -2277,6 +2299,7 @@ class TestKeycloakCallbackRecaptcha:
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_user_auth_store.get_authorization_type = AsyncMock(return_value=None)
@@ -2331,6 +2354,7 @@ async def test_keycloak_callback_calls_backfill_user_email_for_existing_user(
mock_user_store.create_user = AsyncMock(return_value=mock_user)
mock_user_store.backfill_contact_name = AsyncMock()
mock_user_store.backfill_user_email = AsyncMock()
+ mock_user_store.record_login = AsyncMock()
mock_token_manager.get_keycloak_tokens = AsyncMock(
return_value=('test_access_token', 'test_refresh_token')
diff --git a/enterprise/tests/unit/test_user_store_login.py b/enterprise/tests/unit/test_user_store_login.py
new file mode 100644
index 0000000000..4ae3700d71
--- /dev/null
+++ b/enterprise/tests/unit/test_user_store_login.py
@@ -0,0 +1,93 @@
+import sys
+import uuid
+from contextlib import asynccontextmanager
+from datetime import datetime, timezone
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3] / 'enterprise'))
+
+from enterprise.storage import user_store as user_store_module
+from enterprise.storage.user_store import UserStore
+
+
+class FrozenDateTime:
+ def __init__(self, fixed: datetime):
+ self._fixed = fixed
+
+ def now(self, tz=None):
+ return self._fixed
+
+
+class DummySession:
+ def __init__(self, user):
+ self.user = user
+ self.committed = False
+ self.get_args = None
+
+ async def get(self, model, user_id):
+ self.get_args = (model, user_id)
+ return self.user
+
+ async def commit(self):
+ self.committed = True
+
+
+async def test_record_login_sets_first_and_last(monkeypatch):
+ fixed = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
+ expected = fixed.replace(tzinfo=None)
+ user = SimpleNamespace(first_login_at=None, last_login_at=None)
+ session = DummySession(user)
+
+ @asynccontextmanager
+ async def fake_session_maker():
+ yield session
+
+ monkeypatch.setattr(user_store_module, 'a_session_maker', fake_session_maker)
+ monkeypatch.setattr(user_store_module, 'datetime', FrozenDateTime(fixed))
+
+ await UserStore.record_login('00000000-0000-0000-0000-000000000001')
+
+ assert user.first_login_at == expected
+ assert user.last_login_at == expected
+ assert session.committed is True
+
+
+async def test_record_login_preserves_first_login(monkeypatch):
+ fixed = datetime(2026, 2, 1, 9, 30, 0, tzinfo=timezone.utc)
+ expected_last = fixed.replace(tzinfo=None)
+ initial_first = datetime(2025, 12, 25, 8, 0, 0)
+ user = SimpleNamespace(first_login_at=initial_first, last_login_at=None)
+ session = DummySession(user)
+
+ @asynccontextmanager
+ async def fake_session_maker():
+ yield session
+
+ monkeypatch.setattr(user_store_module, 'a_session_maker', fake_session_maker)
+ monkeypatch.setattr(user_store_module, 'datetime', FrozenDateTime(fixed))
+
+ await UserStore.record_login('00000000-0000-0000-0000-000000000001')
+
+ assert user.first_login_at == initial_first
+ assert user.last_login_at == expected_last
+ assert session.committed is True
+
+
+async def test_record_login_no_user(monkeypatch):
+ session = DummySession(user=None)
+
+ @asynccontextmanager
+ async def fake_session_maker():
+ yield session
+
+ monkeypatch.setattr(user_store_module, 'a_session_maker', fake_session_maker)
+
+ await UserStore.record_login(str(uuid.uuid4()))
+
+ assert session.committed is False