feat: add ldap support

This commit is contained in:
Stavros
2025-07-05 02:20:12 +03:00
parent 4524e3322c
commit 1e413e671f
9 changed files with 302 additions and 56 deletions

View File

@@ -7,6 +7,7 @@ import (
"sync"
"time"
"tinyauth/internal/docker"
"tinyauth/internal/ldap"
"tinyauth/internal/types"
"tinyauth/internal/utils"
@@ -22,9 +23,10 @@ type Auth struct {
LoginAttempts map[string]*types.LoginAttempt
LoginMutex sync.RWMutex
Store *sessions.CookieStore
LDAP *ldap.LDAP
}
func NewAuth(config types.AuthConfig, docker *docker.Docker) *Auth {
func NewAuth(config types.AuthConfig, docker *docker.Docker, ldap *ldap.LDAP) *Auth {
// Create cookie store
store := sessions.NewCookieStore([]byte(config.HMACSecret), []byte(config.EncryptionSecret))
@@ -42,6 +44,7 @@ func NewAuth(config types.AuthConfig, docker *docker.Docker) *Auth {
Docker: docker,
LoginAttempts: make(map[string]*types.LoginAttempt),
Store: store,
LDAP: ldap,
}
}
@@ -68,14 +71,87 @@ func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
return session, nil
}
func (auth *Auth) GetUser(username string) *types.User {
func (auth *Auth) GetUser(username string) types.UserSearch {
// Loop through users and return the user if the username matches
log.Debug().Str("username", username).Msg("Searching for user")
for _, user := range auth.Config.Users {
if user.Username == username {
return &user
return types.UserSearch{
Username: user.Username,
Type: "local",
}
}
}
return nil
// 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",
}
}
return types.UserSearch{}
}
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
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
auth.LDAP.Bind(auth.LDAP.Config.BindUser, auth.LDAP.Config.BindPassword)
log.Debug().Str("username", search.Username).Msg("LDAP authentication successful")
// Return true if the bind was successful
return true
}
}
// If no user found or authentication failed, return false
log.Warn().Str("username", search.Username).Msg("User authentication failed")
return false
}
func (auth *Auth) GetLocalUser(username string) types.User {
// Loop through users and return the user if the username matches
log.Debug().Str("username", username).Msg("Searching for local user")
for _, user := range auth.Config.Users {
if user.Username == username {
return user
}
}
// If no user found, return an empty user
log.Warn().Str("username", username).Msg("Local user not found")
return types.User{}
}
func (auth *Auth) CheckPassword(user types.User, password string) bool {

View File

@@ -363,10 +363,12 @@ func (h *Handlers) LoginHandler(c *gin.Context) {
}
// Get user based on username
user := h.Auth.GetUser(login.Username)
userSearch := h.Auth.GetUser(login.Username)
log.Debug().Interface("userSearch", userSearch).Msg("Searching for user")
// User does not exist
if user == nil {
if userSearch.Type == "" {
log.Debug().Str("username", login.Username).Msg("User not found")
// Record failed login attempt
h.Auth.RecordLoginAttempt(rateIdentifier, false)
@@ -380,7 +382,7 @@ func (h *Handlers) LoginHandler(c *gin.Context) {
log.Debug().Msg("Got user")
// Check if password is correct
if !h.Auth.CheckPassword(*user, login.Password) {
if !h.Auth.VerifyUser(userSearch, login.Password) {
log.Debug().Str("username", login.Username).Msg("Password incorrect")
// Record failed login attempt
h.Auth.RecordLoginAttempt(rateIdentifier, false)
@@ -396,28 +398,34 @@ func (h *Handlers) LoginHandler(c *gin.Context) {
// Record successful login attempt (will reset failed attempt counter)
h.Auth.RecordLoginAttempt(rateIdentifier, true)
// Check if user has totp enabled
if user.TotpSecret != "" {
log.Debug().Msg("Totp enabled")
// Check if user is using TOTP
if userSearch.Type == "local" {
// Get local user
localUser := h.Auth.GetLocalUser(login.Username)
// Set totp pending cookie
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
Username: login.Username,
Name: utils.Capitalize(login.Username),
Email: fmt.Sprintf("%s@%s", strings.ToLower(login.Username), h.Config.Domain),
Provider: "username",
TotpPending: true,
})
// Check if TOTP is enabled
if localUser.TotpSecret != "" {
log.Debug().Msg("Totp enabled")
// Return totp required
c.JSON(200, gin.H{
"status": 200,
"message": "Waiting for totp",
"totpPending": true,
})
// Set totp pending cookie
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
Username: login.Username,
Name: utils.Capitalize(login.Username),
Email: fmt.Sprintf("%s@%s", strings.ToLower(login.Username), h.Config.Domain),
Provider: "username",
TotpPending: true,
})
// Stop further processing
return
// Return totp required
c.JSON(200, gin.H{
"status": 200,
"message": "Waiting for totp",
"totpPending": true,
})
// Stop further processing
return
}
}
// Create session cookie with username as provider
@@ -469,17 +477,7 @@ func (h *Handlers) TotpHandler(c *gin.Context) {
}
// Get user
user := h.Auth.GetUser(userContext.Username)
// Check if user exists
if user == nil {
log.Debug().Msg("User not found")
c.JSON(401, gin.H{
"status": 401,
"message": "Unauthorized",
})
return
}
user := h.Auth.GetLocalUser(userContext.Username)
// Check if totp is correct
ok := totp.Validate(totpReq.Code, user.TotpSecret)

View File

@@ -36,29 +36,48 @@ func (hooks *Hooks) UseUserContext(c *gin.Context) types.UserContext {
log.Debug().Msg("Got basic auth")
// Get user
user := hooks.Auth.GetUser(basic.Username)
userSearch := hooks.Auth.GetUser(basic.Username)
// Check we have a user
if user == nil {
if userSearch.Type == "" {
log.Error().Str("username", basic.Username).Msg("User does not exist")
// Return empty context
return types.UserContext{}
}
// Check if the user has a correct password
if hooks.Auth.CheckPassword(*user, basic.Password) {
// Return user context since we are logged in with basic auth
// Verify the user
if !hooks.Auth.VerifyUser(userSearch, basic.Password) {
log.Error().Str("username", basic.Username).Msg("Password incorrect")
// Return empty context
return types.UserContext{}
}
// Get the user type
if userSearch.Type == "ldap" {
log.Debug().Msg("User is LDAP")
return types.UserContext{
Username: basic.Username,
Name: utils.Capitalize(basic.Username),
Email: fmt.Sprintf("%s@%s", strings.ToLower(basic.Username), hooks.Config.Domain),
IsLoggedIn: true,
Provider: "basic",
TotpEnabled: user.TotpSecret != "",
TotpEnabled: false,
}
}
user := hooks.Auth.GetLocalUser(basic.Username)
return types.UserContext{
Username: basic.Username,
Name: utils.Capitalize(basic.Username),
Email: fmt.Sprintf("%s@%s", strings.ToLower(basic.Username), hooks.Config.Domain),
IsLoggedIn: true,
Provider: "basic",
TotpEnabled: user.TotpSecret != "",
}
}
// Check cookie error after basic auth
@@ -85,18 +104,25 @@ func (hooks *Hooks) UseUserContext(c *gin.Context) types.UserContext {
if cookie.Provider == "username" {
log.Debug().Msg("Provider is username")
// Check if user exists
if hooks.Auth.GetUser(cookie.Username) != nil {
log.Debug().Msg("User exists")
// Get user
userSearch := hooks.Auth.GetUser(cookie.Username)
// It exists so we are logged in
return types.UserContext{
Username: cookie.Username,
Name: cookie.Name,
Email: cookie.Email,
IsLoggedIn: true,
Provider: "username",
}
if userSearch.Type == "" {
log.Error().Str("username", cookie.Username).Msg("User does not exist")
// Return empty context
return types.UserContext{}
}
log.Debug().Str("type", userSearch.Type).Msg("User exists")
// It exists so we are logged in
return types.UserContext{
Username: cookie.Username,
Name: cookie.Name,
Email: cookie.Email,
IsLoggedIn: true,
Provider: "username",
}
}

74
internal/ldap/ldap.go Normal file
View File

@@ -0,0 +1,74 @@
package ldap
import (
"fmt"
"tinyauth/internal/types"
ldapgo "github.com/go-ldap/ldap/v3"
)
type LDAP struct {
Config types.LdapConfig
Conn *ldapgo.Conn
BaseDN string
}
func NewLDAP(config types.LdapConfig) (*LDAP, error) {
// Connect to the LDAP server
conn, err := ldapgo.DialURL(config.Address)
if err != nil {
return nil, err
}
// Try to connect using TLS
// conn.StartTLS(&tls.Config{
// InsecureSkipVerify: true,
// })
// Bind to the LDAP server with the provided credentials
err = conn.Bind(config.BindUser, config.BindPassword)
if err != nil {
return nil, err
}
return &LDAP{
Config: config,
Conn: conn,
BaseDN: config.BaseDN,
}, nil
}
func (l *LDAP) Search(username string) (string, error) {
// Create a search request to find the user by username
searchRequest := ldapgo.NewSearchRequest(
l.BaseDN,
ldapgo.ScopeWholeSubtree, ldapgo.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(uid=%s)", username),
[]string{"dn"},
nil,
)
// Perform the search
searchResult, err := l.Conn.Search(searchRequest)
if err != nil {
return "", err
}
if len(searchResult.Entries) != 1 {
return "", fmt.Errorf("user not found or multiple entries found for username: %s", username)
}
// User found, return the distinguished name (DN)
userDN := searchResult.Entries[0].DN
return userDN, nil
}
func (l *LDAP) Bind(userDN string, password string) error {
// Bind to the LDAP server with the user's DN and password
err := l.Conn.Bind(userDN, password)
if err != nil {
return err
}
return nil
}

View File

@@ -36,6 +36,10 @@ type Config struct {
LoginMaxRetries int `mapstructure:"login-max-retries"`
FogotPasswordMessage string `mapstructure:"forgot-password-message" validate:"required"`
BackgroundImage string `mapstructure:"background-image" validate:"required"`
LdapAddress string `mapstructure:"ldap-address"`
LdapBindUser string `mapstructure:"ldap-bind-user"`
LdapBindPassword string `mapstructure:"ldap-bind-password"`
LdapBaseDN string `mapstructure:"ldap-base-dn"`
}
// Server configuration
@@ -122,3 +126,11 @@ type Labels struct {
OAuth OAuthLabels
IP IPLabels
}
// Ldap config is a struct that contains the configuration for the LDAP service
type LdapConfig struct {
Address string
BindUser string
BindPassword string
BaseDN string
}

View File

@@ -12,6 +12,12 @@ type User struct {
TotpSecret string
}
// UserSearch is the response of the get user
type UserSearch struct {
Username string
Type string // "local", "ldap" or empty
}
// Users is a list of users
type Users []User