Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add SSO support

Dmitry Abramove265e57f3911
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..8653a3fc
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,29 @@
+# Ensure shell scripts always use LF line endings, even on Windows
+*.sh text eol=lf
+
+# Ensure Python files use LF line endings
+*.py text eol=lf
+
+# Docker files should use LF
+Dockerfile text eol=lf
+docker-compose*.yml text eol=lf
+.dockerignore text eol=lf
+
+# Config files should use LF
+*.example text eol=lf
+*.conf text eol=lf
+*.config text eol=lf
+
+# Documentation uses LF
+*.md text eol=lf
+
+# Binary files
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.ico binary
+*.gif binary
+*.webp binary
+*.db binary
+*.pyc binary
+
diff --git a/config/env.sso.example b/config/env.sso.example
new file mode 100644
index 00000000..418c9d64
--- /dev/null
+++ b/config/env.sso.example
@@ -0,0 +1,32 @@
+###############################################################################
+# SSO (OIDC) Authentication
+###############################################################################
+
+# Enable SSO (Single Sign-On) authentication. Requires discovery URL and client credentials.
+ENABLE_SSO=false
+
+# Display name for the provider (shown in UI button)
+SSO_PROVIDER_NAME=Keycloak
+
+# OIDC client credentials
+SSO_CLIENT_ID=speakr
+SSO_CLIENT_SECRET=change-me
+
+# OIDC discovery document URL (well-known endpoint)
+SSO_DISCOVERY_URL=https://keycloak.example.com/realms/master/.well-known/openid-configuration
+
+# Public redirect URI exposed by Speakr (must be registered in the IdP)
+SSO_REDIRECT_URI=https://speakr.example.com/auth/sso/callback
+
+# Auto-registration settings
+# Allow automatic account creation for new users signing in via SSO.
+SSO_AUTO_REGISTER=true
+
+# Comma-separated list of allowed email domains for auto-registration.
+# Leave empty to allow all domains (e.g., example.com,company.org).
+SSO_ALLOWED_DOMAINS=
+
+# Claims used to map user profile fields
+SSO_DEFAULT_USERNAME_CLAIM=preferred_username
+SSO_DEFAULT_NAME_CLAIM=name
+
diff --git a/docs/admin-guide/sso-setup.md b/docs/admin-guide/sso-setup.md
new file mode 100644
index 00000000..1c29e953
--- /dev/null
+++ b/docs/admin-guide/sso-setup.md
@@ -0,0 +1,95 @@
+# SSO Setup (OIDC)
+
+This guide explains how to enable Single Sign-On (SSO) for Speakr using any OpenID Connect (OIDC) identity provider such as Keycloak, Azure AD/Entra ID, Google, or Auth0.
+
+## Prerequisites
+
+- Speakr server reachable by the IdP at the redirect URL you configure.
+- Client ID and Client Secret issued by your IdP.
+- OIDC discovery (well-known) URL from your IdP.
+
+## Required environment variables
+
+Set these variables (see `config/env.sso.example`):
+
+```
+ENABLE_SSO=true
+SSO_PROVIDER_NAME=Keycloak
+SSO_CLIENT_ID=speakr
+SSO_CLIENT_SECRET=change-me
+SSO_DISCOVERY_URL=https://keycloak.example.com/realms/master/.well-known/openid-configuration
+SSO_REDIRECT_URI=https://speakr.example.com/auth/sso/callback
+
+# Auto-registration (email domain filter)
+SSO_AUTO_REGISTER=true
+SSO_ALLOWED_DOMAINS=example.com,company.org
+
+# Claim mapping (optional)
+SSO_DEFAULT_USERNAME_CLAIM=preferred_username
+SSO_DEFAULT_NAME_CLAIM=name
+```
+
+Restart Speakr after updating environment variables.
+
+## Claim expectations
+
+- `sub` (required): stable subject identifier.
+- `email` (recommended): used for matching and domain allowlist.
+- `preferred_username` or `name`: used for username/full name if provided.
+
+## Keycloak quick start
+
+1. In Keycloak, create a new client (e.g., `speakr`) with:
+ - **Client Type**: OpenID Connect
+ - **Access Type**: Confidential
+ - **Valid Redirect URI**: `https://your-host/auth/sso/callback`
+ - **Web Origins**: `+` (or your domain)
+2. Copy the **Client ID** and **Client Secret**.
+3. Note the **OpenID Endpoint Configuration** (discovery) URL, typically:
+ `https://<host>/realms/<realm>/.well-known/openid-configuration`
+4. Set the environment variables accordingly and restart Speakr.
+
+## Azure AD / Entra ID quick start
+
+1. Create an App Registration.
+2. Add a **Web Redirect URI**: `https://your-host/auth/sso/callback`.
+3. Grant API permissions: `openid`, `profile`, `email`.
+4. Create a client secret.
+5. Discovery URL format:
+ `https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration`
+6. Set variables and restart.
+
+## Google quick start
+
+1. Create OAuth credentials (Web application).
+2. Add authorized redirect URI: `https://your-host/auth/sso/callback`.
+3. Use discovery URL:
+ `https://accounts.google.com/.well-known/openid-configuration`
+4. Set variables and restart.
+
+## Auth0 quick start
+
+1. Create a Regular Web Application.
+2. Allowed Callback URLs: `https://your-host/auth/sso/callback`.
+3. Discovery URL:
+ `https://<your-tenant>.auth0.com/.well-known/openid-configuration`
+4. Set variables and restart.
+
+## Auto-registration behavior
+
+- If `SSO_AUTO_REGISTER=true`, new users are created on first login when their email domain is allowed (or when allowlist is empty).
+- If `SSO_AUTO_REGISTER=false`, only existing users with a linked SSO subject can sign in.
+- Email domain allowlist is enforced only when an email is present.
+
+## Linking existing users
+
+- In **Account > Single Sign-On**, click **Link {PROVIDER} account** while logged in.
+- If the SSO subject is already linked to another user, the link is rejected.
+
+## Troubleshooting
+
+- **Login fails immediately**: verify `SSO_DISCOVERY_URL`, client credentials, and that the redirect URI matches exactly.
+- **User created without email**: some IdPs do not return `email`; user is created with a placeholder email based on `sub`.
+- **Domain rejected**: confirm `SSO_ALLOWED_DOMAINS` and that the IdP returns an `email` claim.
+- **Already linked**: ensure each SSO subject is unique; unlinking is not yet implemented.
+
diff --git a/requirements.txt b/requirements.txt
index dafc15de..a3437f4f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,6 +4,8 @@ flask-login==0.6.3
flask-wtf==1.2.2
flask-bcrypt==1.0.1
Flask-Limiter==3.5.0
+authlib>=1.3.0
+itsdangerous>=2.1.0
email-validator==2.2.0
openai>=2.2.0
pywebpush==1.14.0
diff --git a/src/api/auth.py b/src/api/auth.py
index a72b6e9e..3c8af0f2 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -8,7 +8,7 @@ and password changes.
import os
import re
import mimetypes
-from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, session, current_app
from flask_login import login_user, logout_user, login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
@@ -20,6 +20,16 @@ import markdown
from src.database import db
from src.models import User, SystemSetting, GroupMembership
from src.utils import password_check
+from src.auth.sso import (
+ init_sso_client,
+ is_sso_enabled,
+ get_sso_config,
+ get_sso_client,
+ create_or_update_sso_user,
+ is_domain_allowed,
+ link_sso_to_existing_user,
+ update_user_profile_from_claims,
+)
# Create blueprint
auth_bp = Blueprint('auth', __name__)
@@ -128,19 +138,136 @@ def login():
if current_user.is_authenticated:
return redirect(url_for('recordings.index'))
+ sso_enabled = is_sso_enabled()
+ sso_config = get_sso_config()
+ if sso_enabled:
+ init_sso_client(current_app)
+
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
- if user and bcrypt.check_password_hash(user.password, form.password.data):
- login_user(user, remember=form.remember.data)
- next_page = request.args.get('next')
- if not is_safe_url(next_page):
- return redirect(url_for('recordings.index'))
- return redirect(next_page) if next_page else redirect(url_for('recordings.index'))
+ if user and user.password:
+ if bcrypt.check_password_hash(user.password, form.password.data):
+ login_user(user, remember=form.remember.data)
+ next_page = request.args.get('next')
+ if not is_safe_url(next_page):
+ return redirect(url_for('recordings.index'))
+ return redirect(next_page) if next_page else redirect(url_for('recordings.index'))
+ else:
+ flash('Login unsuccessful. Please check email and password.', 'danger')
+ elif user and not user.password:
+ flash('This account uses SSO login. Please sign in with SSO.', 'warning')
else:
flash('Login unsuccessful. Please check email and password.', 'danger')
- return render_template('login.html', title='Login', form=form)
+ return render_template(
+ 'login.html',
+ title='Login',
+ form=form,
+ sso_enabled=sso_enabled,
+ sso_provider_name=sso_config.get('provider_name', 'SSO')
+ )
+
+
+@auth_bp.route('/auth/sso/login')
+@rate_limit("10 per minute")
+def sso_login():
+ if not is_sso_enabled():
+ flash('SSO is not configured. Please contact the administrator.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ oauth = get_sso_client() or init_sso_client(current_app)
+ if not oauth:
+ flash('Failed to initialize SSO client. Check server logs.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ next_url = request.args.get('next')
+ if next_url and is_safe_url(next_url):
+ session['sso_next'] = next_url
+ else:
+ session.pop('sso_next', None)
+
+ return oauth.sso.authorize_redirect(redirect_uri=get_sso_config().get('redirect_uri'))
+
+
+@auth_bp.route('/auth/sso/callback')
+@rate_limit("20 per minute")
+def sso_callback():
+ if not is_sso_enabled():
+ flash('SSO is not configured. Please contact the administrator.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ oauth = get_sso_client() or init_sso_client(current_app)
+ if not oauth:
+ flash('Failed to initialize SSO client. Check server logs.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ try:
+ token = oauth.sso.authorize_access_token()
+ userinfo = token.get('userinfo') or oauth.sso.userinfo()
+ except Exception as e:
+ current_app.logger.warning(f"SSO callback error: {e}")
+ flash('SSO login failed. Please try again.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ subject = userinfo.get('sub')
+ if not subject:
+ flash('SSO response did not include a subject identifier.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ link_user_id = session.pop('sso_link_user_id', None)
+ next_url = session.pop('sso_next', None)
+ cfg = get_sso_config()
+
+ if link_user_id:
+ target_user = db.session.get(User, int(link_user_id))
+ if not target_user:
+ flash('Could not link account: user not found.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ existing = User.query.filter_by(sso_subject=subject).first()
+ if existing and existing.id != target_user.id:
+ flash('This SSO account is already linked to another user.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ update_user_profile_from_claims(target_user, userinfo)
+ target_user.sso_provider = cfg.get('provider_name', 'SSO')
+ target_user.sso_subject = subject
+ db.session.commit()
+ flash('SSO account linked successfully.', 'success')
+ return redirect(url_for('auth.account'))
+
+ try:
+ user = create_or_update_sso_user(userinfo)
+ except PermissionError as e:
+ flash(str(e), 'danger')
+ return redirect(url_for('auth.login'))
+ except ValueError as e:
+ flash(str(e), 'danger')
+ return redirect(url_for('auth.login'))
+ except Exception as e:
+ current_app.logger.warning(f"SSO login error: {e}")
+ flash('Could not complete SSO login. Please try again.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ login_user(user, remember=True)
+
+ if next_url and is_safe_url(next_url):
+ return redirect(next_url)
+ return redirect(url_for('recordings.index'))
+
+
+@auth_bp.route('/auth/sso/link', methods=['POST'])
+@login_required
+def sso_link():
+ if not is_sso_enabled():
+ flash('SSO is not configured. Please contact the administrator.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ session['sso_link_user_id'] = current_user.id
+ session['sso_next'] = url_for('auth.account')
+
+ return redirect(url_for('auth.sso_login'))
@auth_bp.route('/logout')
@@ -238,6 +365,12 @@ def account():
'name': membership.group.name
})
+ sso_config = get_sso_config()
+ sso_enabled = is_sso_enabled()
+ if sso_enabled:
+ init_sso_client(current_app)
+ sso_linked = bool(current_user.sso_subject)
+
return render_template('account.html',
title='Account',
default_summary_prompt_text=default_summary_prompt_text,
@@ -247,7 +380,11 @@ def account():
user_admin_groups=user_admin_groups,
asr_diarize_locked=asr_diarize_locked,
asr_diarize_env_value=ASR_DIARIZE,
- is_team_admin=is_team_admin)
+ is_team_admin=is_team_admin,
+ sso_enabled=sso_enabled,
+ sso_provider_name=sso_config.get('provider_name', 'SSO'),
+ sso_linked=sso_linked,
+ sso_subject=current_user.sso_subject)
@auth_bp.route('/change_password', methods=['POST'])
diff --git a/src/auth/sso.py b/src/auth/sso.py
new file mode 100644
index 00000000..d28ccd4f
--- /dev/null
+++ b/src/auth/sso.py
@@ -0,0 +1,187 @@
+import os
+import re
+from typing import Dict, Optional
+
+from authlib.integrations.flask_client import OAuth
+from flask import current_app
+
+from src.database import db
+from src.models import User
+
+# Keep a single OAuth client instance
+_oauth: Optional[OAuth] = None
+
+
+def _str_to_bool(value: str) -> bool:
+ return str(value or "").lower() == "true"
+
+
+def get_sso_config() -> Dict[str, Optional[str]]:
+ """Load SSO configuration from environment variables."""
+ return {
+ "enabled": _str_to_bool(os.environ.get("ENABLE_SSO", "false")),
+ "provider_name": os.environ.get("SSO_PROVIDER_NAME", "SSO"),
+ "client_id": os.environ.get("SSO_CLIENT_ID"),
+ "client_secret": os.environ.get("SSO_CLIENT_SECRET"),
+ "discovery_url": os.environ.get("SSO_DISCOVERY_URL"),
+ "redirect_uri": os.environ.get("SSO_REDIRECT_URI"),
+ "auto_register": _str_to_bool(os.environ.get("SSO_AUTO_REGISTER", "true")),
+ "allowed_domains": os.environ.get("SSO_ALLOWED_DOMAINS"),
+ "username_claim": os.environ.get("SSO_DEFAULT_USERNAME_CLAIM", "preferred_username"),
+ "name_claim": os.environ.get("SSO_DEFAULT_NAME_CLAIM", "name"),
+ }
+
+
+def is_sso_enabled() -> bool:
+ cfg = get_sso_config()
+ return bool(
+ cfg["enabled"]
+ and cfg["client_id"]
+ and cfg["client_secret"]
+ and cfg["discovery_url"]
+ and cfg["redirect_uri"]
+ )
+
+
+def init_sso_client(app) -> Optional[OAuth]:
+ """Initialize OAuth client if SSO is enabled."""
+ global _oauth
+ if not is_sso_enabled():
+ return None
+
+ if _oauth:
+ return _oauth
+
+ cfg = get_sso_config()
+ oauth = OAuth(app)
+ oauth.register(
+ name="sso",
+ server_metadata_url=cfg["discovery_url"],
+ client_id=cfg["client_id"],
+ client_secret=cfg["client_secret"],
+ client_kwargs={"scope": "openid email profile"},
+ )
+ _oauth = oauth
+ app.logger.info("SSO client initialized with discovery URL %s", cfg["discovery_url"])
+ return _oauth
+
+
+def get_sso_client() -> Optional[OAuth]:
+ """Return initialized OAuth client or None."""
+ return _oauth
+
+
+def is_domain_allowed(email: Optional[str]) -> bool:
+ """Check if email domain is allowed for auto-registration."""
+ if not email:
+ return False
+ cfg = get_sso_config()
+ domains_env = cfg["allowed_domains"]
+ if not domains_env:
+ return True # no restriction
+
+ allowed = [d.strip().lower() for d in domains_env.split(",") if d.strip()]
+ if not allowed:
+ return True
+
+ parts = email.lower().rsplit("@", 1)
+ if len(parts) != 2:
+ return False
+ domain = parts[1]
+ return domain in allowed
+
+
+def _sanitize_username(candidate: str) -> str:
+ sanitized = re.sub(r"[^a-zA-Z0-9._-]", "", candidate or "")
+ return sanitized or "user"
+
+
+def generate_unique_username(preferred: Optional[str]) -> str:
+ """Generate a unique username based on preferred value."""
+ base = _sanitize_username(preferred or "user")
+ base = base[:20]
+
+ suffix = 0
+ candidate = base
+ while User.query.filter_by(username=candidate).first():
+ suffix += 1
+ candidate = f"{base[:18]}{suffix:02d}"
+ return candidate
+
+
+def create_or_update_sso_user(userinfo: Dict[str, str]) -> User:
+ """Create or update a user from SSO (OIDC) claims."""
+ cfg = get_sso_config()
+ subject = userinfo.get("sub")
+ email = userinfo.get("email")
+ username_claim = cfg["username_claim"]
+ name_claim = cfg["name_claim"]
+
+ if not subject:
+ raise ValueError("SSO userinfo does not include 'sub'")
+
+ if not cfg["auto_register"] and not User.query.filter_by(sso_subject=subject).first():
+ raise PermissionError("SSO auto-registration is disabled")
+
+ if email and not is_domain_allowed(email):
+ raise PermissionError("Email domain is not allowed for SSO sign-up")
+
+ # Existing by subject
+ user = User.query.filter_by(sso_subject=subject).first()
+ if user:
+ _update_profile_fields(user, userinfo, name_claim)
+ db.session.commit()
+ return user
+
+ # Existing by email: attach SSO
+ if email:
+ existing_email_user = User.query.filter_by(email=email).first()
+ if existing_email_user:
+ existing_email_user.sso_provider = cfg["provider_name"]
+ existing_email_user.sso_subject = subject
+ _update_profile_fields(existing_email_user, userinfo, name_claim)
+ db.session.commit()
+ return existing_email_user
+
+ # Create new user
+ preferred_username = userinfo.get(username_claim) or (email.split("@")[0] if email else None)
+ username = generate_unique_username(preferred_username)
+ name_value = userinfo.get(name_claim) if name_claim else userinfo.get("name")
+
+ user = User(
+ username=username,
+ email=email or f"{subject}@placeholder.local",
+ password=None,
+ sso_provider=cfg["provider_name"],
+ sso_subject=subject,
+ name=name_value,
+ )
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def _update_profile_fields(user: User, userinfo: Dict[str, str], name_claim: Optional[str]) -> None:
+ """Update optional profile fields from SSO claims."""
+ if not user.email and userinfo.get("email"):
+ user.email = userinfo["email"]
+ if name_claim and userinfo.get(name_claim):
+ user.name = userinfo[name_claim]
+
+
+def update_user_profile_from_claims(user: User, userinfo: Dict[str, str]) -> None:
+ """Expose profile update for external callers (e.g., account linking)."""
+ cfg = get_sso_config()
+ _update_profile_fields(user, userinfo, cfg["name_claim"])
+
+
+def link_sso_to_existing_user(user: User, provider: str, subject: str) -> User:
+ """Link SSO identity to an existing user account."""
+ if user.sso_subject and user.sso_subject != subject:
+ raise ValueError("Account already linked to another SSO identity")
+
+ user.sso_provider = provider
+ user.sso_subject = subject
+ db.session.commit()
+ return user
+
diff --git a/src/init_db.py b/src/init_db.py
index 4ba41a81..ae9ea1ff 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -73,6 +73,10 @@ def initialize_database(app):
app.logger.info("Added diarize column to user table")
if add_column_if_not_exists(engine, 'user', 'ui_language', 'VARCHAR(10) DEFAULT "en"'):
app.logger.info("Added ui_language column to user table")
+ if add_column_if_not_exists(engine, 'user', 'sso_provider', 'VARCHAR(100)'):
+ app.logger.info("Added sso_provider column to user table")
+ if add_column_if_not_exists(engine, 'user', 'sso_subject', 'VARCHAR(255)'):
+ app.logger.info("Added sso_subject column to user table")
if add_column_if_not_exists(engine, 'recording', 'mime_type', 'VARCHAR(100)'):
app.logger.info("Added mime_type column to recording table")
if add_column_if_not_exists(engine, 'recording', 'completed_at', 'DATETIME'):
@@ -374,6 +378,19 @@ def initialize_database(app):
except Exception as e:
app.logger.warning(f"Could not create speaker_name indexes: {e}")
+ # Add unique index for SSO subject to prevent duplicate linking
+ try:
+ inspector = inspect(engine)
+ if 'user' in inspector.get_table_names():
+ existing_indexes = [idx['name'] for idx in inspector.get_indexes('user')]
+ if 'ix_user_sso_subject' not in existing_indexes:
+ with engine.connect() as conn:
+ conn.execute(text('CREATE UNIQUE INDEX IF NOT EXISTS ix_user_sso_subject ON user (sso_subject)'))
+ conn.commit()
+ app.logger.info("Created unique index ix_user_sso_subject on user.sso_subject")
+ except Exception as e:
+ app.logger.warning(f"Could not create unique index on user.sso_subject: {e}")
+
# Initialize default system settings
if not SystemSetting.query.filter_by(key='transcript_length_limit').first():
SystemSetting.set_setting(
diff --git a/src/models/user.py b/src/models/user.py
index 199703dc..7ac35519 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -16,7 +16,9 @@ class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
- password = db.Column(db.String(60), nullable=False)
+ password = db.Column(db.String(60), nullable=True)
+ sso_provider = db.Column(db.String(100), nullable=True)
+ sso_subject = db.Column(db.String(255), unique=True, nullable=True)
is_admin = db.Column(db.Boolean, default=False)
can_share_publicly = db.Column(db.Boolean, default=True) # Permission to create public share links
recordings = db.relationship('Recording', backref='owner', lazy=True)
diff --git a/templates/account.html b/templates/account.html
index 455eefb7..2ebf80ed 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -591,6 +591,38 @@
</div>
</div>
</div>
+
+ {% if sso_enabled %}
+ <div class="mt-6">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Single Sign-On</h3>
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] space-y-3">
+ <div class="flex items-center justify-between">
+ <div>
+ <span class="block text-sm font-medium text-[var(--text-muted)]">Provider</span>
+ <span class="block text-[var(--text-primary)]">{{ sso_provider_name }}</span>
+ </div>
+ {% if sso_linked %}
+ <span class="px-2 py-1 text-xs rounded bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">Linked</span>
+ {% else %}
+ <span class="px-2 py-1 text-xs rounded bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]">Not linked</span>
+ {% endif %}
+ </div>
+
+ {% if sso_linked %}
+ <div class="text-xs text-[var(--text-muted)] break-all">
+ <span class="font-medium text-[var(--text-secondary)]">Subject:</span> {{ sso_subject }}
+ </div>
+ {% else %}
+ <form method="POST" action="{{ url_for('auth.sso_link') }}" class="mt-2">
+ <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+ <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-link mr-2"></i> Link {{ sso_provider_name }} account
+ </button>
+ </form>
+ {% endif %}
+ </div>
+ </div>
+ {% endif %}
<div class="mt-6"> <!-- Added mt-6 for spacing, was mt-8 on Account Actions -->
<h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2" data-i18n="account.accountActions">Account Actions</h3>
diff --git a/templates/login.html b/templates/login.html
index 4af4d1cd..5f601c30 100644
--- a/templates/login.html
+++ b/templates/login.html
@@ -75,6 +75,19 @@
{% endif %}
{% endwith %}
+ {% if sso_enabled %}
+ <div class="flex flex-col space-y-3 mb-6">
+ <a href="{{ url_for('auth.sso_login') }}" class="w-full inline-flex items-center justify-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-cloud mr-2"></i> Sign in with {{ sso_provider_name }}
+ </a>
+ <div class="flex items-center text-xs text-[var(--text-muted)]">
+ <span class="flex-grow border-t border-[var(--border-secondary)]"></span>
+ <span class="mx-3 uppercase tracking-wide">or</span>
+ <span class="flex-grow border-t border-[var(--border-secondary)]"></span>
+ </div>
+ </div>
+ {% endif %}
+
<form method="POST" action="{{ url_for('auth.login') }}">
{{ form.hidden_tag() }}