Add SSO login options to desktop app (#4954)

# Description of Changes
Add SSO login options to desktop app
This commit is contained in:
James Brunton
2025-11-25 11:56:25 +00:00
committed by GitHub
parent 2534c532b7
commit 64d343b765
12 changed files with 753 additions and 29 deletions
@@ -1,6 +1,10 @@
import React, { useState } from 'react';
import { Stack, TextInput, PasswordInput, Button, Text } from '@mantine/core';
import { Stack, TextInput, PasswordInput, Button, Text, Divider, Group } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { authService } from '@app/services/authService';
import { STIRLING_SAAS_URL } from '@app/constants/connection';
import { buildOAuthCallbackHtml } from '@app/utils/oauthCallbackHtml';
import { BASE_PATH } from '@app/constants/app';
interface LoginFormProps {
serverUrl: string;
@@ -14,6 +18,7 @@ export const LoginForm: React.FC<LoginFormProps> = ({ serverUrl, isSaaS = false,
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [validationError, setValidationError] = useState<string | null>(null);
const [oauthLoading, setOauthLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -33,6 +38,51 @@ export const LoginForm: React.FC<LoginFormProps> = ({ serverUrl, isSaaS = false,
await onLogin(username.trim(), password);
};
const handleOAuthLogin = async (provider: 'google' | 'github') => {
// Prevent concurrent OAuth attempts
if (oauthLoading || loading) {
return;
}
try {
setOauthLoading(true);
setValidationError(null);
// For SaaS, use configured SaaS URL; for self-hosted, derive from serverUrl
const authServerUrl = isSaaS
? STIRLING_SAAS_URL
: serverUrl; // Self-hosted might have its own auth
// Build callback page HTML with translations and dark mode support
const successHtml = buildOAuthCallbackHtml({
title: t('oauth.success.title', 'Authentication Successful'),
message: t('oauth.success.message', 'You can close this window and return to Stirling PDF.'),
isError: false,
});
const errorHtml = buildOAuthCallbackHtml({
title: t('oauth.error.title', 'Authentication Failed'),
message: t('oauth.error.message', 'Authentication was not successful. You can close this window and try again.'),
isError: true,
errorPlaceholder: true, // {error} will be replaced by Rust
});
const userInfo = await authService.loginWithOAuth(provider, authServerUrl, successHtml, errorHtml);
// Call the onLogin callback to complete setup (username/password not needed for OAuth)
await onLogin(userInfo.username, '');
} catch (error) {
console.error('OAuth login failed:', error);
const errorMessage = error instanceof Error
? error.message
: t('setup.login.error.oauthFailed', 'OAuth login failed. Please try again.');
setValidationError(errorMessage);
setOauthLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
<Stack gap="md">
@@ -40,6 +90,47 @@ export const LoginForm: React.FC<LoginFormProps> = ({ serverUrl, isSaaS = false,
{t('setup.login.connectingTo', 'Connecting to:')} <strong>{isSaaS ? 'stirling.com' : serverUrl}</strong>
</Text>
{/* OAuth Login Buttons - Only show for SaaS */}
{isSaaS && (
<>
<Stack gap="xs">
<Group grow>
<Button
variant="default"
leftSection={<img src={`${BASE_PATH}/Login/google.svg`} alt="Google" width={18} height={18} />}
onClick={() => handleOAuthLogin('google')}
disabled={loading || oauthLoading}
styles={{
root: { height: '42px' },
}}
>
{t('setup.login.signInWith', 'Sign in with')} Google
</Button>
<Button
variant="default"
leftSection={<img src={`${BASE_PATH}/Login/github.svg`} alt="GitHub" width={18} height={18} />}
onClick={() => handleOAuthLogin('github')}
disabled={loading || oauthLoading}
styles={{
root: { height: '42px' },
}}
>
{t('setup.login.signInWith', 'Sign in with')} GitHub
</Button>
</Group>
{oauthLoading && (
<Text size="sm" c="dimmed" ta="center">
{t('setup.login.oauthPending', 'Opening browser for authentication...')}
</Text>
)}
</Stack>
<Divider label={t('setup.login.orContinueWith', 'Or continue with email')} labelPosition="center" />
</>
)}
<TextInput
label={t('setup.login.username.label', 'Username')}
placeholder={t('setup.login.username.placeholder', 'Enter your username')}
@@ -5,7 +5,10 @@
flex-direction: column;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
background: linear-gradient(135deg,
light-dark(#f5f5f5, #1a1a1a) 0%,
light-dark(#e8e8e8, #0d0d0d) 100%
);
padding: 2rem;
}
@@ -15,6 +18,6 @@
}
.setup-card {
background-color: white;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.12);
background-color: light-dark(var(--mantine-color-white), var(--mantine-color-dark-6));
box-shadow: 0 20px 60px light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.4));
}
@@ -53,7 +53,13 @@ export const SetupWizard: React.FC<SetupWizardProps> = ({ onComplete }) => {
setLoading(true);
setError(null);
await authService.login(serverConfig.url, username, password);
// Only attempt password login if a password is provided
// If password is empty, assume OAuth login already completed
const isAlreadyAuthenticated = await authService.isAuthenticated();
if (!isAlreadyAuthenticated && password) {
await authService.login(serverConfig.url, username, password);
}
await connectionModeService.switchToSaaS(serverConfig.url);
await tauriBackendService.startBackend();
onComplete();
+5 -6
View File
@@ -2,11 +2,10 @@
* Connection-related constants for desktop app
*/
// SaaS server URL from environment variable (required)
// SaaS server URL from environment variable
// The SaaS authentication server
// Will throw error if VITE_SAAS_SERVER_URL is not set
if (!import.meta.env.VITE_SAAS_SERVER_URL) {
throw new Error('VITE_SAAS_SERVER_URL environment variable is required');
}
export const STIRLING_SAAS_URL: string = import.meta.env.VITE_SAAS_SERVER_URL || '';
export const STIRLING_SAAS_URL = import.meta.env.VITE_SAAS_SERVER_URL;
// Supabase publishable key from environment variable
// Used for SaaS authentication
export const SUPABASE_KEY: string = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY || '';
+104 -8
View File
@@ -1,5 +1,6 @@
import { invoke } from '@tauri-apps/api/core';
import axios from 'axios';
import { STIRLING_SAAS_URL, SUPABASE_KEY } from '@app/constants/connection';
export interface UserInfo {
username: string;
@@ -12,7 +13,13 @@ interface LoginResponse {
email: string | null;
}
export type AuthStatus = 'authenticated' | 'unauthenticated' | 'refreshing';
interface OAuthCallbackResult {
access_token: string;
refresh_token: string | null;
expires_in: number | null;
}
export type AuthStatus = 'authenticated' | 'unauthenticated' | 'refreshing' | 'oauth_pending';
export class AuthService {
private static instance: AuthService;
@@ -50,11 +57,23 @@ export class AuthService {
try {
console.log('Logging in to:', serverUrl);
// Validate SaaS configuration if connecting to SaaS
if (serverUrl === STIRLING_SAAS_URL) {
if (!STIRLING_SAAS_URL) {
throw new Error('VITE_SAAS_SERVER_URL is not configured');
}
if (!SUPABASE_KEY) {
throw new Error('VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY is not configured');
}
}
// Call Rust login command (bypasses CORS)
const response = await invoke<LoginResponse>('login', {
serverUrl,
username,
password,
supabaseKey: SUPABASE_KEY,
saasServerUrl: STIRLING_SAAS_URL,
});
const { token, username: returnedUsername, email } = response;
@@ -80,13 +99,7 @@ export class AuthService {
} catch (error) {
console.error('Login failed:', error);
this.setAuthStatus('unauthenticated', null);
// Rust commands return string errors
if (typeof error === 'string') {
throw new Error(error);
}
throw new Error('Login failed. Please try again.');
throw error;
}
}
@@ -193,6 +206,89 @@ export class AuthService {
this.setAuthStatus('unauthenticated', null);
}
}
/**
* Start OAuth login flow by opening system browser with localhost callback
*/
async loginWithOAuth(provider: string, authServerUrl: string, successHtml: string, errorHtml: string): Promise<UserInfo> {
try {
console.log('Starting OAuth login with provider:', provider);
this.setAuthStatus('oauth_pending', null);
// Validate Supabase key is configured for OAuth
if (!SUPABASE_KEY) {
throw new Error('VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY is not configured');
}
// Call Rust command which:
// 1. Starts localhost HTTP server on random port
// 2. Opens browser to OAuth provider
// 3. Waits for callback
// 4. Returns tokens
const result = await invoke<OAuthCallbackResult>('start_oauth_login', {
provider,
authServerUrl,
supabaseKey: SUPABASE_KEY,
successHtml,
errorHtml,
});
console.log('OAuth authentication successful, storing tokens');
// Save the access token to keyring
await invoke('save_auth_token', { token: result.access_token });
// Fetch user info from Supabase using the access token
const userInfo = await this.fetchSupabaseUserInfo(authServerUrl, result.access_token);
// Save user info to store
await invoke('save_user_info', {
username: userInfo.username,
email: userInfo.email || null,
});
this.setAuthStatus('authenticated', userInfo);
console.log('OAuth login successful');
return userInfo;
} catch (error) {
console.error('Failed to complete OAuth login:', error);
this.setAuthStatus('unauthenticated', null);
throw error;
}
}
/**
* Fetch user info from Supabase using access token
*/
private async fetchSupabaseUserInfo(authServerUrl: string, accessToken: string): Promise<UserInfo> {
try {
const userEndpoint = `${authServerUrl}/auth/v1/user`;
const response = await axios.get(userEndpoint, {
headers: {
Authorization: `Bearer ${accessToken}`,
'apikey': SUPABASE_KEY,
},
});
const data = response.data;
console.log('User info fetched:', data.email);
return {
username: data.user_metadata?.full_name || data.email || 'Unknown',
email: data.email,
};
} catch (error) {
console.error('Failed to fetch user info from Supabase:', error);
// Fallback to basic info
return {
username: 'User',
email: undefined,
};
}
}
}
export const authService = AuthService.getInstance();
@@ -0,0 +1,154 @@
/**
* Builds HTML for OAuth callback pages with i18n and dark mode support
*/
interface OAuthCallbackHtmlOptions {
title: string;
message: string;
isError?: boolean;
errorPlaceholder?: boolean;
}
/**
* Generates OAuth callback HTML with automatic dark mode support
*/
export function buildOAuthCallbackHtml({
title,
message,
isError = false,
errorPlaceholder = false,
}: OAuthCallbackHtmlOptions): string {
const iconColor = isError ? '#d32f2f' : '#2e7d32';
const iconColorDark = isError ? '#ef5350' : '#66bb6a';
const icon = isError ? '✗' : '✓';
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
text-align: center;
padding: 50px 20px;
background: #f5f5f5;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background: white;
border-radius: 12px;
padding: 40px;
max-width: 420px;
width: 100%;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.icon {
font-size: 48px;
margin-bottom: 16px;
color: ${iconColor};
}
h1 {
font-size: 24px;
font-weight: 600;
margin-bottom: 12px;
color: #1a1a1a;
}
p {
color: #666;
line-height: 1.6;
font-size: 15px;
}
${errorPlaceholder ? `
.error-details {
background: #ffebee;
border: 1px solid #ffcdd2;
padding: 16px;
border-radius: 8px;
margin-top: 20px;
font-size: 14px;
color: #c62828;
word-break: break-word;
text-align: left;
line-height: 1.5;
}
` : ''}
/* Dark mode support */
@media (prefers-color-scheme: dark) {
body {
background: #1a1a1a;
color: #e0e0e0;
}
.container {
background: #2d2d2d;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
.icon {
color: ${iconColorDark};
}
h1 {
color: #f5f5f5;
}
p {
color: #b0b0b0;
}
${errorPlaceholder ? `
.error-details {
background: #3d2020;
border: 1px solid #5d3030;
color: #ef9a9a;
}
` : ''}
}
/* Mobile responsive */
@media (max-width: 480px) {
body {
padding: 20px 16px;
}
.container {
padding: 32px 24px;
}
h1 {
font-size: 20px;
}
.icon {
font-size: 40px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="icon">${icon}</div>
<h1>${title}</h1>
<p>${message}</p>
${errorPlaceholder ? '<div class="error-details">{error}</div>' : ''}
</div>
</body>
</html>`;
}