Skip to content

Add Inactive user status for users who haven't logged in for 30+ days#49211

Open
allenhouchins wants to merge 4 commits into
mainfrom
add-inactive-user-status
Open

Add Inactive user status for users who haven't logged in for 30+ days#49211
allenhouchins wants to merge 4 commits into
mainfrom
add-inactive-user-status

Conversation

@allenhouchins

@allenhouchins allenhouchins commented Jul 13, 2026

Copy link
Copy Markdown
Member

Adds an "Inactive" status to the Users table for accounts that haven't been used for 30+ days — both human users and API-only accounts — with a tooltip explaining what it means, and builds the underlying last-login / last-activity tracking to surface that info.

Details

Backend

  • New users.last_login_at column (nullable timestamp). Backfilled from live sessions' created_at (session creation = login); users with no live session keep NULL. The backfill explicitly preserves updated_at (which has ON UPDATE CURRENT_TIMESTAMP).
  • last_login_at is stamped whenever a session is created (makeSessionInTransaction), covering password, SSO, and MFA logins. NewSession now wraps the session insert + stamp in a transaction.
  • New computed last_activity_at field: MAX(accessed_at) over the user's live sessions (Fleet already bumps accessed_at on every authenticated request). This is the inactivity signal for API-only accounts, whose long-lived token session is created once but used constantly. A new idx_sessions_user_id index supports the aggregate.
  • Both fields are returned on user objects from the users API endpoints (null when never logged in / no live session).

Frontend

  • The Users table status is now derived as: "No access" (unchanged) → "Invite pending" (unchanged) → "Inactive" when the account's last-seen time is 30+ days old → otherwise "Active".
  • Last seen = most recent of last_activity_at and last_login_at, falling back to created_at for accounts that have never logged in.
  • Tooltip on the Inactive status: "Hasn't logged in for 30+ days" for regular users, "No API activity for 30+ days" for API-only users.

Checklist for submitter

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

  • Input data is properly validated, SELECT * is avoided, SQL injection is prevented (using placeholders for values in statements), JS inline code is prevented especially for url redirects, and untrusted data interpolated into shell scripts/commands is validated against shell metacharacters.

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Database migrations

  • Checked schema for all modified table for columns that will auto-update timestamps during migration.
  • Confirmed that updating the timestamps is acceptable, and will not cause unwanted side effects.
    • users.updated_at has ON UPDATE CURRENT_TIMESTAMP; both the migration backfill and the per-login stamp explicitly preserve it (updated_at = updated_at), covered by tests.
  • Ensured the correct collation is explicitly set for character columns (COLLATE utf8mb4_unicode_ci).
    • N/A in practice: the new column is a TIMESTAMP, no character columns added.

Summary by CodeRabbit

  • New Features
    • Added user last-login tracking, including backfill from existing session creation timestamps.
    • Updated the Admin → Manage Users table to classify users as Active/Inactive based on most recent activity vs last login, and to show “No access” / “Invite pending” accordingly (with an inactivity tooltip).
  • Bug Fixes
    • Improved StatusIndicator styling for inactive vs no-access states, ensuring the correct visual treatment.
  • Tests
    • Added migration and datastore session/user tests to validate last-login behavior and updated Manage Users status logic.

Users who haven't logged in for 30+ days now show an "Inactive" status
(with an explanatory tooltip) in the Users table.

- Add users.last_login_at column, backfilled from live sessions'
  created_at (login time), preserving updated_at
- Stamp last_login_at whenever a session is created (password, SSO, MFA)
- Wrap NewSession's insert + stamp in a transaction
- Return last_login_at from the users API
- Frontend derives Inactive from last_login_at (created_at fallback);
  API-only users are never marked inactive
Copilot AI review requested due to automatic review settings July 13, 2026 15:55
@allenhouchins allenhouchins requested review from a team and rachaelshaw as code owners July 13, 2026 15:55
@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.23077% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.99%. Comparing base (7ac8c65) to head (5ecdf56).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
...ersPage/components/UsersTable/UsersTableConfig.tsx 69.23% 8 Missing ⚠️
...ons/tables/20260713150609_AddLastLoginAtToUsers.go 61.90% 5 Missing and 3 partials ⚠️
server/datastore/mysql/sessions.go 71.42% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #49211    +/-   ##
========================================
  Coverage   67.99%   67.99%            
========================================
  Files        3779     3781     +2     
  Lines      239082   239227   +145     
  Branches    12610    12646    +36     
========================================
+ Hits       162563   162665   +102     
- Misses      61756    61793    +37     
- Partials    14763    14769     +6     
Flag Coverage Δ
backend 69.56% <69.23%> (+<0.01%) ⬆️
frontend 59.38% <69.23%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

  • Copilot's review of this pull request may be incomplete because some of the changed files are excluded by your Copilot content exclusion settings. See Excluding content from Copilot for details.

Pull request overview

This PR introduces backend tracking of a user’s most recent login time (users.last_login_at) and uses it in the admin Users table to surface an Inactive status for users who haven’t logged in for 30+ days (with a tooltip explaining the status).

Changes:

  • Add users.last_login_at (schema + migration with best-effort backfill from live sessions) and expose it on fleet.User.
  • Stamp last_login_at when creating a session (now done within a transaction) and add datastore tests to ensure updated_at is preserved.
  • Update the frontend Users table to derive “Inactive” status (with tooltip) and add unit tests + stubs/mocks updates.

Reviewed changes

Copilot reviewed 13 out of 15 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
server/fleet/users.go Adds LastLoginAt to the User API model.
server/datastore/mysql/users.go Includes last_login_at in standard user SELECT columns.
server/datastore/mysql/sessions.go Wraps session creation in a transaction and stamps users.last_login_at.
server/datastore/mysql/sessions_test.go Adds test coverage for last_login_at stamping and updated_at preservation.
server/datastore/mysql/schema.sql Updates schema snapshot for users.last_login_at and migration status table.
server/datastore/mysql/migrations/tables/20260713150609_AddLastLoginAtToUsers.go Adds the column + backfills from sessions.created_at.
server/datastore/mysql/migrations/tables/20260713150609_AddLastLoginAtToUsers_test.go Tests migration backfill + updated_at preservation.
frontend/interfaces/user.ts Adds last_login_at to IUser.
frontend/test/stubs.ts Updates frontend userStub to include last_login_at.
frontend/mocks/userMock.ts Updates default mock user to include last_login_at.
frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tsx Implements Inactive status logic + tooltip in the Users table.
frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tests.tsx Adds unit tests for Active/Inactive/No access/Invite pending cases.
frontend/components/StatusIndicator/_styles.scss Adds styling hook for the “inactive” status indicator.
docs/REST API/rest-api.md Updated (content excluded from review by policy).
changes/inactive-user-status.md Added/updated (content excluded from review by policy).
Files excluded by content exclusion policy (2)
  • changes/inactive-user-status.md
  • docs/REST API/rest-api.md

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +171 to +174
if _, err := tx.ExecContext(ctx,
`UPDATE users SET last_login_at = ?, updated_at = updated_at WHERE id = ?`,
ds.clock.Now(), userID,
); err != nil {
Comment thread frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tsx Outdated
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7f6ce1a9-6e64-4799-9c23-569d3afdca0d

📥 Commits

Reviewing files that changed from the base of the PR and between 9ab19d1 and 5ecdf56.

📒 Files selected for processing (1)
  • frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tsx

Walkthrough

Adds a nullable last_login_at field across the database, backend user model, frontend interface, mocks, and stubs. Existing users are backfilled from their latest session creation time, and new session creation updates the timestamp without changing updated_at. The admin users table now derives inactive, active, no-access, and invite-pending statuses, displays an inactive tooltip, and applies inactive indicator styling. Tests cover migration, session updates, and status combinations.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding an inactive user status after 30+ days without login.
Description check ✅ Passed The description matches the template well and covers the required sections, testing, and migration details.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-inactive-user-status

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tests.tsx (1)

74-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the "No access" invite path.

generateInviteStatus can return "No access" when an invite has global_role: null and empty teams, but no test covers this branch. Adding it would complete coverage for both return paths of the function.

🧪 Suggested test addition
   it("returns 'Invite pending' for invites", () => {
     const invites = [createMockInvite()];
     const [row] = combineDataSets([], invites, 99);
     expect(row.status).toBe("Invite pending");
   });
+
+  it("returns 'No access' for an invite without a role", () => {
+    const invites = [createMockInvite({ global_role: null, teams: [] })];
+    const [row] = combineDataSets([], invites, 99);
+    expect(row.status).toBe("No access");
+  });
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tests.tsx`
around lines 74 - 78, Add a test alongside the existing invite-status test in
UsersTableConfig tests that creates an invite with global_role set to null and
an empty teams array, passes it through combineDataSets, and asserts the
resulting row status is "No access".
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tests.tsx`:
- Around line 74-78: Add a test alongside the existing invite-status test in
UsersTableConfig tests that creates an invite with global_role set to null and
an empty teams array, passes it through combineDataSets, and asserts the
resulting row status is "No access".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a9ef56ee-676b-4f43-b008-6341295ace31

📥 Commits

Reviewing files that changed from the base of the PR and between 53ecfe0 and a386eca.

⛔ Files ignored due to path filters (2)
  • changes/inactive-user-status.md is excluded by !**/*.md
  • docs/REST API/rest-api.md is excluded by !**/*.md
📒 Files selected for processing (13)
  • frontend/__mocks__/userMock.ts
  • frontend/components/StatusIndicator/_styles.scss
  • frontend/interfaces/user.ts
  • frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tests.tsx
  • frontend/pages/admin/ManageUsersPage/components/UsersTable/UsersTableConfig.tsx
  • frontend/test/stubs.ts
  • server/datastore/mysql/migrations/tables/20260713150609_AddLastLoginAtToUsers.go
  • server/datastore/mysql/migrations/tables/20260713150609_AddLastLoginAtToUsers_test.go
  • server/datastore/mysql/schema.sql
  • server/datastore/mysql/sessions.go
  • server/datastore/mysql/sessions_test.go
  • server/datastore/mysql/users.go
  • server/fleet/users.go

Surface last_activity_at (MAX of live sessions' accessed_at, bumped on
every authenticated request) on user API responses, and use the most
recent of last activity / last login in the Inactive check so API-only
accounts are covered too, with an API-specific tooltip. Adds a user_id
index on sessions for the aggregate.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@allenhouchins

Copy link
Copy Markdown
Member Author

API user:
Screenshot 2026-07-13 at 12 09 43 PM

Human user:
Screenshot 2026-07-13 at 12 09 51 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Highlight when Fleet admins and API accounts go stale (no activity in 30+ days)

3 participants