mirror of
				https://github.com/steveiliop56/tinyauth.git
				synced 2025-10-31 06:05:43 +00:00 
			
		
		
		
	Compare commits
	
		
			2 Commits
		
	
	
		
			dependabot
			...
			feat/light
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | f5f18bc2f6 | ||
|   | 0227af6d2b | 
| @@ -1,5 +1,5 @@ | ||||
| # Site builder | ||||
| FROM oven/bun:1.3.1-alpine AS frontend-builder | ||||
| FROM oven/bun:1.3.0-alpine AS frontend-builder | ||||
|  | ||||
| WORKDIR /frontend | ||||
|  | ||||
|   | ||||
| @@ -1,5 +1,5 @@ | ||||
| # Site builder | ||||
| FROM oven/bun:1.3.1-alpine AS frontend-builder | ||||
| FROM oven/bun:1.3.0-alpine AS frontend-builder | ||||
|  | ||||
| WORKDIR /frontend | ||||
|  | ||||
|   | ||||
| @@ -12,7 +12,7 @@ | ||||
|     <link rel="manifest" href="/site.webmanifest" /> | ||||
|     <title>Tinyauth</title> | ||||
|   </head> | ||||
|   <body class="dark"> | ||||
|   <body> | ||||
|     <div id="root"></div> | ||||
|     <script type="module" src="/src/main.tsx"></script> | ||||
|   </body> | ||||
|   | ||||
| @@ -18,9 +18,10 @@ export const LanguageSelector = () => { | ||||
|     setLanguage(option as SupportedLanguage); | ||||
|     i18n.changeLanguage(option as SupportedLanguage); | ||||
|   }; | ||||
|  | ||||
|   return ( | ||||
|     <Select onValueChange={handleSelect} value={language}> | ||||
|       <SelectTrigger className="absolute top-5 right-5"> | ||||
|       <SelectTrigger className="bg-card"> | ||||
|         <SelectValue placeholder="Select language" /> | ||||
|       </SelectTrigger> | ||||
|       <SelectContent> | ||||
|   | ||||
| @@ -3,6 +3,7 @@ import { LanguageSelector } from "../language/language"; | ||||
| import { Outlet } from "react-router"; | ||||
| import { useCallback, useEffect, useState } from "react"; | ||||
| import { DomainWarning } from "../domain-warning/domain-warning"; | ||||
| import { ThemeSwitch } from "../theme-switch/theme-switch"; | ||||
|  | ||||
| const BaseLayout = ({ children }: { children: React.ReactNode }) => { | ||||
|   const { backgroundImage, title } = useAppContext(); | ||||
| @@ -20,7 +21,10 @@ const BaseLayout = ({ children }: { children: React.ReactNode }) => { | ||||
|         backgroundPosition: "center", | ||||
|       }} | ||||
|     > | ||||
|       <div className="absolute top-5 right-5 flex flex-row gap-2"> | ||||
|         <ThemeSwitch /> | ||||
|         <LanguageSelector /> | ||||
|       </div> | ||||
|       {children} | ||||
|     </div> | ||||
|   ); | ||||
|   | ||||
							
								
								
									
										53
									
								
								frontend/src/components/providers/theme-provider.tsx
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								frontend/src/components/providers/theme-provider.tsx
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,53 @@ | ||||
| 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; | ||||
| }; | ||||
							
								
								
									
										23
									
								
								frontend/src/components/theme-switch/theme-switch.tsx
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								frontend/src/components/theme-switch/theme-switch.tsx
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,23 @@ | ||||
| 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"; | ||||
|  | ||||
| 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", | ||||
|   "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", | ||||
|   { | ||||
|     variants: { | ||||
|       variant: { | ||||
|   | ||||
| @@ -35,7 +35,7 @@ function SelectTrigger({ | ||||
|       data-slot="select-trigger" | ||||
|       data-size={size} | ||||
|       className={cn( | ||||
|         "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", | ||||
|         "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", | ||||
|         className, | ||||
|       )} | ||||
|       {...props} | ||||
|   | ||||
| @@ -1,8 +1,9 @@ | ||||
| import { useTheme } from "next-themes"; | ||||
| import { useTheme } from "../providers/theme-provider"; | ||||
| import { Toaster as Sonner, ToasterProps } from "sonner"; | ||||
|  | ||||
| const Toaster = ({ ...props }: ToasterProps) => { | ||||
|   const { theme = "system" } = useTheme(); | ||||
|   const { darkMode } = useTheme(); | ||||
|   const theme = darkMode ? "dark" : "light"; | ||||
|  | ||||
|   return ( | ||||
|     <Sonner | ||||
|   | ||||
| @@ -16,6 +16,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; | ||||
| import { AppContextProvider } from "./context/app-context.tsx"; | ||||
| import { UserContextProvider } from "./context/user-context.tsx"; | ||||
| import { Toaster } from "@/components/ui/sonner"; | ||||
| import { ThemeProvider } from "./components/providers/theme-provider.tsx"; | ||||
|  | ||||
| const queryClient = new QueryClient(); | ||||
|  | ||||
| @@ -24,6 +25,7 @@ createRoot(document.getElementById("root")!).render( | ||||
|     <QueryClientProvider client={queryClient}> | ||||
|       <AppContextProvider> | ||||
|         <UserContextProvider> | ||||
|           <ThemeProvider> | ||||
|             <BrowserRouter> | ||||
|               <Routes> | ||||
|                 <Route element={<Layout />} errorElement={<ErrorPage />}> | ||||
| @@ -43,6 +45,7 @@ createRoot(document.getElementById("root")!).render( | ||||
|               </Routes> | ||||
|             </BrowserRouter> | ||||
|             <Toaster /> | ||||
|           </ThemeProvider> | ||||
|         </UserContextProvider> | ||||
|       </AppContextProvider> | ||||
|     </QueryClientProvider> | ||||
|   | ||||
							
								
								
									
										1
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										1
									
								
								go.mod
									
									
									
									
									
								
							| @@ -47,6 +47,7 @@ require ( | ||||
| 	github.com/quic-go/qpack v0.5.1 // indirect | ||||
| 	github.com/quic-go/quic-go v0.54.1 // indirect | ||||
| 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect | ||||
| 	github.com/stoewer/go-strcase v1.3.1 // indirect | ||||
| 	github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect | ||||
| 	go.opentelemetry.io/auto/sdk v1.1.0 // indirect | ||||
| 	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.34.0 // indirect | ||||
|   | ||||
							
								
								
									
										2
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										2
									
								
								go.sum
									
									
									
									
									
								
							| @@ -259,6 +259,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= | ||||
| github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= | ||||
| github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= | ||||
| github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= | ||||
| github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs= | ||||
| github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= | ||||
| github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | ||||
| github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= | ||||
| github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= | ||||
|   | ||||
| @@ -53,16 +53,16 @@ type Claims struct { | ||||
| } | ||||
|  | ||||
| type OAuthServiceConfig struct { | ||||
| 	ClientID           string   `key:"client-id"` | ||||
| 	ClientSecret       string   `key:"client-secret"` | ||||
| 	ClientSecretFile   string   `key:"client-secret-file"` | ||||
| 	Scopes             []string `key:"scopes"` | ||||
| 	RedirectURL        string   `key:"redirect-url"` | ||||
| 	AuthURL            string   `key:"auth-url"` | ||||
| 	TokenURL           string   `key:"token-url"` | ||||
| 	UserinfoURL        string   `key:"user-info-url"` | ||||
| 	InsecureSkipVerify bool     `key:"insecure-skip-verify"` | ||||
| 	Name               string   `key:"name"` | ||||
| 	ClientID           string `field:"client-id"` | ||||
| 	ClientSecret       string | ||||
| 	ClientSecretFile   string | ||||
| 	Scopes             []string | ||||
| 	RedirectURL        string `field:"redirect-url"` | ||||
| 	AuthURL            string `field:"auth-url"` | ||||
| 	TokenURL           string `field:"token-url"` | ||||
| 	UserinfoURL        string `field:"user-info-url"` | ||||
| 	InsecureSkipVerify bool | ||||
| 	Name               string | ||||
| } | ||||
|  | ||||
| var OverrideProviders = map[string]string{ | ||||
|   | ||||
| @@ -147,7 +147,7 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	envProviders, err := decoders.DecodeEnv(envMap) | ||||
| 	envProviders, err := decoders.DecodeEnv[config.Providers, config.OAuthServiceConfig](envMap, "providers") | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| @@ -167,7 +167,7 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	flagProviders, err := decoders.DecodeFlags(flagsMap) | ||||
| 	flagProviders, err := decoders.DecodeFlags[config.Providers, config.OAuthServiceConfig](flagsMap, "providers") | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
|   | ||||
| @@ -3,29 +3,24 @@ package decoders | ||||
| import ( | ||||
| 	"reflect" | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
|  | ||||
| 	"github.com/stoewer/go-strcase" | ||||
| ) | ||||
|  | ||||
| func NormalizeKeys(keys map[string]string, rootName string, sep string) map[string]string { | ||||
| func normalizeKeys[T any](input map[string]string, root string, sep string) map[string]string { | ||||
| 	knownKeys := getKnownKeys[T]() | ||||
| 	normalized := make(map[string]string) | ||||
| 	knownKeys := getKnownKeys() | ||||
|  | ||||
| 	for k, v := range keys { | ||||
| 		var finalKey []string | ||||
| 		var suffix string | ||||
| 		var camelClientName string | ||||
| 		var camelField string | ||||
| 	for k, v := range input { | ||||
| 		parts := []string{"tinyauth"} | ||||
|  | ||||
| 		finalKey = append(finalKey, rootName) | ||||
| 		finalKey = append(finalKey, "providers") | ||||
| 		lowerKey := strings.ToLower(k) | ||||
| 		key := strings.ToLower(k) | ||||
| 		key = strings.ReplaceAll(key, sep, "-") | ||||
|  | ||||
| 		if !strings.HasPrefix(lowerKey, "providers"+sep) { | ||||
| 			continue | ||||
| 		} | ||||
| 		suffix := "" | ||||
|  | ||||
| 		for _, known := range knownKeys { | ||||
| 			if strings.HasSuffix(lowerKey, strings.ReplaceAll(known, "-", sep)) { | ||||
| 			if strings.HasSuffix(key, known) { | ||||
| 				suffix = known | ||||
| 				break | ||||
| 			} | ||||
| @@ -35,55 +30,47 @@ func NormalizeKeys(keys map[string]string, rootName string, sep string) map[stri | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		if strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(lowerKey, "providers"+sep), strings.ReplaceAll(suffix, "-", sep))) == "" { | ||||
| 		parts = append(parts, root) | ||||
|  | ||||
| 		id := strings.TrimPrefix(key, root+"-") | ||||
| 		id = strings.TrimSuffix(id, "-"+suffix) | ||||
|  | ||||
| 		if id == "" { | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		clientNameParts := strings.Split(strings.TrimPrefix(strings.TrimSuffix(lowerKey, sep+strings.ReplaceAll(suffix, "-", sep)), "providers"+sep), sep) | ||||
| 		parts = append(parts, id) | ||||
| 		parts = append(parts, suffix) | ||||
|  | ||||
| 		for i, p := range clientNameParts { | ||||
| 			if i == 0 { | ||||
| 				camelClientName += p | ||||
| 				continue | ||||
| 		final := "" | ||||
|  | ||||
| 		for i, part := range parts { | ||||
| 			if i > 0 { | ||||
| 				final += "." | ||||
| 			} | ||||
| 			if p == "" { | ||||
| 				continue | ||||
| 			} | ||||
| 			camelClientName += strings.ToUpper(string([]rune(p)[0])) + string([]rune(p)[1:]) | ||||
| 			final += strcase.LowerCamelCase(part) | ||||
| 		} | ||||
|  | ||||
| 		finalKey = append(finalKey, camelClientName) | ||||
|  | ||||
| 		fieldParts := strings.Split(suffix, "-") | ||||
|  | ||||
| 		for i, p := range fieldParts { | ||||
| 			if i == 0 { | ||||
| 				camelField += p | ||||
| 				continue | ||||
| 			} | ||||
| 			if p == "" { | ||||
| 				continue | ||||
| 			} | ||||
| 			camelField += strings.ToUpper(string([]rune(p)[0])) + string([]rune(p)[1:]) | ||||
| 		} | ||||
|  | ||||
| 		finalKey = append(finalKey, camelField) | ||||
| 		normalized[strings.Join(finalKey, ".")] = v | ||||
| 		normalized[final] = v | ||||
| 	} | ||||
|  | ||||
| 	return normalized | ||||
| } | ||||
|  | ||||
| func getKnownKeys() []string { | ||||
| 	var known []string | ||||
| func getKnownKeys[T any]() []string { | ||||
| 	var keys []string | ||||
| 	var t T | ||||
|  | ||||
| 	p := config.OAuthServiceConfig{} | ||||
| 	v := reflect.ValueOf(p) | ||||
| 	typeOfP := v.Type() | ||||
| 	v := reflect.ValueOf(t) | ||||
| 	typeOfT := v.Type() | ||||
|  | ||||
| 	for field := range typeOfP.NumField() { | ||||
| 		known = append(known, typeOfP.Field(field).Tag.Get("key")) | ||||
| 	for field := range typeOfT.NumField() { | ||||
| 		if typeOfT.Field(field).Tag.Get("field") != "" { | ||||
| 			keys = append(keys, typeOfT.Field(field).Tag.Get("field")) | ||||
| 			continue | ||||
| 		} | ||||
| 		keys = append(keys, strcase.KebabCase(typeOfT.Field(field).Name)) | ||||
| 	} | ||||
|  | ||||
| 	return known | ||||
| 	return keys | ||||
| } | ||||
|   | ||||
| @@ -1,49 +0,0 @@ | ||||
| package decoders_test | ||||
|  | ||||
| import ( | ||||
| 	"testing" | ||||
| 	"tinyauth/internal/utils/decoders" | ||||
|  | ||||
| 	"gotest.tools/v3/assert" | ||||
| ) | ||||
|  | ||||
| func TestNormalizeKeys(t *testing.T) { | ||||
| 	// Test with env | ||||
| 	test := map[string]string{ | ||||
| 		"PROVIDERS_CLIENT1_CLIENT_ID":                    "my-client-id", | ||||
| 		"PROVIDERS_CLIENT1_CLIENT_SECRET":                "my-client-secret", | ||||
| 		"PROVIDERS_MY_AWESOME_CLIENT_CLIENT_ID":          "my-awesome-client-id", | ||||
| 		"PROVIDERS_MY_AWESOME_CLIENT_CLIENT_SECRET_FILE": "/path/to/secret", | ||||
| 		"I_LOOK_LIKE_A_KEY_CLIENT_ID":                    "should-not-appear", | ||||
| 		"PROVIDERS_CLIENT_ID":                            "should-not-appear", | ||||
| 	} | ||||
| 	expected := map[string]string{ | ||||
| 		"tinyauth.providers.client1.clientId":                 "my-client-id", | ||||
| 		"tinyauth.providers.client1.clientSecret":             "my-client-secret", | ||||
| 		"tinyauth.providers.myAwesomeClient.clientId":         "my-awesome-client-id", | ||||
| 		"tinyauth.providers.myAwesomeClient.clientSecretFile": "/path/to/secret", | ||||
| 	} | ||||
|  | ||||
| 	normalized := decoders.NormalizeKeys(test, "tinyauth", "_") | ||||
| 	assert.DeepEqual(t, normalized, expected) | ||||
|  | ||||
| 	// Test with flags (assume -- is already stripped) | ||||
| 	test = map[string]string{ | ||||
| 		"providers-client1-client-id":                    "my-client-id", | ||||
| 		"providers-client1-client-secret":                "my-client-secret", | ||||
| 		"providers-my-awesome-client-client-id":          "my-awesome-client-id", | ||||
| 		"providers-my-awesome-client-client-secret-file": "/path/to/secret", | ||||
| 		"providers-should-not-appear-client":             "should-not-appear", | ||||
| 		"i-look-like-a-key-client-id":                    "should-not-appear", | ||||
| 		"providers-client-id":                            "should-not-appear", | ||||
| 	} | ||||
| 	expected = map[string]string{ | ||||
| 		"tinyauth.providers.client1.clientId":                 "my-client-id", | ||||
| 		"tinyauth.providers.client1.clientSecret":             "my-client-secret", | ||||
| 		"tinyauth.providers.myAwesomeClient.clientId":         "my-awesome-client-id", | ||||
| 		"tinyauth.providers.myAwesomeClient.clientSecretFile": "/path/to/secret", | ||||
| 	} | ||||
|  | ||||
| 	normalized = decoders.NormalizeKeys(test, "tinyauth", "-") | ||||
| 	assert.DeepEqual(t, normalized, expected) | ||||
| } | ||||
| @@ -1,20 +1,19 @@ | ||||
| package decoders | ||||
|  | ||||
| import ( | ||||
| 	"tinyauth/internal/config" | ||||
|  | ||||
| 	"github.com/traefik/paerser/parser" | ||||
| ) | ||||
|  | ||||
| func DecodeEnv(env map[string]string) (config.Providers, error) { | ||||
| 	normalized := NormalizeKeys(env, "tinyauth", "_") | ||||
| 	var providers config.Providers | ||||
| func DecodeEnv[T any, C any](env map[string]string, subName string) (T, error) { | ||||
| 	var result T | ||||
|  | ||||
| 	err := parser.Decode(normalized, &providers, "tinyauth", "tinyauth.providers") | ||||
| 	normalized := normalizeKeys[C](env, subName, "_") | ||||
|  | ||||
| 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return config.Providers{}, err | ||||
| 		return result, err | ||||
| 	} | ||||
|  | ||||
| 	return providers, nil | ||||
| 	return result, nil | ||||
| } | ||||
|   | ||||
| @@ -9,52 +9,29 @@ import ( | ||||
| ) | ||||
|  | ||||
| func TestDecodeEnv(t *testing.T) { | ||||
| 	// Variables | ||||
| 	expected := config.Providers{ | ||||
| 		Providers: map[string]config.OAuthServiceConfig{ | ||||
| 			"client1": { | ||||
| 				ClientID:           "client1-id", | ||||
| 				ClientSecret:       "client1-secret", | ||||
| 				Scopes:             []string{"client1-scope1", "client1-scope2"}, | ||||
| 				RedirectURL:        "client1-redirect-url", | ||||
| 				AuthURL:            "client1-auth-url", | ||||
| 				UserinfoURL:        "client1-user-info-url", | ||||
| 				Name:               "Client1", | ||||
| 				InsecureSkipVerify: false, | ||||
| 			}, | ||||
| 			"client2": { | ||||
| 				ClientID:           "client2-id", | ||||
| 				ClientSecret:       "client2-secret", | ||||
| 				Scopes:             []string{"client2-scope1", "client2-scope2"}, | ||||
| 				RedirectURL:        "client2-redirect-url", | ||||
| 				AuthURL:            "client2-auth-url", | ||||
| 				UserinfoURL:        "client2-user-info-url", | ||||
| 				Name:               "My Awesome Client2", | ||||
| 				InsecureSkipVerify: false, | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
| 	test := map[string]string{ | ||||
| 		"PROVIDERS_CLIENT1_CLIENT_ID":            "client1-id", | ||||
| 		"PROVIDERS_CLIENT1_CLIENT_SECRET":        "client1-secret", | ||||
| 		"PROVIDERS_CLIENT1_SCOPES":               "client1-scope1,client1-scope2", | ||||
| 		"PROVIDERS_CLIENT1_REDIRECT_URL":         "client1-redirect-url", | ||||
| 		"PROVIDERS_CLIENT1_AUTH_URL":             "client1-auth-url", | ||||
| 		"PROVIDERS_CLIENT1_USER_INFO_URL":        "client1-user-info-url", | ||||
| 		"PROVIDERS_CLIENT1_NAME":                 "Client1", | ||||
| 		"PROVIDERS_CLIENT1_INSECURE_SKIP_VERIFY": "false", | ||||
| 		"PROVIDERS_CLIENT2_CLIENT_ID":            "client2-id", | ||||
| 		"PROVIDERS_CLIENT2_CLIENT_SECRET":        "client2-secret", | ||||
| 		"PROVIDERS_CLIENT2_SCOPES":               "client2-scope1,client2-scope2", | ||||
| 		"PROVIDERS_CLIENT2_REDIRECT_URL":         "client2-redirect-url", | ||||
| 		"PROVIDERS_CLIENT2_AUTH_URL":             "client2-auth-url", | ||||
| 		"PROVIDERS_CLIENT2_USER_INFO_URL":        "client2-user-info-url", | ||||
| 		"PROVIDERS_CLIENT2_NAME":                 "My Awesome Client2", | ||||
| 		"PROVIDERS_CLIENT2_INSECURE_SKIP_VERIFY": "false", | ||||
| 	// Setup | ||||
| 	env := map[string]string{ | ||||
| 		"PROVIDERS_GOOGLE_CLIENT_ID":        "google-client-id", | ||||
| 		"PROVIDERS_GOOGLE_CLIENT_SECRET":    "google-client-secret", | ||||
| 		"PROVIDERS_MY_GITHUB_CLIENT_ID":     "github-client-id", | ||||
| 		"PROVIDERS_MY_GITHUB_CLIENT_SECRET": "github-client-secret", | ||||
| 	} | ||||
|  | ||||
| 	// Test | ||||
| 	res, err := decoders.DecodeEnv(test) | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, expected, res) | ||||
| 	expected := config.Providers{ | ||||
| 		Providers: map[string]config.OAuthServiceConfig{ | ||||
| 			"google": { | ||||
| 				ClientID:     "google-client-id", | ||||
| 				ClientSecret: "google-client-secret", | ||||
| 			}, | ||||
| 			"myGithub": { | ||||
| 				ClientID:     "github-client-id", | ||||
| 				ClientSecret: "github-client-secret", | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	// Execute | ||||
| 	result, err := decoders.DecodeEnv[config.Providers, config.OAuthServiceConfig](env, "providers") | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, result, expected) | ||||
| } | ||||
|   | ||||
| @@ -2,23 +2,23 @@ package decoders | ||||
|  | ||||
| import ( | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
|  | ||||
| 	"github.com/traefik/paerser/parser" | ||||
| ) | ||||
|  | ||||
| func DecodeFlags(flags map[string]string) (config.Providers, error) { | ||||
| 	filtered := filterFlags(flags) | ||||
| 	normalized := NormalizeKeys(filtered, "tinyauth", "-") | ||||
| 	var providers config.Providers | ||||
| func DecodeFlags[T any, C any](flags map[string]string, subName string) (T, error) { | ||||
| 	var result T | ||||
|  | ||||
| 	err := parser.Decode(normalized, &providers, "tinyauth", "tinyauth.providers") | ||||
| 	filtered := filterFlags(flags) | ||||
| 	normalized := normalizeKeys[C](filtered, subName, "_") | ||||
|  | ||||
| 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return config.Providers{}, err | ||||
| 		return result, err | ||||
| 	} | ||||
|  | ||||
| 	return providers, nil | ||||
| 	return result, nil | ||||
| } | ||||
|  | ||||
| func filterFlags(flags map[string]string) map[string]string { | ||||
|   | ||||
| @@ -9,52 +9,29 @@ import ( | ||||
| ) | ||||
|  | ||||
| func TestDecodeFlags(t *testing.T) { | ||||
| 	// Variables | ||||
| 	expected := config.Providers{ | ||||
| 		Providers: map[string]config.OAuthServiceConfig{ | ||||
| 			"client1": { | ||||
| 				ClientID:           "client1-id", | ||||
| 				ClientSecret:       "client1-secret", | ||||
| 				Scopes:             []string{"client1-scope1", "client1-scope2"}, | ||||
| 				RedirectURL:        "client1-redirect-url", | ||||
| 				AuthURL:            "client1-auth-url", | ||||
| 				UserinfoURL:        "client1-user-info-url", | ||||
| 				Name:               "Client1", | ||||
| 				InsecureSkipVerify: false, | ||||
| 			}, | ||||
| 			"client2": { | ||||
| 				ClientID:           "client2-id", | ||||
| 				ClientSecret:       "client2-secret", | ||||
| 				Scopes:             []string{"client2-scope1", "client2-scope2"}, | ||||
| 				RedirectURL:        "client2-redirect-url", | ||||
| 				AuthURL:            "client2-auth-url", | ||||
| 				UserinfoURL:        "client2-user-info-url", | ||||
| 				Name:               "My Awesome Client2", | ||||
| 				InsecureSkipVerify: false, | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
| 	test := map[string]string{ | ||||
| 		"--providers-client1-client-id":            "client1-id", | ||||
| 		"--providers-client1-client-secret":        "client1-secret", | ||||
| 		"--providers-client1-scopes":               "client1-scope1,client1-scope2", | ||||
| 		"--providers-client1-redirect-url":         "client1-redirect-url", | ||||
| 		"--providers-client1-auth-url":             "client1-auth-url", | ||||
| 		"--providers-client1-user-info-url":        "client1-user-info-url", | ||||
| 		"--providers-client1-name":                 "Client1", | ||||
| 		"--providers-client1-insecure-skip-verify": "false", | ||||
| 		"--providers-client2-client-id":            "client2-id", | ||||
| 		"--providers-client2-client-secret":        "client2-secret", | ||||
| 		"--providers-client2-scopes":               "client2-scope1,client2-scope2", | ||||
| 		"--providers-client2-redirect-url":         "client2-redirect-url", | ||||
| 		"--providers-client2-auth-url":             "client2-auth-url", | ||||
| 		"--providers-client2-user-info-url":        "client2-user-info-url", | ||||
| 		"--providers-client2-name":                 "My Awesome Client2", | ||||
| 		"--providers-client2-insecure-skip-verify": "false", | ||||
| 	// Setup | ||||
| 	flags := map[string]string{ | ||||
| 		"--providers-google-client-id":        "google-client-id", | ||||
| 		"--providers-google-client-secret":    "google-client-secret", | ||||
| 		"--providers-my-github-client-id":     "github-client-id", | ||||
| 		"--providers-my-github-client-secret": "github-client-secret", | ||||
| 	} | ||||
|  | ||||
| 	// Test | ||||
| 	res, err := decoders.DecodeFlags(test) | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, expected, res) | ||||
| 	expected := config.Providers{ | ||||
| 		Providers: map[string]config.OAuthServiceConfig{ | ||||
| 			"google": { | ||||
| 				ClientID:     "google-client-id", | ||||
| 				ClientSecret: "google-client-secret", | ||||
| 			}, | ||||
| 			"myGithub": { | ||||
| 				ClientID:     "github-client-id", | ||||
| 				ClientSecret: "github-client-secret", | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	// Execute | ||||
| 	result, err := decoders.DecodeFlags[config.Providers, config.OAuthServiceConfig](flags, "providers") | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, result, expected) | ||||
| } | ||||
|   | ||||
		Reference in New Issue
	
	Block a user