chore: remove meaningless comments

This commit is contained in:
Stavros
2025-07-12 13:17:06 +03:00
parent e742603c15
commit 8ebed0ac9a
24 changed files with 81 additions and 876 deletions

View File

@@ -27,10 +27,8 @@ type Auth struct {
}
func NewAuth(config types.AuthConfig, docker *docker.Docker, ldap *ldap.LDAP) *Auth {
// Create cookie store
// Setup cookie store and create the auth service
store := sessions.NewCookieStore([]byte(config.HMACSecret), []byte(config.EncryptionSecret))
// Configure cookie store
store.Options = &sessions.Options{
Path: "/",
MaxAge: config.SessionExpiry,
@@ -38,7 +36,6 @@ func NewAuth(config types.AuthConfig, docker *docker.Docker, ldap *ldap.LDAP) *A
HttpOnly: true,
Domain: fmt.Sprintf(".%s", config.Domain),
}
return &Auth{
Config: config,
Docker: docker,
@@ -49,20 +46,14 @@ func NewAuth(config types.AuthConfig, docker *docker.Docker, ldap *ldap.LDAP) *A
}
func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
// Get session
session, err := auth.Store.Get(c.Request, auth.Config.SessionCookieName)
// If there was an error getting the session, it might be invalid so let's clear it and retry
if err != nil {
log.Warn().Err(err).Msg("Invalid session, clearing cookie and retrying")
// Delete the session cookie if there is an error
c.SetCookie(auth.Config.SessionCookieName, "", -1, "/", fmt.Sprintf(".%s", auth.Config.Domain), auth.Config.CookieSecure, true)
// Try to get the session again
session, err = auth.Store.Get(c.Request, auth.Config.SessionCookieName)
if err != nil {
// If we still can't get the session, log the error and return nil
log.Error().Err(err).Msg("Failed to get session")
return nil, err
}
@@ -72,13 +63,11 @@ func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
}
func (auth *Auth) SearchUser(username string) types.UserSearch {
// Loop through users and return the user if the username matches
log.Debug().Str("username", username).Msg("Searching for user")
// Check local users first
if auth.GetLocalUser(username).Username != "" {
log.Debug().Str("username", username).Msg("Found local user")
// If user found, return a user with the username and type "local"
return types.UserSearch{
Username: username,
Type: "local",
@@ -88,14 +77,11 @@ func (auth *Auth) SearchUser(username string) types.UserSearch {
// If no user found, check LDAP
if auth.LDAP != nil {
log.Debug().Str("username", username).Msg("Checking LDAP for user")
userDN, err := auth.LDAP.Search(username)
if err != nil {
log.Warn().Err(err).Str("username", username).Msg("Failed to find user in LDAP")
return types.UserSearch{}
}
// If user found in LDAP, return a user with the DN as username
return types.UserSearch{
Username: userDN,
Type: "ldap",
@@ -109,34 +95,28 @@ func (auth *Auth) VerifyUser(search types.UserSearch, password string) bool {
// Authenticate the user based on the type
switch search.Type {
case "local":
// Get local user
// If local user, get the user and check the password
user := auth.GetLocalUser(search.Username)
// Check if password is correct
return auth.CheckPassword(user, password)
case "ldap":
// If LDAP is configured, bind to the LDAP server with the user DN and password
if auth.LDAP != nil {
log.Debug().Str("username", search.Username).Msg("Binding to LDAP for user authentication")
// Bind to the LDAP server
err := auth.LDAP.Bind(search.Username, password)
if err != nil {
log.Warn().Err(err).Str("username", search.Username).Msg("Failed to bind to LDAP")
return false
}
// If bind is successful, rebind with the LDAP bind user
// Rebind with the service account to reset the connection
err = auth.LDAP.Bind(auth.LDAP.Config.BindDN, auth.LDAP.Config.BindPassword)
if err != nil {
log.Error().Err(err).Msg("Failed to rebind with service account after user authentication")
// Consider closing the connection or creating a new one
return false
}
log.Debug().Str("username", search.Username).Msg("LDAP authentication successful")
// Return true if the bind was successful
return true
}
default:
@@ -165,11 +145,9 @@ func (auth *Auth) GetLocalUser(username string) types.User {
}
func (auth *Auth) CheckPassword(user types.User, password string) bool {
// Compare the hashed password with the password provided
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) == nil
}
// IsAccountLocked checks if a username or IP is locked due to too many failed login attempts
func (auth *Auth) IsAccountLocked(identifier string) (bool, int) {
auth.LoginMutex.RLock()
defer auth.LoginMutex.RUnlock()
@@ -196,7 +174,6 @@ func (auth *Auth) IsAccountLocked(identifier string) (bool, int) {
return false, 0
}
// RecordLoginAttempt records a login attempt for rate limiting
func (auth *Auth) RecordLoginAttempt(identifier string, success bool) {
// Skip if rate limiting is not configured
if auth.Config.LoginMaxRetries <= 0 || auth.Config.LoginTimeout <= 0 {
@@ -240,7 +217,6 @@ func (auth *Auth) EmailWhitelisted(email string) bool {
func (auth *Auth) CreateSessionCookie(c *gin.Context, data *types.SessionCookie) error {
log.Debug().Msg("Creating session cookie")
// Get session
session, err := auth.GetSession(c)
if err != nil {
log.Error().Err(err).Msg("Failed to get session")
@@ -249,7 +225,6 @@ func (auth *Auth) CreateSessionCookie(c *gin.Context, data *types.SessionCookie)
log.Debug().Msg("Setting session cookie")
// Calculate expiry
var sessionExpiry int
if data.TotpPending {
@@ -258,7 +233,6 @@ func (auth *Auth) CreateSessionCookie(c *gin.Context, data *types.SessionCookie)
sessionExpiry = auth.Config.SessionExpiry
}
// Set data
session.Values["username"] = data.Username
session.Values["name"] = data.Name
session.Values["email"] = data.Email
@@ -267,21 +241,18 @@ func (auth *Auth) CreateSessionCookie(c *gin.Context, data *types.SessionCookie)
session.Values["totpPending"] = data.TotpPending
session.Values["oauthGroups"] = data.OAuthGroups
// Save session
err = session.Save(c.Request, c.Writer)
if err != nil {
log.Error().Err(err).Msg("Failed to save session")
return err
}
// Return nil
return nil
}
func (auth *Auth) DeleteSessionCookie(c *gin.Context) error {
log.Debug().Msg("Deleting session cookie")
// Get session
session, err := auth.GetSession(c)
if err != nil {
log.Error().Err(err).Msg("Failed to get session")
@@ -293,21 +264,18 @@ func (auth *Auth) DeleteSessionCookie(c *gin.Context) error {
delete(session.Values, key)
}
// Save session
err = session.Save(c.Request, c.Writer)
if err != nil {
log.Error().Err(err).Msg("Failed to save session")
return err
}
// Return nil
return nil
}
func (auth *Auth) GetSessionCookie(c *gin.Context) (types.SessionCookie, error) {
log.Debug().Msg("Getting session cookie")
// Get session
session, err := auth.GetSession(c)
if err != nil {
log.Error().Err(err).Msg("Failed to get session")
@@ -316,7 +284,6 @@ func (auth *Auth) GetSessionCookie(c *gin.Context) (types.SessionCookie, error)
log.Debug().Msg("Got session")
// Get data from session
username, usernameOk := session.Values["username"].(string)
email, emailOk := session.Values["email"].(string)
name, nameOk := session.Values["name"].(string)
@@ -325,30 +292,21 @@ func (auth *Auth) GetSessionCookie(c *gin.Context) (types.SessionCookie, error)
totpPending, totpPendingOk := session.Values["totpPending"].(bool)
oauthGroups, oauthGroupsOk := session.Values["oauthGroups"].(string)
// If any data is missing, delete the session cookie
if !usernameOk || !providerOK || !expiryOk || !totpPendingOk || !emailOk || !nameOk || !oauthGroupsOk {
log.Warn().Msg("Session cookie is invalid")
// If any data is missing, delete the session cookie
auth.DeleteSessionCookie(c)
// Return empty cookie
return types.SessionCookie{}, nil
}
// Check if the cookie has expired
// If the session cookie has expired, delete it
if time.Now().Unix() > expiry {
log.Warn().Msg("Session cookie expired")
// If it has, delete it
auth.DeleteSessionCookie(c)
// Return empty cookie
return types.SessionCookie{}, nil
}
log.Debug().Str("username", username).Str("provider", provider).Int64("expiry", expiry).Bool("totpPending", totpPending).Str("name", name).Str("email", email).Str("oauthGroups", oauthGroups).Msg("Parsed cookie")
// Return the cookie
return types.SessionCookie{
Username: username,
Name: name,
@@ -360,25 +318,21 @@ func (auth *Auth) GetSessionCookie(c *gin.Context) (types.SessionCookie, error)
}
func (auth *Auth) UserAuthConfigured() bool {
// If there are users, return true
// If there are users or LDAP is configured, return true
return len(auth.Config.Users) > 0 || auth.LDAP != nil
}
func (auth *Auth) ResourceAllowed(c *gin.Context, context types.UserContext, labels types.Labels) bool {
// Check if oauth is allowed
if context.OAuth {
log.Debug().Msg("Checking OAuth whitelist")
return utils.CheckFilter(labels.OAuth.Whitelist, context.Email)
}
// Check users
log.Debug().Msg("Checking users")
return utils.CheckFilter(labels.Users, context.Username)
}
func (auth *Auth) OAuthGroup(c *gin.Context, context types.UserContext, labels types.Labels) bool {
// Check if groups are required
if labels.OAuth.Groups == "" {
return true
}
@@ -402,18 +356,12 @@ func (auth *Auth) OAuthGroup(c *gin.Context, context types.UserContext, labels t
// No groups matched
log.Debug().Msg("No groups matched")
// Return false
return false
}
func (auth *Auth) AuthEnabled(c *gin.Context, labels types.Labels) (bool, error) {
// Get headers
uri := c.Request.Header.Get("X-Forwarded-Uri")
// Check if the allowed label is empty
func (auth *Auth) AuthEnabled(uri string, labels types.Labels) (bool, error) {
// If the label is empty, auth is enabled
if labels.Allowed == "" {
// Auth enabled
return true, nil
}
@@ -426,9 +374,8 @@ func (auth *Auth) AuthEnabled(c *gin.Context, labels types.Labels) (bool, error)
return true, err
}
// Check if the uri matches the regex
// If the regex matches the URI, auth is not enabled
if regex.MatchString(uri) {
// Auth disabled
return false, nil
}
@@ -437,15 +384,10 @@ func (auth *Auth) AuthEnabled(c *gin.Context, labels types.Labels) (bool, error)
}
func (auth *Auth) GetBasicAuth(c *gin.Context) *types.User {
// Get the Authorization header
username, password, ok := c.Request.BasicAuth()
// If not ok, return an empty user
if !ok {
return nil
}
// Return the user
return &types.User{
Username: username,
Password: password,
@@ -486,7 +428,6 @@ func (auth *Auth) CheckIP(labels types.Labels, ip string) bool {
}
log.Debug().Str("ip", ip).Msg("IP not in allow or block list, allowing by default")
return true
}
@@ -505,6 +446,5 @@ func (auth *Auth) BypassedIP(labels types.Labels, ip string) bool {
}
log.Debug().Str("ip", ip).Msg("IP not in bypass list, continuing with authentication")
return false
}

View File

@@ -4,7 +4,6 @@ import (
"testing"
"time"
"tinyauth/internal/auth"
"tinyauth/internal/docker"
"tinyauth/internal/types"
)
@@ -18,7 +17,7 @@ func TestLoginRateLimiting(t *testing.T) {
// Initialize a new auth service with 3 max retries and 5 seconds timeout
config.LoginMaxRetries = 3
config.LoginTimeout = 5
authService := auth.NewAuth(config, &docker.Docker{}, nil)
authService := auth.NewAuth(config, nil, nil)
// Test identifier
identifier := "test_user"
@@ -62,7 +61,7 @@ func TestLoginRateLimiting(t *testing.T) {
// Reinitialize auth service with a shorter timeout for testing
config.LoginTimeout = 1
config.LoginMaxRetries = 3
authService = auth.NewAuth(config, &docker.Docker{}, nil)
authService = auth.NewAuth(config, nil, nil)
// Add enough failed attempts to lock the account
for i := 0; i < 3; i++ {
@@ -87,7 +86,7 @@ func TestLoginRateLimiting(t *testing.T) {
t.Log("Testing disabled rate limiting")
config.LoginMaxRetries = 0
config.LoginTimeout = 0
authService = auth.NewAuth(config, &docker.Docker{}, nil)
authService = auth.NewAuth(config, nil, nil)
for i := 0; i < 10; i++ {
authService.RecordLoginAttempt(identifier, false)
@@ -103,7 +102,7 @@ func TestConcurrentLoginAttempts(t *testing.T) {
// Initialize a new auth service with 2 max retries and 5 seconds timeout
config.LoginMaxRetries = 2
config.LoginTimeout = 5
authService := auth.NewAuth(config, &docker.Docker{}, nil)
authService := auth.NewAuth(config, nil, nil)
// Test multiple identifiers
identifiers := []string{"user1", "user2", "user3"}