Feat(UI): hide UI login when ALLOW_LOCAL_AUTH is set to false

This commit is contained in:
aaldebs99 2025-10-30 22:10:04 +00:00
parent d4eaad8162
commit 58652bc300
4 changed files with 272 additions and 147 deletions

View File

@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import {
Box,
Card,
@ -12,6 +12,7 @@ import {
IconButton,
Fade,
Grow,
CircularProgress,
} from '@mui/material';
import {
Visibility,
@ -34,7 +35,14 @@ interface LoginFormData {
password: string;
}
interface AuthConfig {
allow_local_auth: boolean;
oidc_enabled: boolean;
}
const Login: React.FC = () => {
const [authConfig, setAuthConfig] = useState<AuthConfig | null>(null);
const [configLoading, setConfigLoading] = useState<boolean>(true);
const [showPassword, setShowPassword] = useState<boolean>(false);
const [error, setError] = useState<string>('');
const [loading, setLoading] = useState<boolean>(false);
@ -45,6 +53,30 @@ const Login: React.FC = () => {
const theme = useMuiTheme();
const { t } = useTranslation();
// Fetch authentication configuration from backend
useEffect(() => {
const fetchAuthConfig = async () => {
try {
const response = await fetch('/api/auth/config');
if (response.ok) {
const config = await response.json();
setAuthConfig(config);
} else {
// Default to allowing both if config fetch fails
setAuthConfig({ allow_local_auth: true, oidc_enabled: true });
}
} catch (err) {
console.error('Failed to fetch auth config:', err);
// Default to allowing both if config fetch fails
setAuthConfig({ allow_local_auth: true, oidc_enabled: true });
} finally {
setConfigLoading(false);
}
};
fetchAuthConfig();
}, []);
const {
register,
handleSubmit,
@ -178,18 +210,26 @@ const Login: React.FC = () => {
</Typography>
</Box>
{/* Loading state while fetching config */}
{configLoading && (
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
<CircularProgress sx={{ color: 'white' }} />
</Box>
)}
{/* Login Card */}
<Grow in={true} timeout={1200}>
<Card
elevation={0}
sx={{
borderRadius: 4,
backdropFilter: 'blur(20px)',
backgroundColor: mode === 'light'
? 'rgba(255, 255, 255, 0.95)'
: 'rgba(30, 30, 30, 0.95)',
border: mode === 'light'
? '1px solid rgba(255, 255, 255, 0.2)'
{!configLoading && authConfig && (
<Grow in={true} timeout={1200}>
<Card
elevation={0}
sx={{
borderRadius: 4,
backdropFilter: 'blur(20px)',
backgroundColor: mode === 'light'
? 'rgba(255, 255, 255, 0.95)'
: 'rgba(30, 30, 30, 0.95)',
border: mode === 'light'
? '1px solid rgba(255, 255, 255, 0.2)'
: '1px solid rgba(255, 255, 255, 0.1)',
boxShadow: mode === 'light'
? '0 25px 50px -12px rgba(0, 0, 0, 0.25)'
@ -216,142 +256,148 @@ const Login: React.FC = () => {
)}
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
<TextField
fullWidth
label={t('auth.username')}
margin="normal"
{...register('username', {
required: t('auth.usernameRequired'),
})}
error={!!errors.username}
helperText={errors.username?.message}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<EmailIcon sx={{ color: 'text.secondary' }} />
</InputAdornment>
),
}}
sx={{ mb: 2 }}
/>
{authConfig.allow_local_auth && (
<>
<TextField
fullWidth
label={t('auth.username')}
margin="normal"
{...register('username', {
required: t('auth.usernameRequired'),
})}
error={!!errors.username}
helperText={errors.username?.message}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<EmailIcon sx={{ color: 'text.secondary' }} />
</InputAdornment>
),
}}
sx={{ mb: 2 }}
/>
<TextField
fullWidth
label={t('auth.password')}
type={showPassword ? 'text' : 'password'}
margin="normal"
{...register('password', {
required: t('auth.passwordRequired'),
})}
error={!!errors.password}
helperText={errors.password?.message}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<LockIcon sx={{ color: 'text.secondary' }} />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleClickShowPassword}
edge="end"
sx={{ color: 'text.secondary' }}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
sx={{ mb: 3 }}
/>
<TextField
fullWidth
label={t('auth.password')}
type={showPassword ? 'text' : 'password'}
margin="normal"
{...register('password', {
required: t('auth.passwordRequired'),
})}
error={!!errors.password}
helperText={errors.password?.message}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<LockIcon sx={{ color: 'text.secondary' }} />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleClickShowPassword}
edge="end"
sx={{ color: 'text.secondary' }}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
sx={{ mb: 3 }}
/>
<Button
type="submit"
fullWidth
variant="contained"
size="large"
disabled={loading || oidcLoading}
sx={{
py: 1.5,
mb: 2,
background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
borderRadius: 2,
fontSize: '1rem',
fontWeight: 600,
textTransform: 'none',
boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
'&:hover': {
background: 'linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%)',
boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)',
},
'&:disabled': {
background: 'rgba(0, 0, 0, 0.12)',
},
}}
>
{loading ? t('auth.signingIn') : t('auth.signIn')}
</Button>
<Button
type="submit"
fullWidth
variant="contained"
size="large"
disabled={loading || oidcLoading}
sx={{
py: 1.5,
mb: 2,
background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
borderRadius: 2,
fontSize: '1rem',
fontWeight: 600,
textTransform: 'none',
boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
'&:hover': {
background: 'linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%)',
boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)',
},
'&:disabled': {
background: 'rgba(0, 0, 0, 0.12)',
},
}}
>
{loading ? t('auth.signingIn') : t('auth.signIn')}
</Button>
<Box
sx={{
display: 'flex',
alignItems: 'center',
my: 2,
'&::before': {
content: '""',
flex: 1,
height: '1px',
backgroundColor: 'divider',
},
'&::after': {
content: '""',
flex: 1,
height: '1px',
backgroundColor: 'divider',
},
}}
>
<Typography
variant="body2"
<Box
sx={{
display: 'flex',
alignItems: 'center',
my: 2,
'&::before': {
content: '""',
flex: 1,
height: '1px',
backgroundColor: 'divider',
},
'&::after': {
content: '""',
flex: 1,
height: '1px',
backgroundColor: 'divider',
},
}}
>
<Typography
variant="body2"
sx={{
px: 2,
color: 'text.secondary',
}}
>
{t('common.or')}
</Typography>
</Box>
</>
)}
{authConfig.oidc_enabled && (
<Button
fullWidth
variant="outlined"
size="large"
disabled={loading || oidcLoading}
onClick={handleOidcLogin}
startIcon={<SecurityIcon />}
sx={{
px: 2,
color: 'text.secondary',
py: 1.5,
mb: 2,
borderRadius: 2,
fontSize: '1rem',
fontWeight: 600,
textTransform: 'none',
borderColor: 'primary.main',
color: 'primary.main',
'&:hover': {
backgroundColor: 'primary.main',
color: 'white',
borderColor: 'primary.main',
},
'&:disabled': {
borderColor: 'rgba(0, 0, 0, 0.12)',
color: 'rgba(0, 0, 0, 0.26)',
},
}}
>
{t('common.or')}
</Typography>
</Box>
<Button
fullWidth
variant="outlined"
size="large"
disabled={loading || oidcLoading}
onClick={handleOidcLogin}
startIcon={<SecurityIcon />}
sx={{
py: 1.5,
mb: 2,
borderRadius: 2,
fontSize: '1rem',
fontWeight: 600,
textTransform: 'none',
borderColor: 'primary.main',
color: 'primary.main',
'&:hover': {
backgroundColor: 'primary.main',
color: 'white',
borderColor: 'primary.main',
},
'&:disabled': {
borderColor: 'rgba(0, 0, 0, 0.12)',
color: 'rgba(0, 0, 0, 0.26)',
},
}}
>
{oidcLoading ? t('auth.redirecting') : t('auth.signInWithOIDC')}
</Button>
{oidcLoading ? t('auth.redirecting') : t('auth.signInWithOIDC')}
</Button>
)}
<Box sx={{ textAlign: 'center', mt: 2 }}>
</Box>
@ -359,6 +405,7 @@ const Login: React.FC = () => {
</CardContent>
</Card>
</Grow>
)}
{/* Footer */}
<Box sx={{ textAlign: 'center', mt: 4 }}>

View File

@ -1,4 +1,4 @@
import { describe, test, expect } from 'vitest';
import { describe, test, expect, vi, beforeEach } from 'vitest';
import Login from '../Login';
// Basic existence test for Login component
@ -6,6 +6,11 @@ import Login from '../Login';
// is causing infrastructure issues
describe('Login - OIDC Features - Simplified', () => {
beforeEach(() => {
// Mock fetch for auth config endpoint
global.fetch = vi.fn();
});
test('Test file exists and can run', () => {
// This is a basic test to ensure the test file is valid
expect(true).toBe(true);
@ -16,4 +21,11 @@ describe('Login - OIDC Features - Simplified', () => {
expect(Login).toBeDefined();
expect(typeof Login).toBe('function');
});
test('Component fetches auth config at runtime', () => {
// The component now fetches /api/auth/config to determine
// which authentication methods are available
// Actual rendering logic is tested in E2E tests
expect(global.fetch).toBeDefined();
});
});

View File

@ -1,17 +1,46 @@
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import React, { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '../contexts/AuthContext'
interface AuthConfig {
allow_local_auth: boolean;
oidc_enabled: boolean;
}
function Register() {
const navigate = useNavigate()
const { t } = useTranslation()
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [configLoading, setConfigLoading] = useState(true)
const { register } = useAuth()
// Fetch authentication configuration and redirect if local auth is disabled
useEffect(() => {
const fetchAuthConfig = async () => {
try {
const response = await fetch('/api/auth/config');
if (response.ok) {
const config: AuthConfig = await response.json();
if (!config.allow_local_auth) {
// Redirect to login if local auth is disabled
navigate('/login');
}
}
} catch (err) {
console.error('Failed to fetch auth config:', err);
} finally {
setConfigLoading(false);
}
};
fetchAuthConfig();
}, [navigate])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
@ -26,6 +55,16 @@ function Register() {
}
}
if (configLoading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="text-center">
<p className="text-gray-600">{t('common.loading', 'Loading...')}</p>
</div>
</div>
)
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">

View File

@ -5,7 +5,7 @@ use axum::{
routing::{get, post},
Router,
};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use crate::{
@ -20,10 +20,17 @@ pub fn router() -> Router<Arc<AppState>> {
.route("/register", post(register))
.route("/login", post(login))
.route("/me", get(me))
.route("/config", get(get_auth_config))
.route("/oidc/login", get(oidc_login))
.route("/oidc/callback", get(oidc_callback))
}
#[derive(Serialize, utoipa::ToSchema)]
struct AuthConfig {
allow_local_auth: bool,
oidc_enabled: bool,
}
#[utoipa::path(
post,
@ -82,6 +89,26 @@ async fn register(
}
}
#[utoipa::path(
get,
path = "/api/auth/config",
tag = "auth",
responses(
(status = 200, description = "Authentication configuration", body = AuthConfig),
)
)]
async fn get_auth_config(
State(state): State<Arc<AppState>>,
) -> Json<AuthConfig> {
let allow_local_auth = state.config.allow_local_auth.unwrap_or(true);
let oidc_enabled = state.oidc_client.is_some();
Json(AuthConfig {
allow_local_auth,
oidc_enabled,
})
}
#[utoipa::path(
post,
path = "/api/auth/login",