mirror of
				https://github.com/steveiliop56/tinyauth.git
				synced 2025-10-31 14:15:50 +00:00 
			
		
		
		
	Compare commits
	
		
			8 Commits
		
	
	
		
			97639ae903
			...
			feat/light
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | 95dced96ae | ||
|   | 2c3b72353a | ||
|   | f5f18bc2f6 | ||
|   | 0227af6d2b | ||
|   | c5bb389258 | ||
|   | 6647c6cd78 | ||
|   | 7231efcbc3 | ||
|   | 5482430907 | 
| @@ -5,6 +5,7 @@ | ||||
|       "name": "tinyauth-shadcn", | ||||
|       "dependencies": { | ||||
|         "@hookform/resolvers": "^5.2.2", | ||||
|         "@radix-ui/react-dropdown-menu": "^2.1.16", | ||||
|         "@radix-ui/react-label": "^2.1.7", | ||||
|         "@radix-ui/react-select": "^2.2.6", | ||||
|         "@radix-ui/react-separator": "^1.1.7", | ||||
| @@ -213,6 +214,8 @@ | ||||
|  | ||||
|     "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], | ||||
|  | ||||
|     "@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw=="], | ||||
|  | ||||
|     "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="], | ||||
|  | ||||
|     "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="], | ||||
| @@ -221,12 +224,18 @@ | ||||
|  | ||||
|     "@radix-ui/react-label": ["@radix-ui/react-label@2.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ=="], | ||||
|  | ||||
|     "@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg=="], | ||||
|  | ||||
|     "@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], | ||||
|  | ||||
|     "@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], | ||||
|  | ||||
|     "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], | ||||
|  | ||||
|     "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], | ||||
|  | ||||
|     "@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA=="], | ||||
|  | ||||
|     "@radix-ui/react-select": ["@radix-ui/react-select@2.2.6", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ=="], | ||||
|  | ||||
|     "@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA=="], | ||||
|   | ||||
| @@ -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> | ||||
|   | ||||
| @@ -7,10 +7,12 @@ | ||||
|     "dev": "vite", | ||||
|     "build": "tsc -b && vite build", | ||||
|     "lint": "eslint .", | ||||
|     "preview": "vite preview" | ||||
|     "preview": "vite preview", | ||||
|     "tsc": "tsc -b" | ||||
|   }, | ||||
|   "dependencies": { | ||||
|     "@hookform/resolvers": "^5.2.2", | ||||
|     "@radix-ui/react-dropdown-menu": "^2.1.16", | ||||
|     "@radix-ui/react-label": "^2.1.7", | ||||
|     "@radix-ui/react-select": "^2.2.6", | ||||
|     "@radix-ui/react-separator": "^1.1.7", | ||||
| @@ -54,4 +56,4 @@ | ||||
|     "typescript-eslint": "^8.46.1", | ||||
|     "vite": "^7.1.10" | ||||
|   } | ||||
| } | ||||
| } | ||||
|   | ||||
| @@ -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> | ||||
|         <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 { ThemeToggle } from "../theme-toggle/theme-toggle"; | ||||
|  | ||||
| const BaseLayout = ({ children }: { children: React.ReactNode }) => { | ||||
|   const { backgroundImage, title } = useAppContext(); | ||||
| @@ -20,7 +21,10 @@ const BaseLayout = ({ children }: { children: React.ReactNode }) => { | ||||
|         backgroundPosition: "center", | ||||
|       }} | ||||
|     > | ||||
|       <LanguageSelector /> | ||||
|       <div className="absolute top-5 right-5 flex flex-row gap-2"> | ||||
|         <ThemeToggle /> | ||||
|         <LanguageSelector /> | ||||
|       </div> | ||||
|       {children} | ||||
|     </div> | ||||
|   ); | ||||
|   | ||||
							
								
								
									
										73
									
								
								frontend/src/components/providers/theme-provider.tsx
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										73
									
								
								frontend/src/components/providers/theme-provider.tsx
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,73 @@ | ||||
| import { createContext, useContext, useEffect, useState } from "react"; | ||||
|  | ||||
| type Theme = "dark" | "light" | "system"; | ||||
|  | ||||
| type ThemeProviderProps = { | ||||
|   children: React.ReactNode; | ||||
|   defaultTheme?: Theme; | ||||
|   storageKey?: string; | ||||
| }; | ||||
|  | ||||
| type ThemeProviderState = { | ||||
|   theme: Theme; | ||||
|   setTheme: (theme: Theme) => void; | ||||
| }; | ||||
|  | ||||
| const initialState: ThemeProviderState = { | ||||
|   theme: "system", | ||||
|   setTheme: () => null, | ||||
| }; | ||||
|  | ||||
| const ThemeProviderContext = createContext<ThemeProviderState>(initialState); | ||||
|  | ||||
| export function ThemeProvider({ | ||||
|   children, | ||||
|   defaultTheme = "system", | ||||
|   storageKey = "vite-ui-theme", | ||||
|   ...props | ||||
| }: ThemeProviderProps) { | ||||
|   const [theme, setTheme] = useState<Theme>( | ||||
|     () => (localStorage.getItem(storageKey) as Theme) || defaultTheme, | ||||
|   ); | ||||
|  | ||||
|   useEffect(() => { | ||||
|     const root = window.document.documentElement; | ||||
|  | ||||
|     root.classList.remove("light", "dark"); | ||||
|  | ||||
|     if (theme === "system") { | ||||
|       const systemTheme = window.matchMedia("(prefers-color-scheme: dark)") | ||||
|         .matches | ||||
|         ? "dark" | ||||
|         : "light"; | ||||
|  | ||||
|       root.classList.add(systemTheme); | ||||
|       return; | ||||
|     } | ||||
|  | ||||
|     root.classList.add(theme); | ||||
|   }, [theme]); | ||||
|  | ||||
|   const value = { | ||||
|     theme, | ||||
|     setTheme: (theme: Theme) => { | ||||
|       localStorage.setItem(storageKey, theme); | ||||
|       setTheme(theme); | ||||
|     }, | ||||
|   }; | ||||
|  | ||||
|   return ( | ||||
|     <ThemeProviderContext.Provider {...props} value={value}> | ||||
|       {children} | ||||
|     </ThemeProviderContext.Provider> | ||||
|   ); | ||||
| } | ||||
|  | ||||
| export const useTheme = () => { | ||||
|   const context = useContext(ThemeProviderContext); | ||||
|  | ||||
|   if (context === undefined) | ||||
|     throw new Error("useTheme must be used within a ThemeProvider"); | ||||
|  | ||||
|   return context; | ||||
| }; | ||||
							
								
								
									
										40
									
								
								frontend/src/components/theme-toggle/theme-toggle.tsx
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								frontend/src/components/theme-toggle/theme-toggle.tsx
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,40 @@ | ||||
| import { Moon, Sun } from "lucide-react"; | ||||
|  | ||||
| import { Button } from "@/components/ui/button"; | ||||
| import { | ||||
|   DropdownMenu, | ||||
|   DropdownMenuContent, | ||||
|   DropdownMenuItem, | ||||
|   DropdownMenuTrigger, | ||||
| } from "@/components/ui/dropdown-menu"; | ||||
| import { useTheme } from "@/components/providers/theme-provider"; | ||||
|  | ||||
| export function ThemeToggle() { | ||||
|   const { setTheme } = useTheme(); | ||||
|  | ||||
|   return ( | ||||
|     <DropdownMenu> | ||||
|       <DropdownMenuTrigger asChild> | ||||
|         <Button | ||||
|           className="bg-card text-card-foreground hover:bg-card/90" | ||||
|           size="icon" | ||||
|         > | ||||
|           <Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" /> | ||||
|           <Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" /> | ||||
|           <span className="sr-only">Toggle theme</span> | ||||
|         </Button> | ||||
|       </DropdownMenuTrigger> | ||||
|       <DropdownMenuContent align="end"> | ||||
|         <DropdownMenuItem onClick={() => setTheme("light")}> | ||||
|           Light | ||||
|         </DropdownMenuItem> | ||||
|         <DropdownMenuItem onClick={() => setTheme("dark")}> | ||||
|           Dark | ||||
|         </DropdownMenuItem> | ||||
|         <DropdownMenuItem onClick={() => setTheme("system")}> | ||||
|           System | ||||
|         </DropdownMenuItem> | ||||
|       </DropdownMenuContent> | ||||
|     </DropdownMenu> | ||||
|   ); | ||||
| } | ||||
| @@ -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: { | ||||
|   | ||||
							
								
								
									
										255
									
								
								frontend/src/components/ui/dropdown-menu.tsx
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										255
									
								
								frontend/src/components/ui/dropdown-menu.tsx
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,255 @@ | ||||
| import * as React from "react" | ||||
| import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" | ||||
| import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" | ||||
|  | ||||
| import { cn } from "@/lib/utils" | ||||
|  | ||||
| function DropdownMenu({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) { | ||||
|   return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} /> | ||||
| } | ||||
|  | ||||
| function DropdownMenuPortal({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuTrigger({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Trigger | ||||
|       data-slot="dropdown-menu-trigger" | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuContent({ | ||||
|   className, | ||||
|   sideOffset = 4, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Portal> | ||||
|       <DropdownMenuPrimitive.Content | ||||
|         data-slot="dropdown-menu-content" | ||||
|         sideOffset={sideOffset} | ||||
|         className={cn( | ||||
|           "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", | ||||
|           className | ||||
|         )} | ||||
|         {...props} | ||||
|       /> | ||||
|     </DropdownMenuPrimitive.Portal> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuGroup({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuItem({ | ||||
|   className, | ||||
|   inset, | ||||
|   variant = "default", | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { | ||||
|   inset?: boolean | ||||
|   variant?: "default" | "destructive" | ||||
| }) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Item | ||||
|       data-slot="dropdown-menu-item" | ||||
|       data-inset={inset} | ||||
|       data-variant={variant} | ||||
|       className={cn( | ||||
|         "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuCheckboxItem({ | ||||
|   className, | ||||
|   children, | ||||
|   checked, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.CheckboxItem | ||||
|       data-slot="dropdown-menu-checkbox-item" | ||||
|       className={cn( | ||||
|         "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", | ||||
|         className | ||||
|       )} | ||||
|       checked={checked} | ||||
|       {...props} | ||||
|     > | ||||
|       <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> | ||||
|         <DropdownMenuPrimitive.ItemIndicator> | ||||
|           <CheckIcon className="size-4" /> | ||||
|         </DropdownMenuPrimitive.ItemIndicator> | ||||
|       </span> | ||||
|       {children} | ||||
|     </DropdownMenuPrimitive.CheckboxItem> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuRadioGroup({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.RadioGroup | ||||
|       data-slot="dropdown-menu-radio-group" | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuRadioItem({ | ||||
|   className, | ||||
|   children, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.RadioItem | ||||
|       data-slot="dropdown-menu-radio-item" | ||||
|       className={cn( | ||||
|         "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     > | ||||
|       <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> | ||||
|         <DropdownMenuPrimitive.ItemIndicator> | ||||
|           <CircleIcon className="size-2 fill-current" /> | ||||
|         </DropdownMenuPrimitive.ItemIndicator> | ||||
|       </span> | ||||
|       {children} | ||||
|     </DropdownMenuPrimitive.RadioItem> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuLabel({ | ||||
|   className, | ||||
|   inset, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & { | ||||
|   inset?: boolean | ||||
| }) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Label | ||||
|       data-slot="dropdown-menu-label" | ||||
|       data-inset={inset} | ||||
|       className={cn( | ||||
|         "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuSeparator({ | ||||
|   className, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.Separator | ||||
|       data-slot="dropdown-menu-separator" | ||||
|       className={cn("bg-border -mx-1 my-1 h-px", className)} | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuShortcut({ | ||||
|   className, | ||||
|   ...props | ||||
| }: React.ComponentProps<"span">) { | ||||
|   return ( | ||||
|     <span | ||||
|       data-slot="dropdown-menu-shortcut" | ||||
|       className={cn( | ||||
|         "text-muted-foreground ml-auto text-xs tracking-widest", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuSub({ | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) { | ||||
|   return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} /> | ||||
| } | ||||
|  | ||||
| function DropdownMenuSubTrigger({ | ||||
|   className, | ||||
|   inset, | ||||
|   children, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & { | ||||
|   inset?: boolean | ||||
| }) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.SubTrigger | ||||
|       data-slot="dropdown-menu-sub-trigger" | ||||
|       data-inset={inset} | ||||
|       className={cn( | ||||
|         "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     > | ||||
|       {children} | ||||
|       <ChevronRightIcon className="ml-auto size-4" /> | ||||
|     </DropdownMenuPrimitive.SubTrigger> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| function DropdownMenuSubContent({ | ||||
|   className, | ||||
|   ...props | ||||
| }: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) { | ||||
|   return ( | ||||
|     <DropdownMenuPrimitive.SubContent | ||||
|       data-slot="dropdown-menu-sub-content" | ||||
|       className={cn( | ||||
|         "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", | ||||
|         className | ||||
|       )} | ||||
|       {...props} | ||||
|     /> | ||||
|   ) | ||||
| } | ||||
|  | ||||
| export { | ||||
|   DropdownMenu, | ||||
|   DropdownMenuPortal, | ||||
|   DropdownMenuTrigger, | ||||
|   DropdownMenuContent, | ||||
|   DropdownMenuGroup, | ||||
|   DropdownMenuLabel, | ||||
|   DropdownMenuItem, | ||||
|   DropdownMenuCheckboxItem, | ||||
|   DropdownMenuRadioGroup, | ||||
|   DropdownMenuRadioItem, | ||||
|   DropdownMenuSeparator, | ||||
|   DropdownMenuShortcut, | ||||
|   DropdownMenuSub, | ||||
|   DropdownMenuSubTrigger, | ||||
|   DropdownMenuSubContent, | ||||
| } | ||||
| @@ -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 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,8 @@ | ||||
| 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 { theme } = useTheme(); | ||||
|  | ||||
|   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,25 +25,27 @@ createRoot(document.getElementById("root")!).render( | ||||
|     <QueryClientProvider client={queryClient}> | ||||
|       <AppContextProvider> | ||||
|         <UserContextProvider> | ||||
|           <BrowserRouter> | ||||
|             <Routes> | ||||
|               <Route element={<Layout />} errorElement={<ErrorPage />}> | ||||
|                 <Route path="/" element={<App />} /> | ||||
|                 <Route path="/login" element={<LoginPage />} /> | ||||
|                 <Route path="/logout" element={<LogoutPage />} /> | ||||
|                 <Route path="/continue" element={<ContinuePage />} /> | ||||
|                 <Route path="/totp" element={<TotpPage />} /> | ||||
|                 <Route | ||||
|                   path="/forgot-password" | ||||
|                   element={<ForgotPasswordPage />} | ||||
|                 /> | ||||
|                 <Route path="/unauthorized" element={<UnauthorizedPage />} /> | ||||
|                 <Route path="/error" element={<ErrorPage />} /> | ||||
|                 <Route path="*" element={<NotFoundPage />} /> | ||||
|               </Route> | ||||
|             </Routes> | ||||
|           </BrowserRouter> | ||||
|           <Toaster /> | ||||
|           <ThemeProvider defaultTheme="system" storageKey="tinyauth-theme"> | ||||
|             <BrowserRouter> | ||||
|               <Routes> | ||||
|                 <Route element={<Layout />} errorElement={<ErrorPage />}> | ||||
|                   <Route path="/" element={<App />} /> | ||||
|                   <Route path="/login" element={<LoginPage />} /> | ||||
|                   <Route path="/logout" element={<LogoutPage />} /> | ||||
|                   <Route path="/continue" element={<ContinuePage />} /> | ||||
|                   <Route path="/totp" element={<TotpPage />} /> | ||||
|                   <Route | ||||
|                     path="/forgot-password" | ||||
|                     element={<ForgotPasswordPage />} | ||||
|                   /> | ||||
|                   <Route path="/unauthorized" element={<UnauthorizedPage />} /> | ||||
|                   <Route path="/error" element={<ErrorPage />} /> | ||||
|                   <Route path="*" element={<NotFoundPage />} /> | ||||
|                 </Route> | ||||
|               </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= | ||||
|   | ||||
| @@ -2,6 +2,7 @@ package bootstrap | ||||
|  | ||||
| import ( | ||||
| 	"bytes" | ||||
| 	"context" | ||||
| 	"encoding/json" | ||||
| 	"fmt" | ||||
| 	"net/http" | ||||
| @@ -13,11 +14,13 @@ import ( | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/controller" | ||||
| 	"tinyauth/internal/middleware" | ||||
| 	"tinyauth/internal/model" | ||||
| 	"tinyauth/internal/service" | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| 	"gorm.io/gorm" | ||||
| ) | ||||
|  | ||||
| type Controller interface { | ||||
| @@ -136,12 +139,14 @@ func (app *BootstrapApp) Setup() error { | ||||
|  | ||||
| 	// Create services | ||||
| 	dockerService := service.NewDockerService() | ||||
| 	aclsService := service.NewAccessControlsService(dockerService) | ||||
| 	authService := service.NewAuthService(authConfig, dockerService, ldapService, database) | ||||
| 	oauthBrokerService := service.NewOAuthBrokerService(oauthProviders) | ||||
|  | ||||
| 	// Initialize services | ||||
| 	// Initialize services (order matters) | ||||
| 	services := []Service{ | ||||
| 		dockerService, | ||||
| 		aclsService, | ||||
| 		authService, | ||||
| 		oauthBrokerService, | ||||
| 	} | ||||
| @@ -243,7 +248,7 @@ func (app *BootstrapApp) Setup() error { | ||||
|  | ||||
| 	proxyController := controller.NewProxyController(controller.ProxyControllerConfig{ | ||||
| 		AppURL: app.config.AppURL, | ||||
| 	}, apiRouter, dockerService, authService) | ||||
| 	}, apiRouter, aclsService, authService) | ||||
|  | ||||
| 	userController := controller.NewUserController(controller.UserControllerConfig{ | ||||
| 		CookieDomain: cookieDomain, | ||||
| @@ -277,6 +282,10 @@ func (app *BootstrapApp) Setup() error { | ||||
| 		go app.heartbeat() | ||||
| 	} | ||||
|  | ||||
| 	// Start DB cleanup routine | ||||
| 	log.Debug().Msg("Starting database cleanup routine") | ||||
| 	go app.dbCleanup(database) | ||||
|  | ||||
| 	// Start server | ||||
| 	address := fmt.Sprintf("%s:%d", app.config.Address, app.config.Port) | ||||
| 	log.Info().Msgf("Starting server on %s", address) | ||||
| @@ -338,3 +347,17 @@ func (app *BootstrapApp) heartbeat() { | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (app *BootstrapApp) dbCleanup(db *gorm.DB) { | ||||
| 	ticker := time.NewTicker(time.Duration(30) * time.Minute) | ||||
| 	defer ticker.Stop() | ||||
| 	ctx := context.Background() | ||||
|  | ||||
| 	for ; true; <-ticker.C { | ||||
| 		log.Debug().Msg("Cleaning up old database sessions") | ||||
| 		_, err := gorm.G[model.Session](db).Where("expiry < ?", time.Now().UnixMilli()).Delete(ctx) | ||||
| 		if err != nil { | ||||
| 			log.Error().Err(err).Msg("Failed to cleanup old sessions") | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|   | ||||
| @@ -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{ | ||||
|   | ||||
| @@ -72,6 +72,7 @@ func (controller *OAuthController) oauthURLHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	service.GenerateVerifier() | ||||
| 	state := service.GenerateState() | ||||
| 	authURL := service.GetAuthURL(state) | ||||
| 	c.SetCookie(controller.config.CSRFCookieName, state, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true) | ||||
|   | ||||
| @@ -24,15 +24,15 @@ type ProxyControllerConfig struct { | ||||
| type ProxyController struct { | ||||
| 	config ProxyControllerConfig | ||||
| 	router *gin.RouterGroup | ||||
| 	docker *service.DockerService | ||||
| 	acls   *service.AccessControlsService | ||||
| 	auth   *service.AuthService | ||||
| } | ||||
|  | ||||
| func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, docker *service.DockerService, auth *service.AuthService) *ProxyController { | ||||
| func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, acls *service.AccessControlsService, auth *service.AuthService) *ProxyController { | ||||
| 	return &ProxyController{ | ||||
| 		config: config, | ||||
| 		router: router, | ||||
| 		docker: docker, | ||||
| 		acls:   acls, | ||||
| 		auth:   auth, | ||||
| 	} | ||||
| } | ||||
| @@ -76,20 +76,21 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	proto := c.Request.Header.Get("X-Forwarded-Proto") | ||||
| 	host := c.Request.Header.Get("X-Forwarded-Host") | ||||
|  | ||||
| 	labels, err := controller.docker.GetLabels(host) | ||||
| 	// Get acls | ||||
| 	acls, err := controller.acls.GetAccessControls(host) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to get labels from Docker") | ||||
| 		log.Error().Err(err).Msg("Failed to get access controls for resource") | ||||
| 		controller.handleError(c, req, isBrowser) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	log.Trace().Interface("labels", labels).Msg("Labels for resource") | ||||
| 	log.Trace().Interface("acls", acls).Msg("ACLs for resource") | ||||
|  | ||||
| 	clientIP := c.ClientIP() | ||||
|  | ||||
| 	if controller.auth.IsBypassedIP(labels.IP, clientIP) { | ||||
| 		controller.setHeaders(c, labels) | ||||
| 	if controller.auth.IsBypassedIP(acls.IP, clientIP) { | ||||
| 		controller.setHeaders(c, acls) | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| @@ -97,7 +98,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	authEnabled, err := controller.auth.IsAuthEnabled(uri, labels.Path) | ||||
| 	authEnabled, err := controller.auth.IsAuthEnabled(uri, acls.Path) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to check if auth is enabled for resource") | ||||
| @@ -107,7 +108,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
|  | ||||
| 	if !authEnabled { | ||||
| 		log.Debug().Msg("Authentication disabled for resource, allowing access") | ||||
| 		controller.setHeaders(c, labels) | ||||
| 		controller.setHeaders(c, acls) | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| @@ -115,7 +116,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !controller.auth.CheckIP(labels.IP, clientIP) { | ||||
| 	if !controller.auth.CheckIP(acls.IP, clientIP) { | ||||
| 		if req.Proxy == "nginx" || !isBrowser { | ||||
| 			c.JSON(401, gin.H{ | ||||
| 				"status":  401, | ||||
| @@ -160,7 +161,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	} | ||||
|  | ||||
| 	if userContext.IsLoggedIn { | ||||
| 		appAllowed := controller.auth.IsResourceAllowed(c, userContext, labels) | ||||
| 		appAllowed := controller.auth.IsResourceAllowed(c, userContext, acls) | ||||
|  | ||||
| 		if !appAllowed { | ||||
| 			log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User not allowed to access resource") | ||||
| @@ -194,7 +195,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		} | ||||
|  | ||||
| 		if userContext.OAuth { | ||||
| 			groupOK := controller.auth.IsInOAuthGroup(c, userContext, labels.OAuth.Groups) | ||||
| 			groupOK := controller.auth.IsInOAuthGroup(c, userContext, acls.OAuth.Groups) | ||||
|  | ||||
| 			if !groupOK { | ||||
| 				log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User OAuth groups do not match resource requirements") | ||||
| @@ -234,7 +235,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		c.Header("Remote-Email", utils.SanitizeHeader(userContext.Email)) | ||||
| 		c.Header("Remote-Groups", utils.SanitizeHeader(userContext.OAuthGroups)) | ||||
|  | ||||
| 		controller.setHeaders(c, labels) | ||||
| 		controller.setHeaders(c, acls) | ||||
|  | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| @@ -264,21 +265,21 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?%s", controller.config.AppURL, queries.Encode())) | ||||
| } | ||||
|  | ||||
| func (controller *ProxyController) setHeaders(c *gin.Context, labels config.App) { | ||||
| func (controller *ProxyController) setHeaders(c *gin.Context, acls config.App) { | ||||
| 	c.Header("Authorization", c.Request.Header.Get("Authorization")) | ||||
|  | ||||
| 	headers := utils.ParseHeaders(labels.Response.Headers) | ||||
| 	headers := utils.ParseHeaders(acls.Response.Headers) | ||||
|  | ||||
| 	for key, value := range headers { | ||||
| 		log.Debug().Str("header", key).Msg("Setting header") | ||||
| 		c.Header(key, value) | ||||
| 	} | ||||
|  | ||||
| 	basicPassword := utils.GetSecret(labels.Response.BasicAuth.Password, labels.Response.BasicAuth.PasswordFile) | ||||
| 	basicPassword := utils.GetSecret(acls.Response.BasicAuth.Password, acls.Response.BasicAuth.PasswordFile) | ||||
|  | ||||
| 	if labels.Response.BasicAuth.Username != "" && basicPassword != "" { | ||||
| 		log.Debug().Str("username", labels.Response.BasicAuth.Username).Msg("Setting basic auth header") | ||||
| 		c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(labels.Response.BasicAuth.Username, basicPassword))) | ||||
| 	if acls.Response.BasicAuth.Username != "" && basicPassword != "" { | ||||
| 		log.Debug().Str("username", acls.Response.BasicAuth.Username).Msg("Setting basic auth header") | ||||
| 		c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(acls.Response.BasicAuth.Username, basicPassword))) | ||||
| 	} | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -39,6 +39,11 @@ func setupProxyController(t *testing.T, middlewares *[]gin.HandlerFunc) (*gin.En | ||||
|  | ||||
| 	assert.NilError(t, dockerService.Init()) | ||||
|  | ||||
| 	// Access controls | ||||
| 	accessControlsService := service.NewAccessControlsService(dockerService) | ||||
|  | ||||
| 	assert.NilError(t, accessControlsService.Init()) | ||||
|  | ||||
| 	// Auth service | ||||
| 	authService := service.NewAuthService(service.AuthServiceConfig{ | ||||
| 		Users: []config.User{ | ||||
| @@ -59,7 +64,7 @@ func setupProxyController(t *testing.T, middlewares *[]gin.HandlerFunc) (*gin.En | ||||
| 	// Controller | ||||
| 	ctrl := controller.NewProxyController(controller.ProxyControllerConfig{ | ||||
| 		AppURL: "http://localhost:8080", | ||||
| 	}, group, dockerService, authService) | ||||
| 	}, group, accessControlsService, authService) | ||||
| 	ctrl.SetupRoutes() | ||||
|  | ||||
| 	return router, recorder, authService | ||||
|   | ||||
							
								
								
									
										103
									
								
								internal/service/access_controls_service.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										103
									
								
								internal/service/access_controls_service.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,103 @@ | ||||
| package service | ||||
|  | ||||
| import ( | ||||
| 	"os" | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/utils/decoders" | ||||
|  | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type AccessControlsService struct { | ||||
| 	docker  *DockerService | ||||
| 	envACLs config.Apps | ||||
| } | ||||
|  | ||||
| func NewAccessControlsService(docker *DockerService) *AccessControlsService { | ||||
| 	return &AccessControlsService{ | ||||
| 		docker: docker, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) Init() error { | ||||
| 	acls.envACLs = config.Apps{} | ||||
| 	env := os.Environ() | ||||
| 	appEnvVars := []string{} | ||||
|  | ||||
| 	for _, e := range env { | ||||
| 		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 { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	acls.envACLs = apps | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) lookupEnvACLs(appDomain string) *config.App { | ||||
| 	if len(acls.envACLs.Apps) == 0 { | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	for appName, appACLs := range acls.envACLs.Apps { | ||||
| 		if appACLs.Config.Domain == appDomain { | ||||
| 			return &appACLs | ||||
| 		} | ||||
|  | ||||
| 		if strings.SplitN(appDomain, ".", 2)[0] == appName { | ||||
| 			return &appACLs | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) GetAccessControls(appDomain string) (config.App, error) { | ||||
| 	// First check environment variables | ||||
| 	envACLs := acls.lookupEnvACLs(appDomain) | ||||
|  | ||||
| 	if envACLs != nil { | ||||
| 		log.Debug().Str("domain", appDomain).Msg("Found matching access controls in environment variables") | ||||
| 		return *envACLs, nil | ||||
| 	} | ||||
|  | ||||
| 	// Fallback to Docker labels | ||||
| 	return acls.docker.GetLabels(appDomain) | ||||
| } | ||||
| @@ -1,6 +1,8 @@ | ||||
| package service | ||||
|  | ||||
| import ( | ||||
| 	"context" | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"regexp" | ||||
| 	"strings" | ||||
| @@ -41,6 +43,7 @@ type AuthService struct { | ||||
| 	loginMutex    sync.RWMutex | ||||
| 	ldap          *LdapService | ||||
| 	database      *gorm.DB | ||||
| 	ctx           context.Context | ||||
| } | ||||
|  | ||||
| func NewAuthService(config AuthServiceConfig, docker *DockerService, ldap *LdapService, database *gorm.DB) *AuthService { | ||||
| @@ -54,6 +57,7 @@ func NewAuthService(config AuthServiceConfig, docker *DockerService, ldap *LdapS | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) Init() error { | ||||
| 	auth.ctx = context.Background() | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -213,7 +217,7 @@ func (auth *AuthService) CreateSessionCookie(c *gin.Context, data *config.Sessio | ||||
| 		OAuthName:   data.OAuthName, | ||||
| 	} | ||||
|  | ||||
| 	err = auth.database.Create(&session).Error | ||||
| 	err = gorm.G[model.Session](auth.database).Create(auth.ctx, &session) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| @@ -231,10 +235,10 @@ func (auth *AuthService) DeleteSessionCookie(c *gin.Context) error { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	res := auth.database.Unscoped().Where("uuid = ?", cookie).Delete(&model.Session{}) | ||||
| 	_, err = gorm.G[model.Session](auth.database).Where("uuid = ?", cookie).Delete(auth.ctx) | ||||
|  | ||||
| 	if res.Error != nil { | ||||
| 		return res.Error | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	c.SetCookie(auth.config.SessionCookieName, "", -1, "/", fmt.Sprintf(".%s", auth.config.CookieDomain), auth.config.SecureCookie, true) | ||||
| @@ -249,15 +253,13 @@ func (auth *AuthService) GetSessionCookie(c *gin.Context) (config.SessionCookie, | ||||
| 		return config.SessionCookie{}, err | ||||
| 	} | ||||
|  | ||||
| 	var session model.Session | ||||
| 	session, err := gorm.G[model.Session](auth.database).Where("uuid = ?", cookie).First(auth.ctx) | ||||
|  | ||||
| 	res := auth.database.Unscoped().Where("uuid = ?", cookie).First(&session) | ||||
|  | ||||
| 	if res.Error != nil { | ||||
| 		return config.SessionCookie{}, res.Error | ||||
| 	if err != nil { | ||||
| 		return config.SessionCookie{}, err | ||||
| 	} | ||||
|  | ||||
| 	if res.RowsAffected == 0 { | ||||
| 	if errors.Is(err, gorm.ErrRecordNotFound) { | ||||
| 		return config.SessionCookie{}, fmt.Errorf("session not found") | ||||
| 	} | ||||
|  | ||||
| @@ -287,21 +289,21 @@ func (auth *AuthService) UserAuthConfigured() bool { | ||||
| 	return len(auth.config.Users) > 0 || auth.ldap != nil | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsResourceAllowed(c *gin.Context, context config.UserContext, labels config.App) bool { | ||||
| func (auth *AuthService) IsResourceAllowed(c *gin.Context, context config.UserContext, acls config.App) bool { | ||||
| 	if context.OAuth { | ||||
| 		log.Debug().Msg("Checking OAuth whitelist") | ||||
| 		return utils.CheckFilter(labels.OAuth.Whitelist, context.Email) | ||||
| 		return utils.CheckFilter(acls.OAuth.Whitelist, context.Email) | ||||
| 	} | ||||
|  | ||||
| 	if labels.Users.Block != "" { | ||||
| 	if acls.Users.Block != "" { | ||||
| 		log.Debug().Msg("Checking blocked users") | ||||
| 		if utils.CheckFilter(labels.Users.Block, context.Username) { | ||||
| 		if utils.CheckFilter(acls.Users.Block, context.Username) { | ||||
| 			return false | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	log.Debug().Msg("Checking users") | ||||
| 	return utils.CheckFilter(labels.Users.Allow, context.Username) | ||||
| 	return utils.CheckFilter(acls.Users.Allow, context.Username) | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsInOAuthGroup(c *gin.Context, context config.UserContext, requiredGroups string) bool { | ||||
| @@ -369,8 +371,8 @@ func (auth *AuthService) GetBasicAuth(c *gin.Context) *config.User { | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) CheckIP(labels config.AppIP, ip string) bool { | ||||
| 	for _, blocked := range labels.Block { | ||||
| func (auth *AuthService) CheckIP(acls config.AppIP, ip string) bool { | ||||
| 	for _, blocked := range acls.Block { | ||||
| 		res, err := utils.FilterIP(blocked, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", blocked).Msg("Invalid IP/CIDR in block list") | ||||
| @@ -382,7 +384,7 @@ func (auth *AuthService) CheckIP(labels config.AppIP, ip string) bool { | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	for _, allowed := range labels.Allow { | ||||
| 	for _, allowed := range acls.Allow { | ||||
| 		res, err := utils.FilterIP(allowed, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", allowed).Msg("Invalid IP/CIDR in allow list") | ||||
| @@ -394,7 +396,7 @@ func (auth *AuthService) CheckIP(labels config.AppIP, ip string) bool { | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if len(labels.Allow) > 0 { | ||||
| 	if len(acls.Allow) > 0 { | ||||
| 		log.Debug().Str("ip", ip).Msg("IP not in allow list, denying access") | ||||
| 		return false | ||||
| 	} | ||||
| @@ -403,8 +405,8 @@ func (auth *AuthService) CheckIP(labels config.AppIP, ip string) bool { | ||||
| 	return true | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsBypassedIP(labels config.AppIP, ip string) bool { | ||||
| 	for _, bypassed := range labels.Bypass { | ||||
| func (auth *AuthService) IsBypassedIP(acls config.AppIP, ip string) bool { | ||||
| 	for _, bypassed := range acls.Bypass { | ||||
| 		res, err := utils.FilterIP(bypassed, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", bypassed).Msg("Invalid IP/CIDR in bypass list") | ||||
|   | ||||
| @@ -59,10 +59,8 @@ func (generic *GenericOAuthService) Init() error { | ||||
| 	ctx := context.Background() | ||||
|  | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	generic.context = ctx | ||||
| 	generic.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -76,6 +74,12 @@ func (generic *GenericOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (generic *GenericOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	generic.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (generic *GenericOAuthService) GetAuthURL(state string) string { | ||||
| 	return generic.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(generic.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -53,10 +53,7 @@ func (github *GithubOAuthService) Init() error { | ||||
| 	httpClient := &http.Client{} | ||||
| 	ctx := context.Background() | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	github.context = ctx | ||||
| 	github.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -70,6 +67,12 @@ func (github *GithubOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (github *GithubOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	github.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (github *GithubOAuthService) GetAuthURL(state string) string { | ||||
| 	return github.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(github.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -48,10 +48,7 @@ func (google *GoogleOAuthService) Init() error { | ||||
| 	httpClient := &http.Client{} | ||||
| 	ctx := context.Background() | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	google.context = ctx | ||||
| 	google.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -65,6 +62,12 @@ func (oauth *GoogleOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (google *GoogleOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	google.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (google *GoogleOAuthService) GetAuthURL(state string) string { | ||||
| 	return google.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(google.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -11,6 +11,7 @@ import ( | ||||
| type OAuthService interface { | ||||
| 	Init() error | ||||
| 	GenerateState() string | ||||
| 	GenerateVerifier() string | ||||
| 	GetAuthURL(state string) string | ||||
| 	VerifyCode(code string) error | ||||
| 	Userinfo() (config.Claims, error) | ||||
|   | ||||
| @@ -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 | ||||
| 	// 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", | ||||
| 	} | ||||
|  | ||||
| 	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, | ||||
| 			"google": { | ||||
| 				ClientID:     "google-client-id", | ||||
| 				ClientSecret: "google-client-secret", | ||||
| 			}, | ||||
| 			"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, | ||||
| 			"myGithub": { | ||||
| 				ClientID:     "github-client-id", | ||||
| 				ClientSecret: "github-client-secret", | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
| 	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", | ||||
| 	} | ||||
|  | ||||
| 	// Test | ||||
| 	res, err := decoders.DecodeEnv(test) | ||||
| 	// Execute | ||||
| 	result, err := decoders.DecodeEnv[config.Providers, config.OAuthServiceConfig](env, "providers") | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, expected, res) | ||||
| 	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 | ||||
| 	// 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", | ||||
| 	} | ||||
|  | ||||
| 	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, | ||||
| 			"google": { | ||||
| 				ClientID:     "google-client-id", | ||||
| 				ClientSecret: "google-client-secret", | ||||
| 			}, | ||||
| 			"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, | ||||
| 			"myGithub": { | ||||
| 				ClientID:     "github-client-id", | ||||
| 				ClientSecret: "github-client-secret", | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
| 	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", | ||||
| 	} | ||||
|  | ||||
| 	// Test | ||||
| 	res, err := decoders.DecodeFlags(test) | ||||
| 	// Execute | ||||
| 	result, err := decoders.DecodeFlags[config.Providers, config.OAuthServiceConfig](flags, "providers") | ||||
| 	assert.NilError(t, err) | ||||
| 	assert.DeepEqual(t, expected, res) | ||||
| 	assert.DeepEqual(t, result, expected) | ||||
| } | ||||
|   | ||||
		Reference in New Issue
	
	Block a user