mirror of
https://github.com/swissmakers/fail2ban-ui.git
synced 2026-04-11 13:47:05 +02:00
Add optional OIDC authentication with Keycloak, Authentik, and Pocket-ID support
This commit is contained in:
99
pkg/web/auth.go
Normal file
99
pkg/web/auth.go
Normal file
@@ -0,0 +1,99 @@
|
||||
// Fail2ban UI - A Swiss made, management interface for Fail2ban.
|
||||
//
|
||||
// Copyright (C) 2025 Swissmakers GmbH (https://swissmakers.ch)
|
||||
//
|
||||
// Licensed under the GNU General Public License, Version 3 (GPL-3.0)
|
||||
// You may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.gnu.org/licenses/gpl-3.0.en.html
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/swissmakers/fail2ban-ui/internal/auth"
|
||||
)
|
||||
|
||||
// AuthMiddleware protects routes requiring authentication
|
||||
// If OIDC is enabled, validates session and redirects to login if not authenticated
|
||||
// If OIDC is disabled, allows all requests
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Check if OIDC is enabled
|
||||
if !auth.IsEnabled() {
|
||||
// OIDC not enabled, allow request
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this is a public route
|
||||
path := c.Request.URL.Path
|
||||
if isPublicRoute(path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Validate session
|
||||
session, err := auth.GetSession(c.Request)
|
||||
if err != nil {
|
||||
// No valid session, redirect to login
|
||||
if isAPIRequest(c) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// For HTML requests, redirect to login
|
||||
c.Redirect(http.StatusFound, "/auth/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Store session in context for handlers to access
|
||||
c.Set("session", session)
|
||||
c.Set("userID", session.UserID)
|
||||
c.Set("userEmail", session.Email)
|
||||
c.Set("userName", session.Name)
|
||||
c.Set("username", session.Username)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// isPublicRoute checks if the path is a public route that doesn't require authentication
|
||||
func isPublicRoute(path string) bool {
|
||||
publicRoutes := []string{
|
||||
"/auth/login",
|
||||
"/auth/callback",
|
||||
"/auth/logout",
|
||||
"/auth/status",
|
||||
"/api/ban",
|
||||
"/api/unban",
|
||||
"/api/ws",
|
||||
"/static/",
|
||||
"/locales/",
|
||||
}
|
||||
|
||||
for _, route := range publicRoutes {
|
||||
if strings.HasPrefix(path, route) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// isAPIRequest checks if the request is an API request (JSON expected)
|
||||
func isAPIRequest(c *gin.Context) bool {
|
||||
accept := c.GetHeader("Accept")
|
||||
return strings.Contains(accept, "application/json") || strings.HasPrefix(c.Request.URL.Path, "/api/")
|
||||
}
|
||||
@@ -19,8 +19,10 @@ package web
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -30,6 +32,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -42,6 +45,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
"github.com/swissmakers/fail2ban-ui/internal/auth"
|
||||
"github.com/swissmakers/fail2ban-ui/internal/config"
|
||||
"github.com/swissmakers/fail2ban-ui/internal/fail2ban"
|
||||
"github.com/swissmakers/fail2ban-ui/internal/integrations"
|
||||
@@ -1116,8 +1120,8 @@ func shouldAlertForCountry(country string, alertCountries []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IndexHandler serves the HTML page
|
||||
func IndexHandler(c *gin.Context) {
|
||||
// renderIndexPage renders the index.html template with common data
|
||||
func renderIndexPage(c *gin.Context) {
|
||||
// Check if external IP lookup is disabled via environment variable
|
||||
// Default is enabled (false means enabled, true means disabled)
|
||||
disableExternalIP := os.Getenv("DISABLE_EXTERNAL_IP_LOOKUP") == "true" || os.Getenv("DISABLE_EXTERNAL_IP_LOOKUP") == "1"
|
||||
@@ -3007,3 +3011,241 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// *******************************************************************
|
||||
// * OIDC Authentication Handlers *
|
||||
// *******************************************************************
|
||||
|
||||
// LoginHandler shows the login page or initiates the OIDC login flow
|
||||
// If action=redirect query parameter is present, redirects to OIDC provider
|
||||
// Otherwise, renders the login page
|
||||
func LoginHandler(c *gin.Context) {
|
||||
oidcClient := auth.GetOIDCClient()
|
||||
if oidcClient == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "OIDC authentication is not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this is a redirect action (triggered by clicking the login button)
|
||||
if c.Query("action") == "redirect" {
|
||||
// Generate state parameter for CSRF protection
|
||||
stateBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(stateBytes); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate state parameter"})
|
||||
return
|
||||
}
|
||||
state := base64.URLEncoding.EncodeToString(stateBytes)
|
||||
|
||||
// Determine if we're using HTTPS
|
||||
isSecure := c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https"
|
||||
|
||||
// Store state in session cookie for validation
|
||||
stateCookie := &http.Cookie{
|
||||
Name: "oidc_state",
|
||||
Value: state,
|
||||
Path: "/",
|
||||
MaxAge: 600, // 10 minutes
|
||||
HttpOnly: true,
|
||||
Secure: isSecure, // Only secure over HTTPS
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
}
|
||||
http.SetCookie(c.Writer, stateCookie)
|
||||
config.DebugLog("Set state cookie: %s (Secure: %v)", state, isSecure)
|
||||
|
||||
// Get authorization URL and redirect
|
||||
authURL := oidcClient.GetAuthURL(state)
|
||||
c.Redirect(http.StatusFound, authURL)
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise, render the login page (index.html)
|
||||
// The JavaScript will handle showing the login page and redirecting when button is clicked
|
||||
renderIndexPage(c)
|
||||
}
|
||||
|
||||
// CallbackHandler handles the OIDC callback after user authentication
|
||||
func CallbackHandler(c *gin.Context) {
|
||||
oidcClient := auth.GetOIDCClient()
|
||||
if oidcClient == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "OIDC authentication is not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
// Get state from cookie
|
||||
stateCookie, err := c.Cookie("oidc_state")
|
||||
if err != nil {
|
||||
config.DebugLog("Failed to get state cookie: %v", err)
|
||||
config.DebugLog("Request cookies: %v", c.Request.Cookies())
|
||||
config.DebugLog("Request URL: %s", c.Request.URL.String())
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing state parameter", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Determine if we're using HTTPS
|
||||
isSecure := c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https"
|
||||
|
||||
// Clear state cookie
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: "oidc_state",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
Secure: isSecure, // Only secure over HTTPS
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
|
||||
// Verify state parameter
|
||||
returnedState := c.Query("state")
|
||||
if returnedState != stateCookie {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid state parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
// Get authorization code
|
||||
code := c.Query("code")
|
||||
if code == "" {
|
||||
errorDesc := c.Query("error_description")
|
||||
if errorDesc != "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "OIDC authentication failed: " + errorDesc})
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing authorization code"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Exchange code for tokens
|
||||
token, err := oidcClient.ExchangeCode(c.Request.Context(), code)
|
||||
if err != nil {
|
||||
config.DebugLog("Failed to exchange code for token: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to exchange authorization code"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify token and extract user info
|
||||
userInfo, err := oidcClient.VerifyToken(c.Request.Context(), token)
|
||||
if err != nil {
|
||||
config.DebugLog("Failed to verify token: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to verify authentication token"})
|
||||
return
|
||||
}
|
||||
|
||||
// Create session
|
||||
if err := auth.CreateSession(c.Writer, c.Request, userInfo, oidcClient.Config.SessionMaxAge); err != nil {
|
||||
config.DebugLog("Failed to create session: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create session"})
|
||||
return
|
||||
}
|
||||
|
||||
config.DebugLog("User authenticated: %s (%s)", userInfo.Username, userInfo.Email)
|
||||
|
||||
// Redirect to main page
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
}
|
||||
|
||||
// LogoutHandler clears the session and optionally redirects to provider logout
|
||||
func LogoutHandler(c *gin.Context) {
|
||||
oidcClient := auth.GetOIDCClient()
|
||||
|
||||
// Clear session first
|
||||
auth.DeleteSession(c.Writer, c.Request)
|
||||
|
||||
// If provider logout URL is configured, redirect there
|
||||
// Auto-construct logout URL for standard OIDC providers if not explicitly set
|
||||
if oidcClient != nil {
|
||||
logoutURL := oidcClient.Config.LogoutURL
|
||||
if logoutURL == "" && oidcClient.Config.IssuerURL != "" {
|
||||
// Auto-construct standard OIDC logout URL for Keycloak, Authentik, and Pocket-ID
|
||||
issuerURL := oidcClient.Config.IssuerURL
|
||||
redirectURI := oidcClient.Config.RedirectURL
|
||||
// Extract base URL from redirect URI for logout redirect (remove /auth/callback)
|
||||
if strings.Contains(redirectURI, "/auth/callback") {
|
||||
redirectURI = strings.TrimSuffix(redirectURI, "/auth/callback")
|
||||
}
|
||||
// Redirect to login page after logout
|
||||
redirectURI = redirectURI + "/auth/login"
|
||||
// URL encode the redirect_uri parameter
|
||||
redirectURIEncoded := url.QueryEscape(redirectURI)
|
||||
clientIDEncoded := url.QueryEscape(oidcClient.Config.ClientID)
|
||||
|
||||
// Provider-specific logout URL construction
|
||||
switch oidcClient.Config.Provider {
|
||||
case "keycloak":
|
||||
// Keycloak requires client_id when using post_logout_redirect_uri
|
||||
// Format: {issuer}/protocol/openid-connect/logout?post_logout_redirect_uri={redirect}&client_id={client_id}
|
||||
logoutURL = fmt.Sprintf("%s/protocol/openid-connect/logout?post_logout_redirect_uri=%s&client_id=%s", issuerURL, redirectURIEncoded, clientIDEncoded)
|
||||
case "authentik", "pocketid":
|
||||
// Standard OIDC format for Authentik and Pocket-ID
|
||||
// Format: {issuer}/protocol/openid-connect/logout?redirect_uri={redirect}
|
||||
logoutURL = fmt.Sprintf("%s/protocol/openid-connect/logout?redirect_uri=%s", issuerURL, redirectURIEncoded)
|
||||
default:
|
||||
// Fallback to standard OIDC format
|
||||
logoutURL = fmt.Sprintf("%s/protocol/openid-connect/logout?redirect_uri=%s", issuerURL, redirectURIEncoded)
|
||||
}
|
||||
}
|
||||
|
||||
if logoutURL != "" {
|
||||
config.DebugLog("Redirecting to provider logout: %s", logoutURL)
|
||||
c.Redirect(http.StatusFound, logoutURL)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, redirect to login page
|
||||
c.Redirect(http.StatusFound, "/auth/login")
|
||||
}
|
||||
|
||||
// AuthStatusHandler returns the current authentication status
|
||||
func AuthStatusHandler(c *gin.Context) {
|
||||
if !auth.IsEnabled() {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": false,
|
||||
"authenticated": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
session, err := auth.GetSession(c.Request)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": true,
|
||||
"authenticated": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": true,
|
||||
"authenticated": true,
|
||||
"user": gin.H{
|
||||
"id": session.UserID,
|
||||
"email": session.Email,
|
||||
"name": session.Name,
|
||||
"username": session.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// UserInfoHandler returns the current user information
|
||||
func UserInfoHandler(c *gin.Context) {
|
||||
if !auth.IsEnabled() {
|
||||
c.JSON(http.StatusOK, gin.H{"authenticated": false})
|
||||
return
|
||||
}
|
||||
|
||||
session, err := auth.GetSession(c.Request)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Not authenticated"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": true,
|
||||
"user": gin.H{
|
||||
"id": session.UserID,
|
||||
"email": session.Email,
|
||||
"name": session.Name,
|
||||
"username": session.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,8 +25,21 @@ func RegisterRoutes(r *gin.Engine, hub *Hub) {
|
||||
// Set the global WebSocket hub
|
||||
SetWebSocketHub(hub)
|
||||
|
||||
// Public authentication routes (no auth required)
|
||||
authRoutes := r.Group("/auth")
|
||||
{
|
||||
authRoutes.GET("/login", LoginHandler)
|
||||
authRoutes.GET("/callback", CallbackHandler)
|
||||
authRoutes.GET("/logout", LogoutHandler)
|
||||
authRoutes.GET("/status", AuthStatusHandler)
|
||||
authRoutes.GET("/user", UserInfoHandler)
|
||||
}
|
||||
|
||||
// Apply authentication middleware to all routes
|
||||
r.Use(AuthMiddleware())
|
||||
|
||||
// Render the dashboard
|
||||
r.GET("/", IndexHandler)
|
||||
r.GET("/", renderIndexPage)
|
||||
|
||||
api := r.Group("/api")
|
||||
{
|
||||
|
||||
@@ -21,6 +21,277 @@
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Login Page Styling */
|
||||
#loginPage {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: #f3f4f6;
|
||||
padding: 3rem 1rem;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Ensure login page is visible when shown */
|
||||
body:has(#loginPage:not(.hidden)) {
|
||||
background-color: #f3f4f6;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#loginPage .max-w-md {
|
||||
max-width: 28rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#loginPage .bg-white {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
#loginPage .rounded-lg {
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
#loginPage .shadow-lg {
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
#loginPage .p-8 {
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
#loginPage .mb-8 {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
#loginPage .mb-4 {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
#loginPage .mb-6 {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
#loginPage .mb-2 {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
#loginPage .mr-2 {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
#loginPage .mr-3 {
|
||||
margin-right: 0.75rem;
|
||||
}
|
||||
|
||||
#loginPage .ml-3 {
|
||||
margin-left: 0.75rem;
|
||||
}
|
||||
|
||||
#loginPage .pt-6 {
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
#loginPage .py-4 {
|
||||
padding-top: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
#loginPage .py-3 {
|
||||
padding-top: 0.75rem;
|
||||
padding-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
#loginPage .px-4 {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
#loginPage .h-16 {
|
||||
height: 4rem;
|
||||
}
|
||||
|
||||
#loginPage .w-16 {
|
||||
width: 4rem;
|
||||
}
|
||||
|
||||
#loginPage .h-10 {
|
||||
height: 2.5rem;
|
||||
}
|
||||
|
||||
#loginPage .w-10 {
|
||||
width: 2.5rem;
|
||||
}
|
||||
|
||||
#loginPage .h-5 {
|
||||
height: 1.25rem;
|
||||
}
|
||||
|
||||
#loginPage .w-5 {
|
||||
width: 1.25rem;
|
||||
}
|
||||
|
||||
#loginPage .rounded-full {
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
#loginPage .bg-blue-600 {
|
||||
background-color: #2563eb;
|
||||
}
|
||||
|
||||
#loginPage .text-white {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
#loginPage .text-gray-900 {
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
#loginPage .text-gray-600 {
|
||||
color: #4b5563;
|
||||
}
|
||||
|
||||
#loginPage .text-gray-500 {
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
#loginPage .text-red-700 {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
#loginPage .text-red-400 {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
#loginPage .text-3xl {
|
||||
font-size: 1.875rem;
|
||||
line-height: 2.25rem;
|
||||
}
|
||||
|
||||
#loginPage .text-base {
|
||||
font-size: 1rem;
|
||||
line-height: 1.5rem;
|
||||
}
|
||||
|
||||
#loginPage .text-sm {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
}
|
||||
|
||||
#loginPage .text-xs {
|
||||
font-size: 0.75rem;
|
||||
line-height: 1rem;
|
||||
}
|
||||
|
||||
#loginPage .font-bold {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#loginPage .font-medium {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
#loginPage .border {
|
||||
border-width: 1px;
|
||||
}
|
||||
|
||||
#loginPage .border-l-4 {
|
||||
border-left-width: 4px;
|
||||
}
|
||||
|
||||
#loginPage .border-t {
|
||||
border-top-width: 1px;
|
||||
}
|
||||
|
||||
#loginPage .border-gray-200 {
|
||||
border-color: #e5e7eb;
|
||||
}
|
||||
|
||||
#loginPage .border-red-400 {
|
||||
border-color: #f87171;
|
||||
}
|
||||
|
||||
#loginPage .border-transparent {
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
#loginPage .bg-red-50 {
|
||||
background-color: #fef2f2;
|
||||
}
|
||||
|
||||
#loginPage .hover\:bg-blue-700:hover {
|
||||
background-color: #1d4ed8;
|
||||
}
|
||||
|
||||
#loginPage .focus\:outline-none:focus {
|
||||
outline: 2px solid transparent;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
#loginPage .focus\:ring-2:focus {
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
|
||||
}
|
||||
|
||||
#loginPage .focus\:ring-offset-2:focus {
|
||||
box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px rgba(59, 130, 246, 0.5);
|
||||
}
|
||||
|
||||
#loginPage .focus\:ring-blue-500:focus {
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
|
||||
}
|
||||
|
||||
#loginPage .transition-colors {
|
||||
transition-property: background-color, border-color, color;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
}
|
||||
|
||||
#loginPage .animate-spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
#loginPage .flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
#loginPage .inline-flex {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
#loginPage .items-center {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#loginPage .justify-center {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
#loginPage .text-center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#loginPage .mx-auto {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
#loginPage .w-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#loginPage .hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Restart banner */
|
||||
#restartBanner {
|
||||
display: none;
|
||||
@@ -296,6 +567,32 @@ mark {
|
||||
}
|
||||
|
||||
/* Mobile responsive adjustments */
|
||||
/* Custom breakpoint at 830px for menu collapse */
|
||||
/* This overrides Tailwind's default md: breakpoint (768px) to collapse at 830px instead */
|
||||
@media (max-width: 830px) {
|
||||
/* Hide desktop menu navigation at 830px */
|
||||
nav .hidden.md\:block {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Show burger menu button at 830px */
|
||||
nav > div > div > div.md\:hidden:not(#mobileMenu) {
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
/* Allow mobile menu to be shown at 830px (override md:hidden) */
|
||||
/* The menu visibility is controlled by JavaScript via the 'hidden' class */
|
||||
/* When hidden class is NOT present, show the menu */
|
||||
nav #mobileMenu:not(.hidden) {
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
/* When mobile menu has 'hidden' class, hide it (JavaScript control takes precedence) */
|
||||
nav #mobileMenu.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
#backendStatus {
|
||||
padding: 0.125rem 0.375rem;
|
||||
|
||||
@@ -17,3 +17,27 @@ function serverHeaders(headers) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
// Auth-aware fetch wrapper that handles 401/403 responses
|
||||
function authFetch(url, options) {
|
||||
options = options || {};
|
||||
// Ensure Accept header for API requests
|
||||
if (!options.headers) {
|
||||
options.headers = {};
|
||||
}
|
||||
if (!options.headers['Accept']) {
|
||||
options.headers['Accept'] = 'application/json';
|
||||
}
|
||||
|
||||
return fetch(url, options).then(function(response) {
|
||||
// Handle authentication errors
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
if (typeof handleAuthError === 'function') {
|
||||
handleAuthError(response);
|
||||
}
|
||||
// Return a rejected promise to stop the chain
|
||||
return Promise.reject(new Error('Authentication required'));
|
||||
}
|
||||
return response;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
247
pkg/web/static/js/auth.js
Normal file
247
pkg/web/static/js/auth.js
Normal file
@@ -0,0 +1,247 @@
|
||||
// Authentication functions for Fail2ban UI
|
||||
"use strict";
|
||||
|
||||
let authEnabled = false;
|
||||
let isAuthenticated = false;
|
||||
let currentUser = null;
|
||||
|
||||
// Check authentication status on page load
|
||||
async function checkAuthStatus() {
|
||||
// Immediately hide main content to prevent flash
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
const nav = document.querySelector('nav');
|
||||
if (mainContent) {
|
||||
mainContent.style.display = 'none';
|
||||
}
|
||||
if (nav) {
|
||||
nav.style.display = 'none';
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/auth/status', {
|
||||
headers: serverHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to check auth status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
authEnabled = data.enabled || false;
|
||||
isAuthenticated = data.authenticated || false;
|
||||
|
||||
if (authEnabled) {
|
||||
if (isAuthenticated && data.user) {
|
||||
currentUser = data.user;
|
||||
showAuthenticatedUI();
|
||||
} else {
|
||||
showLoginPage();
|
||||
}
|
||||
} else {
|
||||
// OIDC not enabled, show main content
|
||||
showMainContent();
|
||||
}
|
||||
|
||||
return { enabled: authEnabled, authenticated: isAuthenticated, user: currentUser };
|
||||
} catch (error) {
|
||||
console.error('Error checking auth status:', error);
|
||||
// If auth check fails and we're on a protected route, show login
|
||||
if (authEnabled) {
|
||||
showLoginPage();
|
||||
} else {
|
||||
showMainContent();
|
||||
}
|
||||
return { enabled: false, authenticated: false, user: null };
|
||||
}
|
||||
}
|
||||
|
||||
// Get current user info
|
||||
async function getUserInfo() {
|
||||
try {
|
||||
const response = await fetch('/auth/user', {
|
||||
headers: serverHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
isAuthenticated = false;
|
||||
currentUser = null;
|
||||
showLoginPage();
|
||||
return null;
|
||||
}
|
||||
throw new Error('Failed to get user info');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (data.authenticated && data.user) {
|
||||
currentUser = data.user;
|
||||
isAuthenticated = true;
|
||||
return data.user;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error getting user info:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle login - redirect to login endpoint with action parameter
|
||||
function handleLogin() {
|
||||
const loginLoading = document.getElementById('loginLoading');
|
||||
const loginError = document.getElementById('loginError');
|
||||
const loginErrorText = document.getElementById('loginErrorText');
|
||||
const loginButton = event?.target?.closest('button');
|
||||
|
||||
// Show loading state
|
||||
if (loginLoading) loginLoading.classList.remove('hidden');
|
||||
if (loginButton) {
|
||||
loginButton.disabled = true;
|
||||
loginButton.classList.add('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
|
||||
// Hide error if shown
|
||||
if (loginError) {
|
||||
loginError.classList.add('hidden');
|
||||
if (loginErrorText) loginErrorText.textContent = '';
|
||||
}
|
||||
|
||||
// Redirect to login endpoint with action=redirect to trigger OIDC redirect
|
||||
window.location.href = '/auth/login?action=redirect';
|
||||
}
|
||||
|
||||
// Handle logout - use direct redirect instead of fetch to avoid CORS issues
|
||||
function handleLogout() {
|
||||
// Clear local state
|
||||
isAuthenticated = false;
|
||||
currentUser = null;
|
||||
|
||||
// Direct redirect to logout endpoint (server will handle redirect to provider)
|
||||
// Using window.location.href instead of fetch to avoid CORS issues with redirects
|
||||
window.location.href = '/auth/logout';
|
||||
}
|
||||
|
||||
// Show login page
|
||||
function showLoginPage() {
|
||||
const loginPage = document.getElementById('loginPage');
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
const nav = document.querySelector('nav');
|
||||
|
||||
// Hide main content and nav immediately
|
||||
if (mainContent) {
|
||||
mainContent.style.display = 'none';
|
||||
mainContent.classList.add('hidden');
|
||||
}
|
||||
if (nav) {
|
||||
nav.style.display = 'none';
|
||||
nav.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Show login page
|
||||
if (loginPage) {
|
||||
loginPage.style.display = 'flex';
|
||||
loginPage.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Show main content (when authenticated or OIDC disabled)
|
||||
function showMainContent() {
|
||||
const loginPage = document.getElementById('loginPage');
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
const nav = document.querySelector('nav');
|
||||
|
||||
// Hide login page immediately
|
||||
if (loginPage) {
|
||||
loginPage.style.display = 'none';
|
||||
loginPage.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Show main content and nav
|
||||
if (mainContent) {
|
||||
mainContent.style.display = '';
|
||||
mainContent.classList.remove('hidden');
|
||||
}
|
||||
if (nav) {
|
||||
nav.style.display = '';
|
||||
nav.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle user menu dropdown
|
||||
function toggleUserMenu() {
|
||||
const dropdown = document.getElementById('userMenuDropdown');
|
||||
if (dropdown) {
|
||||
dropdown.classList.toggle('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Close user menu when clicking outside
|
||||
document.addEventListener('click', function(event) {
|
||||
const userMenuButton = document.getElementById('userMenuButton');
|
||||
const userMenuDropdown = document.getElementById('userMenuDropdown');
|
||||
|
||||
if (userMenuButton && userMenuDropdown &&
|
||||
!userMenuButton.contains(event.target) &&
|
||||
!userMenuDropdown.contains(event.target)) {
|
||||
userMenuDropdown.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
// Show authenticated UI (update header with user info)
|
||||
function showAuthenticatedUI() {
|
||||
showMainContent();
|
||||
|
||||
const userInfoContainer = document.getElementById('userInfoContainer');
|
||||
const userDisplayName = document.getElementById('userDisplayName');
|
||||
const userMenuDisplayName = document.getElementById('userMenuDisplayName');
|
||||
const userMenuEmail = document.getElementById('userMenuEmail');
|
||||
const mobileUserInfoContainer = document.getElementById('mobileUserInfoContainer');
|
||||
const mobileUserDisplayName = document.getElementById('mobileUserDisplayName');
|
||||
const mobileUserEmail = document.getElementById('mobileUserEmail');
|
||||
|
||||
if (userInfoContainer && currentUser) {
|
||||
userInfoContainer.classList.remove('hidden');
|
||||
|
||||
const displayName = currentUser.name || currentUser.username || currentUser.email;
|
||||
|
||||
if (userDisplayName) {
|
||||
userDisplayName.textContent = displayName;
|
||||
}
|
||||
|
||||
if (userMenuDisplayName) {
|
||||
userMenuDisplayName.textContent = displayName;
|
||||
}
|
||||
|
||||
if (userMenuEmail && currentUser.email) {
|
||||
userMenuEmail.textContent = currentUser.email;
|
||||
}
|
||||
}
|
||||
|
||||
// Update mobile menu
|
||||
if (mobileUserInfoContainer && currentUser) {
|
||||
mobileUserInfoContainer.classList.remove('hidden');
|
||||
|
||||
const displayName = currentUser.name || currentUser.username || currentUser.email;
|
||||
|
||||
if (mobileUserDisplayName) {
|
||||
mobileUserDisplayName.textContent = displayName;
|
||||
}
|
||||
|
||||
if (mobileUserEmail && currentUser.email) {
|
||||
mobileUserEmail.textContent = currentUser.email;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 401/403 responses from API
|
||||
function handleAuthError(response) {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
if (authEnabled) {
|
||||
isAuthenticated = false;
|
||||
currentUser = null;
|
||||
showLoginPage();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -3,6 +3,29 @@
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function() {
|
||||
showLoading(true);
|
||||
|
||||
// Check authentication status first (if auth.js is loaded)
|
||||
if (typeof checkAuthStatus === 'function') {
|
||||
checkAuthStatus().then(function(authStatus) {
|
||||
// Only proceed with initialization if authenticated or OIDC disabled
|
||||
if (!authStatus.enabled || authStatus.authenticated) {
|
||||
initializeApp();
|
||||
} else {
|
||||
// Not authenticated, login page will be shown by checkAuthStatus
|
||||
showLoading(false);
|
||||
}
|
||||
}).catch(function(err) {
|
||||
console.error('Auth check failed:', err);
|
||||
// Proceed with initialization anyway (fallback)
|
||||
initializeApp();
|
||||
});
|
||||
} else {
|
||||
// Auth.js not loaded, proceed normally
|
||||
initializeApp();
|
||||
}
|
||||
});
|
||||
|
||||
function initializeApp() {
|
||||
// Only display external IP if the element exists (not disabled via template variable)
|
||||
if (document.getElementById('external-ip')) {
|
||||
displayExternalIP();
|
||||
@@ -148,4 +171,4 @@ window.addEventListener('DOMContentLoaded', function() {
|
||||
advancedIntegrationSelect.addEventListener('change', updateAdvancedIntegrationFields);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
<!-- ******************************************************************* -->
|
||||
<!-- Navigation START -->
|
||||
<!-- ******************************************************************* -->
|
||||
<nav class="bg-blue-600 text-white shadow-lg">
|
||||
<nav class="hidden bg-blue-600 text-white shadow-lg">
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div class="flex items-center justify-between h-16">
|
||||
<div class="flex items-center">
|
||||
@@ -80,6 +80,25 @@
|
||||
<div id="clockDisplay" class="ml-4 text-sm font-mono">
|
||||
<span id="clockTime">--:--:--</span>
|
||||
</div>
|
||||
<!-- User info and logout (shown when authenticated) -->
|
||||
<div id="userInfoContainer" class="hidden ml-4 flex items-center gap-3 border-l border-blue-500 pl-4">
|
||||
<div class="relative">
|
||||
<button id="userMenuButton" onclick="toggleUserMenu()" class="flex items-center gap-2 px-3 py-2 rounded text-sm font-medium hover:bg-blue-700 transition-colors focus:outline-none">
|
||||
<span id="userDisplayName" class="font-medium"></span>
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<!-- User dropdown menu -->
|
||||
<div id="userMenuDropdown" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 border border-gray-200">
|
||||
<div class="px-4 py-2 border-b border-gray-200">
|
||||
<div class="text-sm font-medium text-gray-900" id="userMenuDisplayName"></div>
|
||||
<div class="text-xs text-gray-500" id="userMenuEmail"></div>
|
||||
</div>
|
||||
<button onclick="handleLogout()" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors" data-i18n="auth.logout">Logout</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="md:hidden">
|
||||
@@ -97,14 +116,79 @@
|
||||
<a href="#" onclick="showSection('dashboardSection')" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-blue-700 transition-colors" data-i18n="nav.dashboard">Dashboard</a>
|
||||
<a href="#" onclick="showSection('filterSection')" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-blue-700 transition-colors" data-i18n="nav.filter_debug">Filter Debug</a>
|
||||
<a href="#" onclick="showSection('settingsSection')" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-blue-700 transition-colors" data-i18n="nav.settings">Settings</a>
|
||||
<!-- User info and logout in mobile menu (shown when authenticated) -->
|
||||
<div id="mobileUserInfoContainer" class="hidden border-t border-blue-500 mt-2 pt-2">
|
||||
<div class="px-3 py-2">
|
||||
<div class="text-sm font-medium" id="mobileUserDisplayName"></div>
|
||||
<div class="text-xs text-blue-200" id="mobileUserEmail"></div>
|
||||
</div>
|
||||
<button onclick="handleLogout()" class="w-full text-left block px-3 py-2 rounded-md text-base font-medium hover:bg-blue-700 transition-colors" data-i18n="auth.logout">Logout</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<!-- ************************ Navigation END *************************** -->
|
||||
|
||||
<!-- Login Page (shown when not authenticated) -->
|
||||
<div id="loginPage" class="min-h-screen flex items-center justify-center bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div class="max-w-md w-full">
|
||||
<!-- Login Card -->
|
||||
<div class="bg-white rounded-lg shadow-lg p-8 border border-gray-200">
|
||||
<!-- Logo and Title -->
|
||||
<div class="text-center mb-8">
|
||||
<div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-blue-600 mb-4">
|
||||
<svg class="h-10 w-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h2 class="text-3xl font-bold text-gray-900 mb-2" data-i18n="auth.login_title">Sign in to Fail2ban UI</h2>
|
||||
<p class="text-sm text-gray-600" data-i18n="auth.login_description">Please authenticate to access the management interface</p>
|
||||
</div>
|
||||
|
||||
<!-- Error Message -->
|
||||
<div id="loginError" class="hidden bg-red-50 border-l-4 border-red-400 text-red-700 px-4 py-3 rounded mb-6">
|
||||
<div class="flex">
|
||||
<div class="flex-shrink-0">
|
||||
<svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-3">
|
||||
<p class="text-sm font-medium" id="loginErrorText"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Login Button -->
|
||||
<div class="mb-6">
|
||||
<button type="button" onclick="handleLogin()" class="w-full flex justify-center items-center py-3 px-4 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
|
||||
<svg class="h-5 w-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
|
||||
</svg>
|
||||
<span data-i18n="auth.login_button">Sign in with OIDC</span>
|
||||
</button>
|
||||
|
||||
<!-- Loading State -->
|
||||
<div id="loginLoading" class="hidden text-center py-4">
|
||||
<div class="inline-flex items-center">
|
||||
<div class="h-5 w-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mr-3"></div>
|
||||
<p class="text-sm text-gray-600 font-medium" data-i18n="auth.logging_in">Redirecting to login...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer Info -->
|
||||
<div class="pt-6 border-t border-gray-200">
|
||||
<p class="text-xs text-center text-gray-500">
|
||||
Secure authentication via OpenID Connect
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Content -->
|
||||
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<main id="mainContent" class="hidden max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<!-- ******************************************************************* -->
|
||||
<!-- Dashboard Page START -->
|
||||
<!-- ******************************************************************* -->
|
||||
@@ -1397,6 +1481,7 @@
|
||||
<script src="/static/js/websocket.js?v={{.version}}"></script>
|
||||
<script src="/static/js/header.js?v={{.version}}"></script>
|
||||
<script src="/static/js/lotr.js?v={{.version}}"></script>
|
||||
<script src="/static/js/auth.js?v={{.version}}"></script>
|
||||
<script src="/static/js/init.js?v={{.version}}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user