mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2026-01-14 19:32:29 +00:00
Compare commits
3 Commits
f5f18bc2f6
...
refactor/a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59e997da26 | ||
|
|
9014be90aa | ||
|
|
f978ae155a |
19
cmd/root.go
19
cmd/root.go
@@ -1,6 +1,7 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"tinyauth/internal/bootstrap"
|
"tinyauth/internal/bootstrap"
|
||||||
"tinyauth/internal/config"
|
"tinyauth/internal/config"
|
||||||
@@ -14,15 +15,16 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type rootCmd struct {
|
type rootCmd struct {
|
||||||
root *cobra.Command
|
root *cobra.Command
|
||||||
cmd *cobra.Command
|
cmd *cobra.Command
|
||||||
|
viper *viper.Viper
|
||||||
viper *viper.Viper
|
aclFlags map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRootCmd() *rootCmd {
|
func newRootCmd() *rootCmd {
|
||||||
return &rootCmd{
|
return &rootCmd{
|
||||||
viper: viper.New(),
|
viper: viper.New(),
|
||||||
|
aclFlags: make(map[string]string),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,6 +34,9 @@ func (c *rootCmd) Register() {
|
|||||||
Short: "The simplest way to protect your apps with a login screen",
|
Short: "The simplest way to protect your apps with a login screen",
|
||||||
Long: `Tinyauth is a simple authentication middleware that adds a simple login screen or OAuth with Google, Github or any other provider to all of your docker apps.`,
|
Long: `Tinyauth is a simple authentication middleware that adds a simple login screen or OAuth with Google, Github or any other provider to all of your docker apps.`,
|
||||||
Run: c.run,
|
Run: c.run,
|
||||||
|
FParseErrWhitelist: cobra.FParseErrWhitelist{
|
||||||
|
UnknownFlags: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
c.viper.AutomaticEnv()
|
c.viper.AutomaticEnv()
|
||||||
@@ -116,7 +121,7 @@ func (c *rootCmd) run(cmd *cobra.Command, args []string) {
|
|||||||
log.Warn().Msg("Log level set to trace, this will log sensitive information!")
|
log.Warn().Msg("Log level set to trace, this will log sensitive information!")
|
||||||
}
|
}
|
||||||
|
|
||||||
app := bootstrap.NewBootstrapApp(conf)
|
app := bootstrap.NewBootstrapApp(conf, c.aclFlags)
|
||||||
|
|
||||||
err = app.Setup()
|
err = app.Setup()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -126,6 +131,8 @@ func (c *rootCmd) run(cmd *cobra.Command, args []string) {
|
|||||||
|
|
||||||
func Run() {
|
func Run() {
|
||||||
rootCmd := newRootCmd()
|
rootCmd := newRootCmd()
|
||||||
|
rootCmd.aclFlags = utils.ExtractACLFlags(os.Args[1:])
|
||||||
|
|
||||||
rootCmd.Register()
|
rootCmd.Register()
|
||||||
root := rootCmd.GetCmd()
|
root := rootCmd.GetCmd()
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
<link rel="manifest" href="/site.webmanifest" />
|
<link rel="manifest" href="/site.webmanifest" />
|
||||||
<title>Tinyauth</title>
|
<title>Tinyauth</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body class="dark">
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -18,10 +18,9 @@ export const LanguageSelector = () => {
|
|||||||
setLanguage(option as SupportedLanguage);
|
setLanguage(option as SupportedLanguage);
|
||||||
i18n.changeLanguage(option as SupportedLanguage);
|
i18n.changeLanguage(option as SupportedLanguage);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Select onValueChange={handleSelect} value={language}>
|
<Select onValueChange={handleSelect} value={language}>
|
||||||
<SelectTrigger className="bg-card">
|
<SelectTrigger className="absolute top-5 right-5">
|
||||||
<SelectValue placeholder="Select language" />
|
<SelectValue placeholder="Select language" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { LanguageSelector } from "../language/language";
|
|||||||
import { Outlet } from "react-router";
|
import { Outlet } from "react-router";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { DomainWarning } from "../domain-warning/domain-warning";
|
import { DomainWarning } from "../domain-warning/domain-warning";
|
||||||
import { ThemeSwitch } from "../theme-switch/theme-switch";
|
|
||||||
|
|
||||||
const BaseLayout = ({ children }: { children: React.ReactNode }) => {
|
const BaseLayout = ({ children }: { children: React.ReactNode }) => {
|
||||||
const { backgroundImage, title } = useAppContext();
|
const { backgroundImage, title } = useAppContext();
|
||||||
@@ -21,10 +20,7 @@ const BaseLayout = ({ children }: { children: React.ReactNode }) => {
|
|||||||
backgroundPosition: "center",
|
backgroundPosition: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="absolute top-5 right-5 flex flex-row gap-2">
|
<LanguageSelector />
|
||||||
<ThemeSwitch />
|
|
||||||
<LanguageSelector />
|
|
||||||
</div>
|
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
import { createContext, useEffect, useState } from "react";
|
|
||||||
|
|
||||||
interface ThemeSchema {
|
|
||||||
darkMode: boolean;
|
|
||||||
setDarkMode: (darkMode: boolean) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ThemeContext = createContext<ThemeSchema | null>(null);
|
|
||||||
|
|
||||||
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
|
|
||||||
const [darkMode, setDarkMode] = useState<boolean>(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const storedTheme = localStorage.getItem("tinyauth-theme");
|
|
||||||
if (storedTheme) {
|
|
||||||
setDarkMode(storedTheme === "dark");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const prefersDark = window.matchMedia(
|
|
||||||
"(prefers-color-scheme: dark)",
|
|
||||||
).matches;
|
|
||||||
setDarkMode(prefersDark);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const rootElement = document.documentElement;
|
|
||||||
rootElement.classList.remove("dark", "light");
|
|
||||||
rootElement.classList.add(darkMode ? "dark" : "light");
|
|
||||||
}, [darkMode]);
|
|
||||||
|
|
||||||
const values = {
|
|
||||||
darkMode,
|
|
||||||
setDarkMode: (darkMode: boolean) => {
|
|
||||||
localStorage.setItem("tinyauth-theme", darkMode ? "dark" : "light");
|
|
||||||
setDarkMode(darkMode);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ThemeContext.Provider value={values}>{children}</ThemeContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useTheme = () => {
|
|
||||||
const context = React.useContext(ThemeContext);
|
|
||||||
|
|
||||||
if (!context) {
|
|
||||||
throw new Error("useTheme must be used within a ThemeProvider");
|
|
||||||
}
|
|
||||||
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import { MoonIcon, SunIcon } from "lucide-react";
|
|
||||||
import { useTheme } from "../providers/theme-provider";
|
|
||||||
import { Button } from "../ui/button";
|
|
||||||
|
|
||||||
export const ThemeSwitch = () => {
|
|
||||||
const { darkMode, setDarkMode } = useTheme();
|
|
||||||
|
|
||||||
const toggleTheme = () => {
|
|
||||||
setDarkMode(!darkMode);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
className="bg-card hover:bg-card/90 text-card-foreground"
|
|
||||||
aria-label={`Switch to ${darkMode ? "light" : "dark"} mode`}
|
|
||||||
onClick={() => {
|
|
||||||
toggleTheme();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{darkMode ? <SunIcon /> : <MoonIcon />}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";
|
|||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
|
|
||||||
const buttonVariants = cva(
|
const buttonVariants = cva(
|
||||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive hover:cursor-pointer",
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ function SelectTrigger({
|
|||||||
data-slot="select-trigger"
|
data-slot="select-trigger"
|
||||||
data-size={size}
|
data-size={size}
|
||||||
className={cn(
|
className={cn(
|
||||||
"hover:cursor-pointer border-input data-[placeholder]:text-card-foreground [&_svg:not([class*='text-'])]:text-card-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-card dark:hover:bg-card/90 flex w-fit items-center justify-between gap-2 rounded-md border bg-card hover:bg-card/90 px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-card dark:hover:bg-card/90 flex w-fit items-center justify-between gap-2 rounded-md border bg-card hover:bg-card/90 px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { useTheme } from "../providers/theme-provider";
|
import { useTheme } from "next-themes";
|
||||||
import { Toaster as Sonner, ToasterProps } from "sonner";
|
import { Toaster as Sonner, ToasterProps } from "sonner";
|
||||||
|
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
const { darkMode } = useTheme();
|
const { theme = "system" } = useTheme();
|
||||||
const theme = darkMode ? "dark" : "light";
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sonner
|
<Sonner
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|||||||
import { AppContextProvider } from "./context/app-context.tsx";
|
import { AppContextProvider } from "./context/app-context.tsx";
|
||||||
import { UserContextProvider } from "./context/user-context.tsx";
|
import { UserContextProvider } from "./context/user-context.tsx";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
import { ThemeProvider } from "./components/providers/theme-provider.tsx";
|
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
@@ -25,27 +24,25 @@ createRoot(document.getElementById("root")!).render(
|
|||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<AppContextProvider>
|
<AppContextProvider>
|
||||||
<UserContextProvider>
|
<UserContextProvider>
|
||||||
<ThemeProvider>
|
<BrowserRouter>
|
||||||
<BrowserRouter>
|
<Routes>
|
||||||
<Routes>
|
<Route element={<Layout />} errorElement={<ErrorPage />}>
|
||||||
<Route element={<Layout />} errorElement={<ErrorPage />}>
|
<Route path="/" element={<App />} />
|
||||||
<Route path="/" element={<App />} />
|
<Route path="/login" element={<LoginPage />} />
|
||||||
<Route path="/login" element={<LoginPage />} />
|
<Route path="/logout" element={<LogoutPage />} />
|
||||||
<Route path="/logout" element={<LogoutPage />} />
|
<Route path="/continue" element={<ContinuePage />} />
|
||||||
<Route path="/continue" element={<ContinuePage />} />
|
<Route path="/totp" element={<TotpPage />} />
|
||||||
<Route path="/totp" element={<TotpPage />} />
|
<Route
|
||||||
<Route
|
path="/forgot-password"
|
||||||
path="/forgot-password"
|
element={<ForgotPasswordPage />}
|
||||||
element={<ForgotPasswordPage />}
|
/>
|
||||||
/>
|
<Route path="/unauthorized" element={<UnauthorizedPage />} />
|
||||||
<Route path="/unauthorized" element={<UnauthorizedPage />} />
|
<Route path="/error" element={<ErrorPage />} />
|
||||||
<Route path="/error" element={<ErrorPage />} />
|
<Route path="*" element={<NotFoundPage />} />
|
||||||
<Route path="*" element={<NotFoundPage />} />
|
</Route>
|
||||||
</Route>
|
</Routes>
|
||||||
</Routes>
|
</BrowserRouter>
|
||||||
</BrowserRouter>
|
<Toaster />
|
||||||
<Toaster />
|
|
||||||
</ThemeProvider>
|
|
||||||
</UserContextProvider>
|
</UserContextProvider>
|
||||||
</AppContextProvider>
|
</AppContextProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
@@ -37,13 +37,15 @@ type Service interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type BootstrapApp struct {
|
type BootstrapApp struct {
|
||||||
config config.Config
|
config config.Config
|
||||||
uuid string
|
aclFlags map[string]string
|
||||||
|
uuid string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBootstrapApp(config config.Config) *BootstrapApp {
|
func NewBootstrapApp(config config.Config, aclFlags map[string]string) *BootstrapApp {
|
||||||
return &BootstrapApp{
|
return &BootstrapApp{
|
||||||
config: config,
|
config: config,
|
||||||
|
aclFlags: aclFlags,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,6 +142,7 @@ func (app *BootstrapApp) Setup() error {
|
|||||||
// Create services
|
// Create services
|
||||||
dockerService := service.NewDockerService()
|
dockerService := service.NewDockerService()
|
||||||
aclsService := service.NewAccessControlsService(dockerService)
|
aclsService := service.NewAccessControlsService(dockerService)
|
||||||
|
aclsService.SetACLFlags(app.aclFlags)
|
||||||
authService := service.NewAuthService(authConfig, dockerService, ldapService, database)
|
authService := service.NewAuthService(authConfig, dockerService, ldapService, database)
|
||||||
oauthBrokerService := service.NewOAuthBrokerService(oauthProviders)
|
oauthBrokerService := service.NewOAuthBrokerService(oauthProviders)
|
||||||
|
|
||||||
|
|||||||
@@ -4,70 +4,39 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"tinyauth/internal/config"
|
"tinyauth/internal/config"
|
||||||
"tinyauth/internal/utils/decoders"
|
"tinyauth/internal/utils"
|
||||||
|
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AccessControlsService struct {
|
type AccessControlsService struct {
|
||||||
docker *DockerService
|
docker *DockerService
|
||||||
envACLs config.Apps
|
envACLs config.Apps
|
||||||
|
aclFlags map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewAccessControlsService(docker *DockerService) *AccessControlsService {
|
func NewAccessControlsService(docker *DockerService) *AccessControlsService {
|
||||||
return &AccessControlsService{
|
return &AccessControlsService{
|
||||||
docker: docker,
|
docker: docker,
|
||||||
|
aclFlags: make(map[string]string),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (acls *AccessControlsService) SetACLFlags(flags map[string]string) {
|
||||||
|
acls.aclFlags = flags
|
||||||
|
}
|
||||||
|
|
||||||
func (acls *AccessControlsService) Init() error {
|
func (acls *AccessControlsService) Init() error {
|
||||||
acls.envACLs = config.Apps{}
|
|
||||||
env := os.Environ()
|
env := os.Environ()
|
||||||
appEnvVars := []string{}
|
|
||||||
|
|
||||||
for _, e := range env {
|
apps, err := utils.GetACLsConfig(env, acls.aclFlags)
|
||||||
if strings.HasPrefix(e, "TINYAUTH_APPS_") {
|
|
||||||
appEnvVars = append(appEnvVars, e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err := acls.loadEnvACLs(appEnvVars)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (acls *AccessControlsService) loadEnvACLs(appEnvVars []string) error {
|
|
||||||
if len(appEnvVars) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
envAcls := map[string]string{}
|
|
||||||
|
|
||||||
for _, e := range appEnvVars {
|
|
||||||
parts := strings.SplitN(e, "=", 2)
|
|
||||||
if len(parts) != 2 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Normalize key, this should use the same normalization logic as in utils/decoders/decoders.go
|
|
||||||
key := parts[0]
|
|
||||||
key = strings.ToLower(key)
|
|
||||||
key = strings.ReplaceAll(key, "_", ".")
|
|
||||||
value := parts[1]
|
|
||||||
envAcls[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
apps, err := decoders.DecodeLabels(envAcls)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
acls.envACLs = apps
|
acls.envACLs = apps
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -208,3 +208,53 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st
|
|||||||
// Return combined providers
|
// Return combined providers
|
||||||
return providers, nil
|
return providers, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetACLsConfig(env []string, flagsMap map[string]string) (config.Apps, error) {
|
||||||
|
apps := config.Apps{Apps: make(map[string]config.App)}
|
||||||
|
|
||||||
|
envMap := make(map[string]string)
|
||||||
|
|
||||||
|
for _, e := range env {
|
||||||
|
pair := strings.SplitN(e, "=", 2)
|
||||||
|
if len(pair) == 2 {
|
||||||
|
envMap[pair[0]] = pair[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
envApps, err := decoders.DecodeACLEnv[config.Apps](envMap, "apps")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return config.Apps{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if envApps.Apps != nil {
|
||||||
|
maps.Copy(apps.Apps, envApps.Apps)
|
||||||
|
}
|
||||||
|
|
||||||
|
flagApps, err := decoders.DecodeACLFlags[config.Apps](flagsMap, "apps")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return config.Apps{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if flagApps.Apps != nil {
|
||||||
|
maps.Copy(apps.Apps, flagApps.Apps)
|
||||||
|
}
|
||||||
|
|
||||||
|
return apps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtractACLFlags(args []string) map[string]string {
|
||||||
|
aclFlags := make(map[string]string)
|
||||||
|
|
||||||
|
for _, arg := range args {
|
||||||
|
if strings.HasPrefix(arg, "--apps-") || strings.HasPrefix(arg, "--tinyauth-apps-") {
|
||||||
|
pair := strings.SplitN(arg[2:], "=", 2)
|
||||||
|
if len(pair) == 2 {
|
||||||
|
aclFlags[pair[0]] = pair[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return aclFlags
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,71 @@ import (
|
|||||||
"github.com/stoewer/go-strcase"
|
"github.com/stoewer/go-strcase"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func ParsePath(parts []string, idx int, t reflect.Type) []string {
|
||||||
|
if idx >= len(parts) {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.Kind() == reflect.Map {
|
||||||
|
|
||||||
|
if idx >= len(parts) {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
elemType := t.Elem()
|
||||||
|
keyEndIdx := idx + 1
|
||||||
|
|
||||||
|
if elemType.Kind() == reflect.Struct {
|
||||||
|
for i := idx + 1; i < len(parts); i++ {
|
||||||
|
found := false
|
||||||
|
|
||||||
|
for j := 0; j < elemType.NumField(); j++ {
|
||||||
|
field := elemType.Field(j)
|
||||||
|
if strings.EqualFold(parts[i], field.Name) {
|
||||||
|
keyEndIdx = i
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if found {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
keyParts := parts[idx:keyEndIdx]
|
||||||
|
keyName := strings.ToLower(strings.Join(keyParts, "_"))
|
||||||
|
|
||||||
|
rest := ParsePath(parts, keyEndIdx, elemType)
|
||||||
|
result := append([]string{keyName}, rest...)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.Kind() == reflect.Struct {
|
||||||
|
for i := 0; i < t.NumField(); i++ {
|
||||||
|
field := t.Field(i)
|
||||||
|
if field.Type.Kind() == reflect.Map {
|
||||||
|
rest := ParsePath(parts, idx, field.Type)
|
||||||
|
if len(rest) > 0 {
|
||||||
|
return rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < t.NumField(); i++ {
|
||||||
|
field := t.Field(i)
|
||||||
|
if strings.EqualFold(parts[idx], field.Name) {
|
||||||
|
rest := ParsePath(parts, idx+1, field.Type)
|
||||||
|
result := append([]string{strings.ToLower(field.Name)}, rest...)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeKeys[T any](input map[string]string, root string, sep string) map[string]string {
|
func normalizeKeys[T any](input map[string]string, root string, sep string) map[string]string {
|
||||||
knownKeys := getKnownKeys[T]()
|
knownKeys := getKnownKeys[T]()
|
||||||
normalized := make(map[string]string)
|
normalized := make(map[string]string)
|
||||||
@@ -74,3 +139,57 @@ func getKnownKeys[T any]() []string {
|
|||||||
|
|
||||||
return keys
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeACLKeys[T any](input map[string]string, root string, sep string) map[string]string {
|
||||||
|
normalized := make(map[string]string)
|
||||||
|
var t T
|
||||||
|
rootType := reflect.TypeOf(t)
|
||||||
|
|
||||||
|
for k, v := range input {
|
||||||
|
parts := strings.Split(strings.ToLower(k), sep)
|
||||||
|
|
||||||
|
if len(parts) < 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two cases:
|
||||||
|
// 1. Keys starting with "tinyauth" (env vars): tinyauth_apps_...
|
||||||
|
// 2. Keys starting with root directly (flags): apps-...
|
||||||
|
startIdx := 0
|
||||||
|
if parts[0] == "tinyauth" {
|
||||||
|
if len(parts) < 3 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if parts[1] != root {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
startIdx = 2 // Skip "tinyauth" and root
|
||||||
|
} else if parts[0] == root {
|
||||||
|
startIdx = 1 // Skip root only
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if startIdx < len(parts) {
|
||||||
|
parsedParts := ParsePath(parts[startIdx:], 0, rootType)
|
||||||
|
|
||||||
|
if len(parsedParts) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
final := "tinyauth." + root
|
||||||
|
|
||||||
|
for _, part := range parsedParts {
|
||||||
|
if strings.Contains(part, "_") {
|
||||||
|
final += "." + part
|
||||||
|
} else {
|
||||||
|
final += "." + strcase.LowerCamelCase(part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
normalized[final] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized
|
||||||
|
}
|
||||||
|
|||||||
@@ -17,3 +17,17 @@ func DecodeEnv[T any, C any](env map[string]string, subName string) (T, error) {
|
|||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func DecodeACLEnv[T any](env map[string]string, subName string) (T, error) {
|
||||||
|
var result T
|
||||||
|
|
||||||
|
normalized := normalizeACLKeys[T](env, subName, "_")
|
||||||
|
|
||||||
|
err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,6 +21,21 @@ func DecodeFlags[T any, C any](flags map[string]string, subName string) (T, erro
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func DecodeACLFlags[T any](flags map[string]string, subName string) (T, error) {
|
||||||
|
var result T
|
||||||
|
|
||||||
|
filtered := filterFlags(flags)
|
||||||
|
normalized := normalizeACLKeys[T](filtered, subName, "-")
|
||||||
|
|
||||||
|
err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
func filterFlags(flags map[string]string) map[string]string {
|
func filterFlags(flags map[string]string) map[string]string {
|
||||||
filtered := make(map[string]string)
|
filtered := make(map[string]string)
|
||||||
for k, v := range flags {
|
for k, v := range flags {
|
||||||
|
|||||||
Reference in New Issue
Block a user