Skip to content

Env vars for OIDC setup#737

Merged
CodeWithCJ merged 24 commits intoCodeWithCJ:mainfrom
nikpcenicni:OIDC-env
Feb 25, 2026
Merged

Env vars for OIDC setup#737
CodeWithCJ merged 24 commits intoCodeWithCJ:mainfrom
nikpcenicni:OIDC-env

Conversation

@nikpcenicni
Copy link
Contributor

Environment Variables for OIDC Setup

Overview

This PR adds support for configuring OIDC (OpenID Connect) authentication entirely via environment variables, so deployments can use a single IdP without requiring an initial email/password signup or manual admin configuration. Auth behavior (enable/disable email login, enable OIDC, auto-redirect) and an optional env-configured OIDC provider are driven by env vars, with optional OIDC group-based admin role sync.

Features

1. OIDC Provider from Environment

  • Startup upsert: When SPARKY_FITNESS_OIDC_ISSUER_URL, SPARKY_FITNESS_OIDC_CLIENT_ID, SPARKY_FITNESS_OIDC_CLIENT_SECRET, and SPARKY_FITNESS_OIDC_PROVIDER_SLUG are set, the server creates or updates an OIDC provider at startup and registers it with the existing SSO/Better Auth flow.
  • Service: utils/oidcEnvConfig.js reads env, normalizes issuer URL, and calls oidcProviderRepository to upsert the provider; SparkyFitnessServer.js runs this after migrations.
  • Provider identity: Env-configured providers are stored with is_env_configured: true in additional_config so the admin UI can show a “Managed by Env” badge and restrict deletion/editing of credentials.

2. Global Auth Settings and Env Overrides

  • Global settings repository: globalSettingsRepository.getGlobalSettings() applies env overrides before returning:
    • SPARKY_FITNESS_DISABLE_EMAIL_LOGIN=trueenable_email_password_login = false
    • SPARKY_FITNESS_FORCE_EMAIL_LOGIN=trueenable_email_password_login = true (fail-safe; wins over disable)
    • SPARKY_FITNESS_OIDC_AUTH_ENABLED=trueis_oidc_active = true
  • Flags: is_email_login_env_configured and is_oidc_active_env_configured indicate when the value came from env so the admin UI can reflect that.

3. Public Auth Settings and Auto-Redirect

  • Endpoint: GET /api/auth/settings returns login options for the frontend: email enabled/disabled, OIDC enabled, list of active OIDC providers (id, display_name, logo_url, auto_register), and auto_redirect.
  • Env for auto-redirect: SPARKY_FITNESS_OIDC_AUTO_REDIRECT=true sets oidc.auto_redirect in the response. The login page auto-redirects to the single OIDC provider only when auto_redirect is true, email login is disabled, and exactly one provider is active.

4. OIDC Group Sync and Admin Role

  • Session hook: In auth.js, the Better Auth session.create.after hook runs after session creation. When SPARKY_FITNESS_OIDC_ADMIN_GROUP is set, it calls oidcGroupSync.syncUserGroups() with the user id and that group name.
  • Group sync: utils/oidcGroupSync.js reads the user’s OIDC account id_token, decodes the groups claim, and promotes the user to admin if the admin group is present, or revokes admin if not. This keeps SparkyFitness admin role in sync with IdP groups.
  • Optional: SPARKY_FITNESS_OIDC_USER_GROUP is documented for IdP configuration (e.g. which group denotes standard users); role sync currently uses only the admin group.

5. Database and Better Auth Adapter

  • Migration: 20260221210000_oidc_config_jsonb.sql changes sso_provider.oidc_config from text to JSONB so the Better Auth adapter receives an object and avoids “invalid_provider” when using the OIDC plugin.
  • Repository: oidcProviderRepository creates/updates providers with a JSONB oidc_config object (issuer, clientId, clientSecret, scopes, discoveryEndpoint, redirectURI, endpoints, etc.) and continues to store display/UI options in additional_config (including is_env_configured).

6. Frontend

  • Types: LoginSettings in types/auth.d.ts includes oidc.auto_redirect?: boolean and OidcProvider includes auto_register.
  • Auth page: Uses GET /api/auth/settings; when oidc.auto_redirect is true, email is disabled, and there is exactly one OIDC provider, it auto-redirects to that provider after a short delay.
  • Admin OIDC settings: Providers returned by the admin API include is_env_configured. The admin table shows a “Managed by Env” badge for such providers and hides the delete button for them (edit remains for display/logo/behavior; credentials are managed via env).

Environment Variables

Variable Purpose
SPARKY_FITNESS_DISABLE_EMAIL_LOGIN Set to true to disable email/password login (overridden by SPARKY_FITNESS_FORCE_EMAIL_LOGIN).
SPARKY_FITNESS_FORCE_EMAIL_LOGIN Set to true to force email login on (fail-safe if OIDC is misconfigured).
SPARKY_FITNESS_OIDC_AUTH_ENABLED Set to true to enable OIDC login (overrides DB admin setting).
SPARKY_FITNESS_OIDC_ISSUER_URL Issuer URL (e.g. https://auth.example.com). Discovery URL is derived as issuer + /.well-known/openid-configuration. Required for env provider upsert.
SPARKY_FITNESS_OIDC_CLIENT_ID OIDC client ID. Required for env provider upsert.
SPARKY_FITNESS_OIDC_CLIENT_SECRET OIDC client secret. Required for env provider upsert.
SPARKY_FITNESS_OIDC_PROVIDER_SLUG URL-safe provider id (e.g. my-idp). Required for env provider upsert.
SPARKY_FITNESS_OIDC_PROVIDER_NAME Display name for the provider (optional; defaults to slug).
SPARKY_FITNESS_OIDC_AUTO_REDIRECT Set to true to allow auto-redirect to the single OIDC provider when email login is disabled.
SPARKY_FITNESS_OIDC_ADMIN_GROUP IdP group/claim value that grants admin role; sync runs on session create.
SPARKY_FITNESS_OIDC_USER_GROUP Documented for IdP user group (e.g. for mapping); used for reference in docs.
SPARKY_FITNESS_OIDC_SCOPE Space-separated scopes (optional; default openid email profile).
SPARKY_FITNESS_OIDC_AUTO_REGISTER Set to true to auto-create user on first OIDC login (optional; default true).
SPARKY_FITNESS_OIDC_LOGO_URL Logo URL for the provider (optional).
SPARKY_FITNESS_OIDC_DOMAIN Organization domain (optional; default {slug}.env).
SPARKY_FITNESS_OIDC_TOKEN_AUTH_METHOD Token endpoint auth method (optional; default client_secret_post).
SPARKY_FITNESS_OIDC_ID_TOKEN_SIGNED_ALG ID token signing algorithm (optional; default RS256).
SPARKY_FITNESS_OIDC_USERINFO_SIGNED_ALG UserInfo signing algorithm (optional; default none).
SPARKY_FITNESS_OIDC_TIMEOUT Request timeout in ms (optional; default 30000).

Note: The issue requested OIDC_CONFIGURATION_URL; this implementation uses OIDC_ISSUER_URL and derives the discovery URL as {issuer}/.well-known/openid-configuration, which is standard and avoids redundancy.

Database Migrations

  • 20260221210000_oidc_config_jsonb.sql: Converts sso_provider.oidc_config from text to JSONB for Better Auth OIDC adapter compatibility.

API Changes

Modified Endpoints

  • GET /api/auth/settings (public): Now returns email.enabled, oidc.enabled, oidc.providers (id, display_name, logo_url, auto_register), and oidc.auto_redirect (from SPARKY_FITNESS_OIDC_AUTO_REDIRECT).

Unchanged

  • Admin OIDC CRUD and logo upload unchanged; responses already include fields from additional_config (e.g. is_env_configured when set by env upsert).

Frontend Changes

  • src/types/auth.d.ts: LoginSettings.oidc extended with auto_redirect?: boolean.
  • src/api/Auth/auth.ts: getLoginSettings() fetches /api/auth/settings; response typing matches new shape.
  • src/pages/Auth/Auth.tsx: Auto-redirect only when loginSettings.oidc.auto_redirect is true, email login is disabled, and exactly one OIDC provider is active.
  • src/pages/Admin/OidcSettings.tsx: Shows “Managed by Env” badge for providers with is_env_configured; delete button hidden for those providers.
  • src/api/Admin/oidcSettingsService.ts: OidcProvider type includes is_env_configured?: boolean.

Testing

  • SparkyFitnessServer/tests/oidcEnvConfig.test.js: Tests for getEnvOidcConfig() (required vars, optional vars, issuer normalization).
  • SparkyFitnessServer/tests/oidcGroupSync.test.js: Tests for group sync (admin grant/revoke based on groups claim).
  • SparkyFitnessServer/tests/globalSettingsRepository.test.js: Updated for env overrides in getGlobalSettings().
  • SparkyFitnessServer/tests/oidcProviderRepository.test.js: Updated for JSONB oidc_config and is_env_configured in config.

Documentation

  • docker/.env.example: Commented block for OIDC (DISABLE_EMAIL_LOGIN, OIDC_AUTH_ENABLED, ISSUER_URL, CLIENT_ID, CLIENT_SECRET, PROVIDER_SLUG/NAME, SCOPE, AUTO_REGISTER, LOGO_URL, DOMAIN, AUTO_REDIRECT, ADMIN_GROUP, USER_GROUP, and advanced options).
  • docs/content/1.install/4.environment-variables.md: OIDC section updated to list all env vars and describe env-configured provider upsert, auth overrides, auto-redirect, and group-based admin sync.

Breaking Changes

None. Existing behavior is preserved:

  • If no OIDC env vars are set, no provider is upserted and admin-configured OIDC continues to work.
  • Global auth settings from the database are still used when env overrides are not set.
  • sso_provider.oidc_config migration is backward-compatible (existing text values are cast to JSONB where applicable).

Migration Notes

  1. Run the migration 20260221210000_oidc_config_jsonb.sql before or with this release.
  2. To use OIDC entirely from env: set SPARKY_FITNESS_OIDC_ISSUER_URL, SPARKY_FITNESS_OIDC_CLIENT_ID, SPARKY_FITNESS_OIDC_CLIENT_SECRET, SPARKY_FITNESS_OIDC_PROVIDER_SLUG, and optionally SPARKY_FITNESS_OIDC_AUTH_ENABLED=true, SPARKY_FITNESS_DISABLE_EMAIL_LOGIN=true, SPARKY_FITNESS_OIDC_AUTO_REDIRECT=true, SPARKY_FITNESS_OIDC_ADMIN_GROUP=your_admin_group.
  3. Keep SPARKY_FITNESS_FORCE_EMAIL_LOGIN=true during testing if you need a fallback to email login.

Related Issues

Closes #598

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @nikpcenicni, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the authentication system by allowing comprehensive configuration of OpenID Connect (OIDC) providers and global authentication settings through environment variables. This change streamlines deployments, particularly for single Identity Provider (IdP) setups, by automating OIDC provider registration and enabling dynamic control over login options and user role synchronization based on IdP groups. The update also includes necessary database schema adjustments and frontend UI improvements to reflect environment-managed settings.

Highlights

  • OIDC Provider Configuration via Environment Variables: Added support to configure OIDC providers entirely through environment variables, enabling automatic upsertion at server startup without manual database intervention.
  • Global Authentication Settings Overrides: Implemented environment variable overrides for global authentication settings, such as enabling/disabling email login and OIDC authentication, providing centralized control.
  • OIDC Group-Based Admin Role Synchronization: Introduced a mechanism to synchronize user roles (specifically admin status) with OIDC groups from the Identity Provider's (IdP) 'id_token' claim upon session creation.
  • Frontend UI Enhancements for Environment-Managed Settings: Updated the admin user interface to display 'Managed by Env' badges for environment-configured OIDC providers and disable editing or deletion of certain fields to prevent conflicts.
  • Database Schema Update for OIDC Configuration: Migrated the 'sso_provider.oidc_config' column from 'text' to 'JSONB' to ensure better compatibility and direct object handling with the Better Auth adapter.
  • Login Page Auto-Redirection Logic: Enhanced the login page to support automatic redirection to a single OIDC provider when configured via environment variables, email login is disabled, and only one OIDC provider is active.
Changelog
  • SparkyFitnessFrontend/src/api/Admin/globalSettingsService.ts
    • Added 'is_email_login_env_configured' and 'is_oidc_active_env_configured' properties to the 'GlobalSettings' interface.
  • SparkyFitnessFrontend/src/api/Admin/oidcSettingsService.ts
    • Added 'is_env_configured' property to the 'OidcProvider' interface.
  • SparkyFitnessFrontend/src/pages/Admin/AuthenticationSettings.tsx
    • Imported the 'Badge' component.
    • Displayed 'Managed by Env' badges and disabled switches for email and OIDC login if environment-configured.
  • SparkyFitnessFrontend/src/pages/Admin/OidcProviderDialog.tsx
    • Imported the 'Badge' component.
    • Displayed 'Managed by Env' badge and a notice for environment-configured providers.
    • Disabled various input fields ('provider_id', 'display_name', 'is_active', 'auto_register', 'logo_file', 'issuer_url', 'domain', 'client_id', 'client_secret', 'scope', 'token_endpoint_auth_method', 'signing_algorithm', 'profile_signing_algorithm', 'timeout') if the provider is environment-configured.
    • Updated the client secret placeholder text for environment-managed secrets.
  • SparkyFitnessFrontend/src/pages/Admin/OidcSettings.tsx
    • Imported the 'Badge' component.
    • Displayed 'Managed by Env' badges next to provider names in the OIDC providers table.
    • Hid the delete button for environment-configured OIDC providers.
  • SparkyFitnessFrontend/src/pages/Auth/Auth.tsx
    • Modified auto-redirect logic to also check 'loginSettings.oidc.auto_redirect' in addition to email being disabled and a single OIDC provider.
  • SparkyFitnessFrontend/src/types/auth.d.ts
    • Added 'auto_redirect' property to the 'LoginSettings.oidc' interface.
  • SparkyFitnessServer/SparkyFitnessServer.js
    • Added logic to call 'upsertEnvOidcProvider' from 'utils/oidcEnvConfig' after migrations, to configure OIDC from environment variables at startup.
  • SparkyFitnessServer/auth.js
    • Added a 'session.create.after' hook to synchronize user roles with OIDC groups using 'utils/oidcGroupSync' if 'SPARKY_FITNESS_OIDC_ADMIN_GROUP' is set.
  • SparkyFitnessServer/db/migrations/20260221210000_oidc_config_jsonb.sql
    • Added a new migration script to alter the 'sso_provider.oidc_config' column type from 'text' to 'JSONB'.
  • SparkyFitnessServer/models/globalSettingsRepository.js
    • Modified 'getGlobalSettings' to apply environment variable overrides for 'enable_email_password_login' and 'is_oidc_active', and added 'is_email_login_env_configured' and 'is_oidc_active_env_configured' flags.
    • Modified 'saveGlobalSettings' to return the full truth (DB + ENV overrides) after saving.
  • SparkyFitnessServer/models/oidcProviderRepository.js
    • Modified 'fetchOidcEndpoints' to include 'issuer' in the returned endpoints.
    • Updated 'getOidcProviderById' to normalize the issuer URL by removing trailing slashes before constructing the discovery URL.
    • Modified 'createOidcProvider' and 'updateOidcProvider' to store 'oidc_config' as a JSONB object (instead of stringified JSON) and to include 'is_env_configured' in 'additional_config'.
    • Normalized issuer URL and constructed 'redirectURI' more robustly in 'createOidcProvider' and 'updateOidcProvider'.
  • SparkyFitnessServer/routes/auth/authCoreRoutes.js
    • Updated '/api/auth/settings' endpoint to use global settings with environment overrides and to include 'oidc.auto_redirect' in the response.
    • Adjusted error fallback logic to reflect environment variable states for email and OIDC enabled status.
  • SparkyFitnessServer/tests/oidcEnvConfig.test.js
    • Added a new test file for the 'oidcEnvConfig' utility, covering required environment variables, default scopes, and optional configuration fields.
  • SparkyFitnessServer/tests/oidcGroupSync.test.js
    • Added a new test file for the 'oidcGroupSync' utility, testing admin role promotion/revocation based on OIDC group claims.
  • SparkyFitnessServer/tests/oidcProviderRepository.test.js
    • Added tests to ensure 'is_env_configured' is correctly persisted in 'additional_config' during OIDC provider creation and update.
  • SparkyFitnessServer/utils/oidcEnvConfig.js
    • Added a new utility file containing 'getEnvOidcConfig' to parse OIDC configuration from environment variables and 'upsertEnvOidcProvider' to create/update OIDC providers in the database based on these variables.
  • SparkyFitnessServer/utils/oidcGroupSync.js
    • Added a new utility file containing 'syncUserGroups' to read OIDC 'id_token' claims and update user roles (admin/user) based on configured group names.
  • docker/.env.example
    • Added a new section for OIDC authentication configuration environment variables, including 'DISABLE_EMAIL_LOGIN', 'OIDC_AUTH_ENABLED', 'ISSUER_URL', 'CLIENT_ID', 'CLIENT_SECRET', 'PROVIDER_SLUG/NAME', 'SCOPE', 'AUTO_REGISTER', 'LOGO_URL', 'DOMAIN', 'AUTO_REDIRECT', 'ADMIN_GROUP', 'USER_GROUP', and advanced options.
  • docs/content/1.install/4.environment-variables.md
    • Updated documentation to include a new section detailing all OIDC-related environment variables and their purposes.
Activity
  • No human activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive and well-structured feature for configuring OIDC entirely through environment variables. The changes span the backend, frontend, database, and documentation, providing a complete solution. The frontend updates to indicate environment-managed settings are a great user experience improvement. I've identified a critical issue in how OIDC configuration is saved to the database which would likely prevent the feature from working as intended, a high-severity security concern in the new JWT parsing logic, and a medium-severity opportunity for refactoring to improve maintainability. After addressing these points, this will be an excellent addition to the project.

endpoints.userInfoEndpoint,
config,
oidcConfig
JSON.stringify(oidcConfig)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

Using JSON.stringify(oidcConfig) here will store a JSON string in the oidc_config JSONB column, rather than a JSON object. The better-auth OIDC plugin expects a parsed object, and this was the motivation for migrating the column to JSONB. Storing it as a string will likely cause the OIDC flow to fail with an invalid_provider error.

The node-postgres (pg) driver automatically handles serializing JavaScript objects to JSON when the target column is JSON or JSONB. You should pass the oidcConfig object directly.

Suggested change
JSON.stringify(oidcConfig)
oidcConfig

endpoints.userInfoEndpoint,
config,
oidcConfig,
JSON.stringify(oidcConfig),
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

Similar to the createOidcProvider function, using JSON.stringify(oidcConfig) here is incorrect for a JSONB column. This will store a JSON string instead of an object, which will likely break the OIDC integration with better-auth. Please pass the oidcConfig object directly to the query; the pg driver will handle serialization.

Suggested change
JSON.stringify(oidcConfig),
oidcConfig,

Comment on lines +28 to +35
const idToken = oidcAccount.id_token;
const parts = idToken.split('.');
if (parts.length < 2) return;

const payloadBase64 = parts[1];
if (payloadBase64) {
// Use Buffer to decode base64url or base64
const payload = JSON.parse(Buffer.from(payloadBase64, 'base64').toString());
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Manually parsing the JWT payload is unsafe and not robust.

  1. Security Risk: The token's signature is not verified. An attacker who can tamper with the id_token in the database could escalate their privileges.
  2. Incorrect Decoding: JWTs use Base64Url encoding. Buffer.from(..., 'base64') expects standard Base64 and can fail.

Please use a dedicated library like jwt-decode for safe decoding. You will need to add it to your package.json. For production, you should consider full signature verification using a library like jsonwebtoken.

Example with jwt-decode:

const { jwtDecode } = require('jwt-decode');

// ... inside syncUserGroups ...
if (oidcAccount?.id_token) {
    try {
        const payload = jwtDecode(oidcAccount.id_token);
        const groups = payload.groups || [];
        // ... rest of your logic
    } catch (e) {
        console.error('Failed to decode token', e);
    }
}

const oidcConfig = JSON.stringify({
issuer: providerData.issuer_url,
// Construct native oidcConfig for Better Auth (object for JSONB column; same base as auth.baseURL)
const baseUrl = (process.env.SPARKY_FITNESS_FRONTEND_URL?.startsWith('http') ? process.env.SPARKY_FITNESS_FRONTEND_URL : `https://${process.env.SPARKY_FITNESS_FRONTEND_URL || 'http://localhost:8080'}`).replace(/\/$/, '');
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This complex line for constructing the baseUrl is duplicated in updateOidcProvider (line 240). To improve maintainability and reduce redundancy, consider extracting this logic into a shared helper function.
For example:

function getBaseUrl() {
    const frontendUrl = process.env.SPARKY_FITNESS_FRONTEND_URL || 'http://localhost:8080';
    const urlWithProtocol = frontendUrl.startsWith('http') ? frontendUrl : `https://${frontendUrl}`;
    return urlWithProtocol.replace(/\/$/, '');
}

@nikpcenicni nikpcenicni marked this pull request as draft February 24, 2026 07:18
…r OIDC provider repository to use getBaseUrl function for URL handling
@nikpcenicni
Copy link
Contributor Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces comprehensive support for configuring OIDC authentication via environment variables, which significantly improves deployment flexibility and automation. The implementation correctly handles startup provider upserts, global settings overrides, and adds a useful group-based admin role synchronization feature. The changes are well-integrated into the existing architecture, following established repository and service patterns. I have identified a few issues regarding security and robustness in the group synchronization logic and environment variable parsing that should be addressed.

if (oidcAccount?.id_token) {
try {
const payload = jwtDecode(oidcAccount.id_token);
const groups = payload.groups || [];
Copy link
Contributor

Choose a reason for hiding this comment

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

security-high high

The current implementation of the group check is vulnerable to substring matching if the groups claim in the ID token is returned as a string instead of an array. For example, if the adminGroup is set to 'admin' and the user's groups claim is 'superadmin', the includes method on a string will return true, leading to unintended privilege escalation. Ensuring the claim is treated as an array (or an element of one) prevents this issue.

Suggested change
const groups = payload.groups || [];
const groupsClaim = payload.groups || [];
const groups = Array.isArray(groupsClaim) ? groupsClaim : [groupsClaim];

Comment on lines +18 to +19
'SELECT provider_id, id_token FROM "account" WHERE user_id = $1',
[userId]
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

When a user has multiple OIDC accounts linked, the current logic picks the first one found in the database to perform group synchronization. This can lead to inconsistent behavior if different providers have different group claims. It is recommended to sort the accounts by their last update time to ensure the synchronization is based on the most recently used (and likely currently active) OIDC provider.

        const { rows: allAccounts } = await pool.query(
            'SELECT provider_id, id_token FROM "account" WHERE user_id = $1 ORDER BY updated_at DESC',

token_endpoint_auth_method: tokenAuthMethod || 'client_secret_post',
signing_algorithm: idTokenAlg || 'RS256',
profile_signing_algorithm: userInfoAlg || 'none',
timeout: timeout ? parseInt(timeout, 10) : 30000,
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The parseInt function can return NaN if the environment variable contains an invalid numeric string. Storing NaN in the configuration could lead to unexpected behavior or crashes in downstream components (e.g., network request timeouts). Providing a fallback to the default value when parsing fails improves the robustness of the configuration loading.

Suggested change
timeout: timeout ? parseInt(timeout, 10) : 30000,
timeout: Number.parseInt(timeout, 10) || 30000,

…nt and properly parse group claims, and improve OIDC timeout handling.
@CodeWithCJ
Copy link
Owner

What hap? Will you be resubmitting again?

@nikpcenicni
Copy link
Contributor Author

Accidentally closed it, and realized there were still a few issues. Negative side effects of coding too late at night. Will resubmit this Pr this evening, Or reopen it depending on your preference

…gging in `oidcGroupSync.js`, and simplify OIDC provider updates in `oidcEnvConfig.js`.
@nikpcenicni nikpcenicni reopened this Feb 25, 2026
@nikpcenicni nikpcenicni marked this pull request as ready for review February 25, 2026 01:22
@nikpcenicni
Copy link
Contributor Author

/gemini review
/gemini summary

@gemini-code-assist
Copy link
Contributor

Hello @nikpcenicni, I see you've requested a new review and summary for this pull request. The system will process these commands shortly and provide updated feedback based on the current state of your changes.

@nikpcenicni
Copy link
Contributor Author

@CodeWithCJ Should be good to go now, let me know if there's any changes you want implemented or if you have any questions

@CodeWithCJ
Copy link
Owner

@nikpcenicni Could you check this.

image

…ted SSO providers post-database initialization in `SparkyFitnessServer.js`
nikpcenicni and others added 8 commits February 24, 2026 22:46
…js` to prevent potential errors during SSO synchronization

Co-authored-by: Cursor <cursoragent@cursor.com>
…nment-variables.md` for improved readability and consistency
…ronment-variables.md`, including password change implications and new database host/port settings
…on to improve readability and maintainability
…rigins and database hooks to enhance readability and maintainability
…itnessServer.js`, including improved sync handling for trusted providers
@nikpcenicni
Copy link
Contributor Author

nikpcenicni commented Feb 25, 2026

IDE had messed up the formatting which was causing some messy conflicts, took a bit to resolve them.

@CodeWithCJ CodeWithCJ merged commit 1dc65bd into CodeWithCJ:main Feb 25, 2026
7 checks passed
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.

[Feature]: Env vars for OIDC setup

2 participants