mirror of
				https://github.com/steveiliop56/tinyauth.git
				synced 2025-10-31 14:15:50 +00:00 
			
		
		
		
	refactor: rework file structure (#325)
* wip: add middlewares * refactor: use context fom middleware in handlers * refactor: use controller approach in handlers * refactor: move oauth providers into services (non-working) * feat: create oauth broker service * refactor: use a boostrap service to bootstrap the app * refactor: split utils into smaller files * refactor: use more clear name for frontend assets * feat: allow customizability of resources dir * fix: fix typo in ui middleware * fix: validate resource file paths in ui middleware * refactor: move resource handling to a controller * feat: add some logging * fix: configure middlewares before groups * fix: use correct api path in login mutation * fix: coderabbit suggestions * fix: further coderabbit suggestions
This commit is contained in:
		
							
								
								
									
										104
									
								
								internal/controller/context_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										104
									
								
								internal/controller/context_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,104 @@ | ||||
| package controller | ||||
|  | ||||
| import ( | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type UserContextResponse struct { | ||||
| 	Status      int    `json:"status"` | ||||
| 	Message     string `json:"message"` | ||||
| 	IsLoggedIn  bool   `json:"isLoggedIn"` | ||||
| 	Username    string `json:"username"` | ||||
| 	Name        string `json:"name"` | ||||
| 	Email       string `json:"email"` | ||||
| 	Provider    string `json:"provider"` | ||||
| 	Oauth       bool   `json:"oauth"` | ||||
| 	TotpPending bool   `json:"totpPending"` | ||||
| } | ||||
|  | ||||
| type AppContextResponse struct { | ||||
| 	Status                int      `json:"status"` | ||||
| 	Message               string   `json:"message"` | ||||
| 	ConfiguredProviders   []string `json:"configuredProviders"` | ||||
| 	DisableContinue       bool     `json:"disableContinue"` | ||||
| 	Title                 string   `json:"title"` | ||||
| 	GenericName           string   `json:"genericName"` | ||||
| 	Domain                string   `json:"domain"` | ||||
| 	ForgotPasswordMessage string   `json:"forgotPasswordMessage"` | ||||
| 	BackgroundImage       string   `json:"backgroundImage"` | ||||
| 	OAuthAutoRedirect     string   `json:"oauthAutoRedirect"` | ||||
| } | ||||
|  | ||||
| type ContextControllerConfig struct { | ||||
| 	ConfiguredProviders   []string | ||||
| 	DisableContinue       bool | ||||
| 	Title                 string | ||||
| 	GenericName           string | ||||
| 	Domain                string | ||||
| 	ForgotPasswordMessage string | ||||
| 	BackgroundImage       string | ||||
| 	OAuthAutoRedirect     string | ||||
| } | ||||
|  | ||||
| type ContextController struct { | ||||
| 	Config ContextControllerConfig | ||||
| 	Router *gin.RouterGroup | ||||
| } | ||||
|  | ||||
| func NewContextController(config ContextControllerConfig, router *gin.RouterGroup) *ContextController { | ||||
| 	return &ContextController{ | ||||
| 		Config: config, | ||||
| 		Router: router, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *ContextController) SetupRoutes() { | ||||
| 	contextGroup := controller.Router.Group("/context") | ||||
| 	contextGroup.GET("/user", controller.userContextHandler) | ||||
| 	contextGroup.GET("/app", controller.appContextHandler) | ||||
| } | ||||
|  | ||||
| func (controller *ContextController) userContextHandler(c *gin.Context) { | ||||
| 	context, err := utils.GetContext(c) | ||||
|  | ||||
| 	userContext := UserContextResponse{ | ||||
| 		Status:      200, | ||||
| 		Message:     "Success", | ||||
| 		IsLoggedIn:  context.IsLoggedIn, | ||||
| 		Username:    context.Username, | ||||
| 		Name:        context.Name, | ||||
| 		Email:       context.Email, | ||||
| 		Provider:    context.Provider, | ||||
| 		Oauth:       context.OAuth, | ||||
| 		TotpPending: context.TotpPending, | ||||
| 	} | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Debug().Err(err).Msg("No user context found in request") | ||||
| 		userContext.Status = 401 | ||||
| 		userContext.Message = "Unauthorized" | ||||
| 		userContext.IsLoggedIn = false | ||||
| 		c.JSON(200, userContext) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.JSON(200, userContext) | ||||
| } | ||||
|  | ||||
| func (controller *ContextController) appContextHandler(c *gin.Context) { | ||||
| 	c.JSON(200, AppContextResponse{ | ||||
| 		Status:                200, | ||||
| 		Message:               "Success", | ||||
| 		ConfiguredProviders:   controller.Config.ConfiguredProviders, | ||||
| 		DisableContinue:       controller.Config.DisableContinue, | ||||
| 		Title:                 controller.Config.Title, | ||||
| 		GenericName:           controller.Config.GenericName, | ||||
| 		Domain:                controller.Config.Domain, | ||||
| 		ForgotPasswordMessage: controller.Config.ForgotPasswordMessage, | ||||
| 		BackgroundImage:       controller.Config.BackgroundImage, | ||||
| 		OAuthAutoRedirect:     controller.Config.OAuthAutoRedirect, | ||||
| 	}) | ||||
| } | ||||
							
								
								
									
										25
									
								
								internal/controller/health_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								internal/controller/health_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,25 @@ | ||||
| package controller | ||||
|  | ||||
| import "github.com/gin-gonic/gin" | ||||
|  | ||||
| type HealthController struct { | ||||
| 	Router *gin.RouterGroup | ||||
| } | ||||
|  | ||||
| func NewHealthController(router *gin.RouterGroup) *HealthController { | ||||
| 	return &HealthController{ | ||||
| 		Router: router, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *HealthController) SetupRoutes() { | ||||
| 	controller.Router.GET("/health", controller.healthHandler) | ||||
| 	controller.Router.HEAD("/health", controller.healthHandler) | ||||
| } | ||||
|  | ||||
| func (controller *HealthController) healthHandler(c *gin.Context) { | ||||
| 	c.JSON(200, gin.H{ | ||||
| 		"status":  "ok", | ||||
| 		"message": "Healthy", | ||||
| 	}) | ||||
| } | ||||
							
								
								
									
										200
									
								
								internal/controller/oauth_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										200
									
								
								internal/controller/oauth_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,200 @@ | ||||
| package controller | ||||
|  | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"net/http" | ||||
| 	"strings" | ||||
| 	"time" | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/service" | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/google/go-querystring/query" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type OAuthRequest struct { | ||||
| 	Provider string `uri:"provider" binding:"required"` | ||||
| } | ||||
|  | ||||
| type OAuthControllerConfig struct { | ||||
| 	CSRFCookieName     string | ||||
| 	RedirectCookieName string | ||||
| 	SecureCookie       bool | ||||
| 	AppURL             string | ||||
| 	Domain             string | ||||
| } | ||||
|  | ||||
| type OAuthController struct { | ||||
| 	Config OAuthControllerConfig | ||||
| 	Router *gin.RouterGroup | ||||
| 	Auth   *service.AuthService | ||||
| 	Broker *service.OAuthBrokerService | ||||
| } | ||||
|  | ||||
| func NewOAuthController(config OAuthControllerConfig, router *gin.RouterGroup, auth *service.AuthService, broker *service.OAuthBrokerService) *OAuthController { | ||||
| 	return &OAuthController{ | ||||
| 		Config: config, | ||||
| 		Router: router, | ||||
| 		Auth:   auth, | ||||
| 		Broker: broker, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *OAuthController) SetupRoutes() { | ||||
| 	oauthGroup := controller.Router.Group("/oauth") | ||||
| 	oauthGroup.GET("/url/:provider", controller.oauthURLHandler) | ||||
| 	oauthGroup.GET("/callback/:provider", controller.oauthCallbackHandler) | ||||
| } | ||||
|  | ||||
| func (controller *OAuthController) oauthURLHandler(c *gin.Context) { | ||||
| 	var req OAuthRequest | ||||
|  | ||||
| 	err := c.BindUri(&req) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to bind URI") | ||||
| 		c.JSON(400, gin.H{ | ||||
| 			"status":  400, | ||||
| 			"message": "Bad Request", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	service, exists := controller.Broker.GetService(req.Provider) | ||||
|  | ||||
| 	if !exists { | ||||
| 		log.Warn().Msgf("OAuth provider not found: %s", req.Provider) | ||||
| 		c.JSON(404, gin.H{ | ||||
| 			"status":  404, | ||||
| 			"message": "Not Found", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	state := service.GenerateState() | ||||
| 	authURL := service.GetAuthURL(state) | ||||
| 	c.SetCookie(controller.Config.CSRFCookieName, state, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.Config.Domain), controller.Config.SecureCookie, true) | ||||
|  | ||||
| 	redirectURI := c.Query("redirect_uri") | ||||
|  | ||||
| 	if redirectURI != "" && utils.IsRedirectSafe(redirectURI, controller.Config.Domain) { | ||||
| 		log.Debug().Msg("Setting redirect URI cookie") | ||||
| 		c.SetCookie(controller.Config.RedirectCookieName, redirectURI, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.Config.Domain), controller.Config.SecureCookie, true) | ||||
| 	} | ||||
|  | ||||
| 	c.JSON(200, gin.H{ | ||||
| 		"status":  200, | ||||
| 		"message": "OK", | ||||
| 		"url":     authURL, | ||||
| 	}) | ||||
| } | ||||
|  | ||||
| func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) { | ||||
| 	var req OAuthRequest | ||||
|  | ||||
| 	err := c.BindUri(&req) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to bind URI") | ||||
| 		c.JSON(400, gin.H{ | ||||
| 			"status":  400, | ||||
| 			"message": "Bad Request", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	state := c.Query("state") | ||||
| 	csrfCookie, err := c.Cookie(controller.Config.CSRFCookieName) | ||||
|  | ||||
| 	if err != nil || state != csrfCookie { | ||||
| 		log.Warn().Err(err).Msg("CSRF token mismatch or cookie missing") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.SetCookie(controller.Config.CSRFCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.Config.Domain), controller.Config.SecureCookie, true) | ||||
|  | ||||
| 	code := c.Query("code") | ||||
| 	service, exists := controller.Broker.GetService(req.Provider) | ||||
|  | ||||
| 	if !exists { | ||||
| 		log.Warn().Msgf("OAuth provider not found: %s", req.Provider) | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	err = service.VerifyCode(code) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to verify OAuth code") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	user, err := controller.Broker.GetUser(req.Provider) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to get user from OAuth provider") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if user.Email == "" { | ||||
| 		log.Error().Msg("OAuth provider did not return an email") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !controller.Auth.EmailWhitelisted(user.Email) { | ||||
| 		queries, err := query.Values(config.UnauthorizedQuery{ | ||||
| 			Username: user.Email, | ||||
| 		}) | ||||
|  | ||||
| 		if err != nil { | ||||
| 			log.Error().Err(err).Msg("Failed to encode unauthorized query") | ||||
| 			c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", controller.Config.AppURL, queries.Encode())) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	var name string | ||||
|  | ||||
| 	if user.Name != "" { | ||||
| 		log.Debug().Msg("Using name from OAuth provider") | ||||
| 		name = user.Name | ||||
| 	} else { | ||||
| 		log.Debug().Msg("No name from OAuth provider, using pseudo name") | ||||
| 		name = fmt.Sprintf("%s (%s)", utils.Capitalize(strings.Split(user.Email, "@")[0]), strings.Split(user.Email, "@")[1]) | ||||
| 	} | ||||
|  | ||||
| 	controller.Auth.CreateSessionCookie(c, &config.SessionCookie{ | ||||
| 		Username:    user.Email, | ||||
| 		Name:        name, | ||||
| 		Email:       user.Email, | ||||
| 		Provider:    req.Provider, | ||||
| 		OAuthGroups: utils.CoalesceToString(user.Groups), | ||||
| 	}) | ||||
|  | ||||
| 	redirectURI, err := c.Cookie(controller.Config.RedirectCookieName) | ||||
|  | ||||
| 	if err != nil || !utils.IsRedirectSafe(redirectURI, controller.Config.Domain) { | ||||
| 		log.Debug().Msg("No redirect URI cookie found, redirecting to app root") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, controller.Config.AppURL) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	queries, err := query.Values(config.RedirectQuery{ | ||||
| 		RedirectURI: redirectURI, | ||||
| 	}) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to encode redirect URI query") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.SetCookie(controller.Config.RedirectCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.Config.Domain), controller.Config.SecureCookie, true) | ||||
| 	c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/continue?%s", controller.Config.AppURL, queries.Encode())) | ||||
| } | ||||
							
								
								
									
										311
									
								
								internal/controller/proxy_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										311
									
								
								internal/controller/proxy_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,311 @@ | ||||
| package controller | ||||
|  | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"net/http" | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/service" | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/google/go-querystring/query" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type Proxy struct { | ||||
| 	Proxy string `uri:"proxy" binding:"required"` | ||||
| } | ||||
|  | ||||
| type ProxyControllerConfig struct { | ||||
| 	AppURL string | ||||
| } | ||||
|  | ||||
| type ProxyController struct { | ||||
| 	Config ProxyControllerConfig | ||||
| 	Router *gin.RouterGroup | ||||
| 	Docker *service.DockerService | ||||
| 	Auth   *service.AuthService | ||||
| } | ||||
|  | ||||
| func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, docker *service.DockerService, auth *service.AuthService) *ProxyController { | ||||
| 	return &ProxyController{ | ||||
| 		Config: config, | ||||
| 		Router: router, | ||||
| 		Docker: docker, | ||||
| 		Auth:   auth, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *ProxyController) SetupRoutes() { | ||||
| 	proxyGroup := controller.Router.Group("/auth") | ||||
| 	proxyGroup.GET("/:proxy", controller.proxyHandler) | ||||
| } | ||||
|  | ||||
| func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	var req Proxy | ||||
|  | ||||
| 	err := c.BindUri(&req) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to bind URI") | ||||
| 		c.JSON(400, gin.H{ | ||||
| 			"status":  400, | ||||
| 			"message": "Bad Request", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	isBrowser := strings.Contains(c.Request.Header.Get("Accept"), "text/html") | ||||
|  | ||||
| 	if isBrowser { | ||||
| 		log.Debug().Msg("Request identified as (most likely) coming from a browser") | ||||
| 	} else { | ||||
| 		log.Debug().Msg("Request identified as (most likely) coming from a non-browser client") | ||||
| 	} | ||||
|  | ||||
| 	uri := c.Request.Header.Get("X-Forwarded-Uri") | ||||
| 	proto := c.Request.Header.Get("X-Forwarded-Proto") | ||||
| 	host := c.Request.Header.Get("X-Forwarded-Host") | ||||
|  | ||||
| 	hostWithoutPort := strings.Split(host, ":")[0] | ||||
| 	id := strings.Split(hostWithoutPort, ".")[0] | ||||
|  | ||||
| 	labels, err := controller.Docker.GetLabels(id, hostWithoutPort) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to get labels from Docker") | ||||
|  | ||||
| 		if req.Proxy == "nginx" || !isBrowser { | ||||
| 			c.JSON(500, gin.H{ | ||||
| 				"status":  500, | ||||
| 				"message": "Internal Server Error", | ||||
| 			}) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	clientIP := c.ClientIP() | ||||
|  | ||||
| 	if controller.Auth.BypassedIP(labels, clientIP) { | ||||
| 		c.Header("Authorization", c.Request.Header.Get("Authorization")) | ||||
|  | ||||
| 		headers := utils.ParseHeaders(labels.Headers) | ||||
|  | ||||
| 		for key, value := range headers { | ||||
| 			log.Debug().Str("header", key).Msg("Setting header") | ||||
| 			c.Header(key, value) | ||||
| 		} | ||||
|  | ||||
| 		if labels.Basic.Username != "" && utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File) != "" { | ||||
| 			log.Debug().Str("username", labels.Basic.Username).Msg("Setting basic auth header") | ||||
| 			c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(labels.Basic.Username, utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File)))) | ||||
| 		} | ||||
|  | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !controller.Auth.CheckIP(labels, clientIP) { | ||||
| 		if req.Proxy == "nginx" || !isBrowser { | ||||
| 			c.JSON(401, gin.H{ | ||||
| 				"status":  401, | ||||
| 				"message": "Unauthorized", | ||||
| 			}) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		queries, err := query.Values(config.UnauthorizedQuery{ | ||||
| 			Resource: strings.Split(host, ".")[0], | ||||
| 			IP:       clientIP, | ||||
| 		}) | ||||
|  | ||||
| 		if err != nil { | ||||
| 			log.Error().Err(err).Msg("Failed to encode unauthorized query") | ||||
| 			c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", controller.Config.AppURL, queries.Encode())) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	authEnabled, err := controller.Auth.AuthEnabled(uri, labels) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to check if auth is enabled for resource") | ||||
|  | ||||
| 		if req.Proxy == "nginx" || !isBrowser { | ||||
| 			c.JSON(500, gin.H{ | ||||
| 				"status":  500, | ||||
| 				"message": "Internal Server Error", | ||||
| 			}) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !authEnabled { | ||||
| 		log.Debug().Msg("Authentication disabled for resource, allowing access") | ||||
|  | ||||
| 		c.Header("Authorization", c.Request.Header.Get("Authorization")) | ||||
|  | ||||
| 		headers := utils.ParseHeaders(labels.Headers) | ||||
|  | ||||
| 		for key, value := range headers { | ||||
| 			log.Debug().Str("header", key).Msg("Setting header") | ||||
| 			c.Header(key, value) | ||||
| 		} | ||||
|  | ||||
| 		if labels.Basic.Username != "" && utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File) != "" { | ||||
| 			log.Debug().Str("username", labels.Basic.Username).Msg("Setting basic auth header") | ||||
| 			c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(labels.Basic.Username, utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File)))) | ||||
| 		} | ||||
|  | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	var userContext config.UserContext | ||||
|  | ||||
| 	context, err := utils.GetContext(c) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Debug().Msg("No user context found in request, treating as not logged in") | ||||
| 		userContext = config.UserContext{ | ||||
| 			IsLoggedIn: false, | ||||
| 		} | ||||
| 	} else { | ||||
| 		userContext = context | ||||
| 	} | ||||
|  | ||||
| 	if userContext.Provider == "basic" && userContext.TotpEnabled { | ||||
| 		log.Debug().Msg("User has TOTP enabled, denying basic auth access") | ||||
| 		userContext.IsLoggedIn = false | ||||
| 	} | ||||
|  | ||||
| 	if userContext.IsLoggedIn { | ||||
| 		appAllowed := controller.Auth.ResourceAllowed(c, userContext, labels) | ||||
|  | ||||
| 		if !appAllowed { | ||||
| 			log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User not allowed to access resource") | ||||
|  | ||||
| 			if req.Proxy == "nginx" || !isBrowser { | ||||
| 				c.JSON(403, gin.H{ | ||||
| 					"status":  403, | ||||
| 					"message": "Forbidden", | ||||
| 				}) | ||||
| 				return | ||||
| 			} | ||||
|  | ||||
| 			queries, err := query.Values(config.UnauthorizedQuery{ | ||||
| 				Resource: strings.Split(host, ".")[0], | ||||
| 			}) | ||||
|  | ||||
| 			if userContext.OAuth { | ||||
| 				queries.Set("username", userContext.Email) | ||||
| 			} else { | ||||
| 				queries.Set("username", userContext.Username) | ||||
| 			} | ||||
|  | ||||
| 			if err != nil { | ||||
| 				log.Error().Err(err).Msg("Failed to encode unauthorized query") | ||||
| 				c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 				return | ||||
| 			} | ||||
|  | ||||
| 			c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", controller.Config.AppURL, queries.Encode())) | ||||
| 			return | ||||
| 		} | ||||
|  | ||||
| 		if userContext.OAuth { | ||||
| 			groupOK := controller.Auth.OAuthGroup(c, userContext, labels) | ||||
|  | ||||
| 			if !groupOK { | ||||
| 				log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User OAuth groups do not match resource requirements") | ||||
|  | ||||
| 				if req.Proxy == "nginx" || !isBrowser { | ||||
| 					c.JSON(403, gin.H{ | ||||
| 						"status":  403, | ||||
| 						"message": "Forbidden", | ||||
| 					}) | ||||
| 					return | ||||
| 				} | ||||
|  | ||||
| 				queries, err := query.Values(config.UnauthorizedQuery{ | ||||
| 					Resource: strings.Split(host, ".")[0], | ||||
| 					GroupErr: true, | ||||
| 				}) | ||||
|  | ||||
| 				if userContext.OAuth { | ||||
| 					queries.Set("username", userContext.Email) | ||||
| 				} else { | ||||
| 					queries.Set("username", userContext.Username) | ||||
| 				} | ||||
|  | ||||
| 				if err != nil { | ||||
| 					log.Error().Err(err).Msg("Failed to encode unauthorized query") | ||||
| 					c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 					return | ||||
| 				} | ||||
|  | ||||
| 				c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", controller.Config.AppURL, queries.Encode())) | ||||
| 				return | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		c.Header("Authorization", c.Request.Header.Get("Authorization")) | ||||
| 		c.Header("Remote-User", utils.SanitizeHeader(userContext.Username)) | ||||
| 		c.Header("Remote-Name", utils.SanitizeHeader(userContext.Name)) | ||||
| 		c.Header("Remote-Email", utils.SanitizeHeader(userContext.Email)) | ||||
| 		c.Header("Remote-Groups", utils.SanitizeHeader(userContext.OAuthGroups)) | ||||
|  | ||||
| 		headers := utils.ParseHeaders(labels.Headers) | ||||
|  | ||||
| 		for key, value := range headers { | ||||
| 			log.Debug().Str("header", key).Msg("Setting header") | ||||
| 			c.Header(key, value) | ||||
| 		} | ||||
|  | ||||
| 		if labels.Basic.Username != "" && utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File) != "" { | ||||
| 			log.Debug().Str("username", labels.Basic.Username).Msg("Setting basic auth header") | ||||
| 			c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(labels.Basic.Username, utils.GetSecret(labels.Basic.Password.Plain, labels.Basic.Password.File)))) | ||||
| 		} | ||||
|  | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if req.Proxy == "nginx" || !isBrowser { | ||||
| 		c.JSON(401, gin.H{ | ||||
| 			"status":  401, | ||||
| 			"message": "Unauthorized", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	queries, err := query.Values(config.RedirectQuery{ | ||||
| 		RedirectURI: fmt.Sprintf("%s://%s%s", proto, host, uri), | ||||
| 	}) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to encode redirect URI query") | ||||
| 		c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.Config.AppURL)) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?%s", controller.Config.AppURL, queries.Encode())) | ||||
| } | ||||
							
								
								
									
										42
									
								
								internal/controller/resources_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								internal/controller/resources_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,42 @@ | ||||
| package controller | ||||
|  | ||||
| import ( | ||||
| 	"net/http" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| ) | ||||
|  | ||||
| type ResourcesControllerConfig struct { | ||||
| 	ResourcesDir string | ||||
| } | ||||
|  | ||||
| type ResourcesController struct { | ||||
| 	Config     ResourcesControllerConfig | ||||
| 	Router     *gin.RouterGroup | ||||
| 	FileServer http.Handler | ||||
| } | ||||
|  | ||||
| func NewResourcesController(config ResourcesControllerConfig, router *gin.RouterGroup) *ResourcesController { | ||||
| 	fileServer := http.StripPrefix("/resources", http.FileServer(http.Dir(config.ResourcesDir))) | ||||
|  | ||||
| 	return &ResourcesController{ | ||||
| 		Config:     config, | ||||
| 		Router:     router, | ||||
| 		FileServer: fileServer, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *ResourcesController) SetupRoutes() { | ||||
| 	controller.Router.GET("/resources/*resource", controller.resourcesHandler) | ||||
| } | ||||
|  | ||||
| func (controller *ResourcesController) resourcesHandler(c *gin.Context) { | ||||
| 	if controller.Config.ResourcesDir == "" { | ||||
| 		c.JSON(404, gin.H{ | ||||
| 			"status":  404, | ||||
| 			"message": "Resources not found", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
| 	controller.FileServer.ServeHTTP(c.Writer, c.Request) | ||||
| } | ||||
							
								
								
									
										266
									
								
								internal/controller/user_controller.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										266
									
								
								internal/controller/user_controller.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,266 @@ | ||||
| package controller | ||||
|  | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/service" | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/pquerna/otp/totp" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type LoginRequest struct { | ||||
| 	Username string `json:"username"` | ||||
| 	Password string `json:"password"` | ||||
| } | ||||
|  | ||||
| type TotpRequest struct { | ||||
| 	Code string `json:"code"` | ||||
| } | ||||
|  | ||||
| type UserControllerConfig struct { | ||||
| 	Domain string | ||||
| } | ||||
|  | ||||
| type UserController struct { | ||||
| 	Config UserControllerConfig | ||||
| 	Router *gin.RouterGroup | ||||
| 	Auth   *service.AuthService | ||||
| } | ||||
|  | ||||
| func NewUserController(config UserControllerConfig, router *gin.RouterGroup, auth *service.AuthService) *UserController { | ||||
| 	return &UserController{ | ||||
| 		Config: config, | ||||
| 		Router: router, | ||||
| 		Auth:   auth, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (controller *UserController) SetupRoutes() { | ||||
| 	userGroup := controller.Router.Group("/user") | ||||
| 	userGroup.POST("/login", controller.loginHandler) | ||||
| 	userGroup.POST("/logout", controller.logoutHandler) | ||||
| 	userGroup.POST("/totp", controller.totpHandler) | ||||
| } | ||||
|  | ||||
| func (controller *UserController) loginHandler(c *gin.Context) { | ||||
| 	var req LoginRequest | ||||
|  | ||||
| 	err := c.ShouldBindJSON(&req) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to bind JSON") | ||||
| 		c.JSON(400, gin.H{ | ||||
| 			"status":  400, | ||||
| 			"message": "Bad Request", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	clientIP := c.ClientIP() | ||||
|  | ||||
| 	rateIdentifier := req.Username | ||||
|  | ||||
| 	if rateIdentifier == "" { | ||||
| 		rateIdentifier = clientIP | ||||
| 	} | ||||
|  | ||||
| 	log.Debug().Str("username", req.Username).Str("ip", clientIP).Msg("Login attempt") | ||||
|  | ||||
| 	isLocked, remainingTime := controller.Auth.IsAccountLocked(rateIdentifier) | ||||
|  | ||||
| 	if isLocked { | ||||
| 		log.Warn().Str("username", req.Username).Str("ip", clientIP).Msg("Account is locked due to too many failed login attempts") | ||||
| 		c.JSON(429, gin.H{ | ||||
| 			"status":  429, | ||||
| 			"message": fmt.Sprintf("Too many failed login attempts. Try again in %d seconds", remainingTime), | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	userSearch := controller.Auth.SearchUser(req.Username) | ||||
|  | ||||
| 	if userSearch.Type == "" { | ||||
| 		log.Warn().Str("username", req.Username).Str("ip", clientIP).Msg("User not found") | ||||
| 		controller.Auth.RecordLoginAttempt(rateIdentifier, false) | ||||
| 		c.JSON(401, gin.H{ | ||||
| 			"status":  401, | ||||
| 			"message": "Unauthorized", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !controller.Auth.VerifyUser(userSearch, req.Password) { | ||||
| 		log.Warn().Str("username", req.Username).Str("ip", clientIP).Msg("Invalid password") | ||||
| 		controller.Auth.RecordLoginAttempt(rateIdentifier, false) | ||||
| 		c.JSON(401, gin.H{ | ||||
| 			"status":  401, | ||||
| 			"message": "Unauthorized", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	log.Info().Str("username", req.Username).Str("ip", clientIP).Msg("Login successful") | ||||
|  | ||||
| 	controller.Auth.RecordLoginAttempt(rateIdentifier, true) | ||||
|  | ||||
| 	if userSearch.Type == "local" { | ||||
| 		user := controller.Auth.GetLocalUser(userSearch.Username) | ||||
|  | ||||
| 		if user.TotpSecret != "" { | ||||
| 			log.Debug().Str("username", req.Username).Msg("User has TOTP enabled, requiring TOTP verification") | ||||
|  | ||||
| 			err := controller.Auth.CreateSessionCookie(c, &config.SessionCookie{ | ||||
| 				Username:    user.Username, | ||||
| 				Name:        utils.Capitalize(req.Username), | ||||
| 				Email:       fmt.Sprintf("%s@%s", strings.ToLower(req.Username), controller.Config.Domain), | ||||
| 				Provider:    "username", | ||||
| 				TotpPending: true, | ||||
| 			}) | ||||
|  | ||||
| 			if err != nil { | ||||
| 				log.Error().Err(err).Msg("Failed to create session cookie") | ||||
| 				c.JSON(500, gin.H{ | ||||
| 					"status":  500, | ||||
| 					"message": "Internal Server Error", | ||||
| 				}) | ||||
| 				return | ||||
| 			} | ||||
|  | ||||
| 			c.JSON(200, gin.H{ | ||||
| 				"status":      200, | ||||
| 				"message":     "TOTP required", | ||||
| 				"totpPending": true, | ||||
| 			}) | ||||
| 			return | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	err = controller.Auth.CreateSessionCookie(c, &config.SessionCookie{ | ||||
| 		Username: req.Username, | ||||
| 		Name:     utils.Capitalize(req.Username), | ||||
| 		Email:    fmt.Sprintf("%s@%s", strings.ToLower(req.Username), controller.Config.Domain), | ||||
| 		Provider: "username", | ||||
| 	}) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to create session cookie") | ||||
| 		c.JSON(500, gin.H{ | ||||
| 			"status":  500, | ||||
| 			"message": "Internal Server Error", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.JSON(200, gin.H{ | ||||
| 		"status":  200, | ||||
| 		"message": "Login successful", | ||||
| 	}) | ||||
| } | ||||
|  | ||||
| func (controller *UserController) logoutHandler(c *gin.Context) { | ||||
| 	log.Debug().Msg("Logout request received") | ||||
|  | ||||
| 	controller.Auth.DeleteSessionCookie(c) | ||||
|  | ||||
| 	c.JSON(200, gin.H{ | ||||
| 		"status":  200, | ||||
| 		"message": "Logout successful", | ||||
| 	}) | ||||
| } | ||||
|  | ||||
| func (controller *UserController) totpHandler(c *gin.Context) { | ||||
| 	var req TotpRequest | ||||
|  | ||||
| 	err := c.ShouldBindJSON(&req) | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to bind JSON") | ||||
| 		c.JSON(400, gin.H{ | ||||
| 			"status":  400, | ||||
| 			"message": "Bad Request", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	context, err := utils.GetContext(c) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to get user context") | ||||
| 		c.JSON(500, gin.H{ | ||||
| 			"status":  500, | ||||
| 			"message": "Internal Server Error", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !context.TotpPending { | ||||
| 		log.Warn().Msg("TOTP attempt without a pending TOTP session") | ||||
| 		c.JSON(401, gin.H{ | ||||
| 			"status":  401, | ||||
| 			"message": "Unauthorized", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	clientIP := c.ClientIP() | ||||
|  | ||||
| 	rateIdentifier := context.Username | ||||
|  | ||||
| 	if rateIdentifier == "" { | ||||
| 		rateIdentifier = clientIP | ||||
| 	} | ||||
|  | ||||
| 	log.Debug().Str("username", context.Username).Str("ip", clientIP).Msg("TOTP verification attempt") | ||||
|  | ||||
| 	isLocked, remainingTime := controller.Auth.IsAccountLocked(rateIdentifier) | ||||
|  | ||||
| 	if isLocked { | ||||
| 		log.Warn().Str("username", context.Username).Str("ip", clientIP).Msg("Account is locked due to too many failed TOTP attempts") | ||||
| 		c.JSON(429, gin.H{ | ||||
| 			"status":  429, | ||||
| 			"message": fmt.Sprintf("Too many failed login attempts. Try again in %d seconds", remainingTime), | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	user := controller.Auth.GetLocalUser(context.Username) | ||||
|  | ||||
| 	ok := totp.Validate(req.Code, user.TotpSecret) | ||||
|  | ||||
| 	if !ok { | ||||
| 		log.Warn().Str("username", context.Username).Str("ip", clientIP).Msg("Invalid TOTP code") | ||||
| 		controller.Auth.RecordLoginAttempt(rateIdentifier, false) | ||||
| 		c.JSON(401, gin.H{ | ||||
| 			"status":  401, | ||||
| 			"message": "Unauthorized", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	log.Info().Str("username", context.Username).Str("ip", clientIP).Msg("TOTP verification successful") | ||||
|  | ||||
| 	controller.Auth.RecordLoginAttempt(rateIdentifier, true) | ||||
|  | ||||
| 	err = controller.Auth.CreateSessionCookie(c, &config.SessionCookie{ | ||||
| 		Username: user.Username, | ||||
| 		Name:     utils.Capitalize(user.Username), | ||||
| 		Email:    fmt.Sprintf("%s@%s", strings.ToLower(user.Username), controller.Config.Domain), | ||||
| 		Provider: "username", | ||||
| 	}) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to create session cookie") | ||||
| 		c.JSON(500, gin.H{ | ||||
| 			"status":  500, | ||||
| 			"message": "Internal Server Error", | ||||
| 		}) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	c.JSON(200, gin.H{ | ||||
| 		"status":  200, | ||||
| 		"message": "Login successful", | ||||
| 	}) | ||||
| } | ||||
		Reference in New Issue
	
	Block a user
	 Stavros
					Stavros