auth

package
v1.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2026 License: MIT Imports: 17 Imported by: 0

README

AegisGate Authentication Package

Enterprise-grade authentication system for AegisGate.

Features

  • OAuth 2.0 (Google, Microsoft, GitHub, Okta, Auth0)
  • SAML 2.0 support (Azure, Okta)
  • Local username/password authentication
  • Role-Based Access Control (RBAC)
  • Session management with secure cookies
  • Zero external dependencies

Files

  • auth.go - Core types and configuration
  • utils.go - Helper functions
  • session.go - Session management
  • local.go - Local authentication
  • oauth.go - OAuth 2.0 implementation
  • middleware.go - HTTP middleware
  • handlers.go - HTTP handlers
  • auth_test.go - Unit tests

Status

Build: SUCCESS Vet: PASSED Dependencies: Zero external (Go standard library only)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var OAuthProviderEndpoints = map[Provider]OAuthEndpoints{
	ProviderGoogle: {
		AuthURL:     "https://accounts.google.com/o/oauth2/v2/auth",
		TokenURL:    "https://oauth2.googleapis.com/token",
		UserInfoURL: "https://openidconnect.googleapis.com/v1/userinfo",
		Scopes:      []string{"openid", "profile", "email"},
	},
	ProviderMicrosoft: {
		AuthURL:     "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
		TokenURL:    "https://login.microsoftonline.com/common/oauth2/v2.0/token",
		UserInfoURL: "https://graph.microsoft.com/v1.0/me",
		Scopes:      []string{"openid", "profile", "email", "User.Read"},
	},
	ProviderGitHub: {
		AuthURL:     "https://github.com/login/oauth/authorize",
		TokenURL:    "https://github.com/login/oauth/access_token",
		UserInfoURL: "https://api.github.com/user",
		Scopes:      []string{"read:user", "user:email"},
	},
	ProviderOkta: {
		Scopes: []string{"openid", "profile", "email"},
	},
	ProviderAuth0: {
		Scopes: []string{"openid", "profile", "email"},
	},
}

OAuthProviderEndpoints maps provider names to their OAuth endpoints.

RolePermissions maps roles to permissions.

Functions

This section is empty.

Types

type Config

type Config struct {
	Provider        Provider
	ClientID        string
	ClientSecret    string
	RedirectURL     string
	AuthURL         string
	TokenURL        string
	UserInfoURL     string
	Scopes          []string
	SAMLMetadataURL string
	SAMLIssuer      string
	SAMLCertPath    string
	SessionDuration time.Duration
	CookieName      string
	CookieSecure    bool
	CookieHTTPOnly  bool
	CookieSameSite  http.SameSite
	RequireHTTPS    bool
	MaxSessions     int
	EnableMFA       bool
	AllowedDomains  []string
	BlockedDomains  []string
	LocalUsers      map[string]LocalUserConfig
}

Config holds authentication configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default authentication configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

type LocalUserConfig

type LocalUserConfig struct {
	PasswordHash string
	Salt         string
	Role         Role
	Enabled      bool
}

LocalUserConfig holds local user credentials

type LocalUserInfo

type LocalUserInfo struct {
	Username string
	Role     Role
	Enabled  bool
}

LocalUserInfo holds public user information

type LoginResult

type LoginResult struct {
	Success   bool      `json:"success"`
	Token     string    `json:"token"`
	Error     string    `json:"error"`
	ExpiresAt time.Time `json:"expires_at"`
}

LoginResult represents the result of a login attempt

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles authentication and session management

func NewManager

func NewManager(config *Config) (*Manager, error)

NewManager creates a new authentication manager

func (*Manager) Close

func (m *Manager) Close()

Close shuts down the authentication manager

func (*Manager) CreateLocalUser

func (m *Manager) CreateLocalUser(username, password string, role Role) error

CreateLocalUser creates a new local user

func (*Manager) CreateSession

func (m *Manager) CreateSession(user *User, r *http.Request) (*Session, error)

CreateSession creates a new authenticated session

func (*Manager) GetActiveSessions

func (m *Manager) GetActiveSessions() []*Session

GetActiveSessions returns all active sessions

func (*Manager) GetConfig

func (m *Manager) GetConfig() *Config

GetConfig returns the authentication configuration

func (*Manager) GetSession

func (m *Manager) GetSession(sessionID string) (*Session, error)

GetSession retrieves a session by ID

func (*Manager) GetSessionFromContext

func (m *Manager) GetSessionFromContext(ctx context.Context) *Session

GetSessionFromContext retrieves session from request context

func (*Manager) GetSessionFromRequest

func (m *Manager) GetSessionFromRequest(r *http.Request) (*Session, error)

GetSessionFromRequest extracts session from HTTP request cookie

func (*Manager) GetUserFromContext

func (m *Manager) GetUserFromContext(ctx context.Context) *User

GetUserFromContext retrieves user from request context

func (*Manager) GetUserSessions

func (m *Manager) GetUserSessions(userID string) []*Session

GetUserSessions returns all sessions for a user

func (*Manager) HandleOAuthCallback

func (m *Manager) HandleOAuthCallback(w http.ResponseWriter, r *http.Request)

HandleOAuthCallback processes the OAuth callback response.

func (*Manager) Handler

func (m *Manager) Handler() http.Handler

Handler returns HTTP handlers for authentication

func (*Manager) InitOAuthFlow

func (m *Manager) InitOAuthFlow(w http.ResponseWriter, r *http.Request)

InitOAuthFlow initiates the OAuth authentication flow. InitOAuthFlow initiates OAuth authentication flow for the given provider.

func (*Manager) InvalidateSession

func (m *Manager) InvalidateSession(sessionID string) error

InvalidateSession marks a session as inactive

func (*Manager) InvalidateUserSessions

func (m *Manager) InvalidateUserSessions(userID string)

InvalidateUserSessions invalidates all sessions for a user

func (*Manager) ListLocalUsers

func (m *Manager) ListLocalUsers() []LocalUserInfo

ListLocalUsers returns all local users

func (*Manager) LocalLogin

func (m *Manager) LocalLogin(w http.ResponseWriter, r *http.Request)

LocalLogin handles local username/password authentication

func (*Manager) Logout

func (m *Manager) Logout(w http.ResponseWriter, r *http.Request) error

Logout handles user logout

func (*Manager) OptionalAuth

func (m *Manager) OptionalAuth(next http.Handler) http.Handler

OptionalAuth middleware adds user to context if authenticated, but doesn't require it

func (*Manager) RefreshSession

func (m *Manager) RefreshSession(sessionID string) error

RefreshSession extends session expiration

func (*Manager) RequireAdmin

func (m *Manager) RequireAdmin(next http.Handler) http.Handler

RequireAdmin middleware ensures user is an admin

func (*Manager) RequireAuth

func (m *Manager) RequireAuth(next http.Handler) http.Handler

RequireAuth middleware ensures user is authenticated

func (*Manager) RequirePermission

func (m *Manager) RequirePermission(permission Permission) func(http.Handler) http.Handler

RequirePermission middleware checks if user has specific permission

func (*Manager) RequireRole

func (m *Manager) RequireRole(role Role) func(http.Handler) http.Handler

RequireRole middleware checks if user has specific role

type OAuthEndpoints

type OAuthEndpoints struct {
	AuthURL     string
	TokenURL    string
	UserInfoURL string
	Scopes      []string
}

OAuthEndpoints holds OAuth provider endpoint URLs. OAuthEndpoints defines OAuth provider endpoint URLs.

type OAuthTokenResponse

type OAuthTokenResponse struct {
	AccessToken  string
	TokenType    string
	ExpiresIn    int
	RefreshToken string
	IDToken      string
	Scope        string
}

OAuthTokenResponse contains OAuth token response data. OAuthTokenResponse contains the OAuth token response from the provider.

type OAuthUserInfo

type OAuthUserInfo struct {
	ID            string
	Email         string
	Name          string
	GivenName     string
	FamilyName    string
	Picture       string
	VerifiedEmail bool
	Provider      string
}

OAuthUserInfo contains user information from OAuth provider. OAuthUserInfo represents user information returned by OAuth provider.

type Permission

type Permission string

Permission represents a specific authorization permission

const (

	// PermViewDashboard is the permission to view the dashboard.
	PermViewDashboard  Permission = "view:dashboard"
	PermManagePolicies Permission = "manage:policies"
	PermManageCerts    Permission = "manage:certificates"
	PermViewLogs       Permission = "view:logs"
	PermManageUsers    Permission = "manage:users"
	PermViewReports    Permission = "view:reports"
	PermSystemConfig   Permission = "system:config"
	PermViewAlerts     Permission = "view:alerts"
)

type Provider

type Provider string

Provider represents an authentication provider type

const (

	// ProviderGoogle identifies the Google OAuth provider.
	ProviderGoogle Provider = "google"
	// ProviderMicrosoft identifies the Microsoft OAuth provider.
	ProviderMicrosoft   Provider = "microsoft"
	ProviderGitHub      Provider = "github"
	ProviderOkta        Provider = "okta"
	ProviderAuth0       Provider = "auth0"
	ProviderGeneric     Provider = "generic_oauth"
	ProviderSAMLGeneric Provider = "saml"
	ProviderSAMLAzure   Provider = "saml_azure"
	ProviderSALMOkta    Provider = "saml_okta"
	ProviderLocal       Provider = "local"
)

type Role

type Role string

Role represents user authorization level

const (

	// RoleAdmin defines the administrator role level.
	RoleAdmin Role = "admin"
	// RoleOperator defines the operator role level.
	RoleOperator Role = "operator"
	RoleViewer   Role = "viewer"
	RoleService  Role = "service"
)

func (Role) AtLeast

func (r Role) AtLeast(required Role) bool

AtLeast returns true if this role has at least the required level

type Session

type Session struct {
	ID           string
	UserID       string
	User         *User
	CreatedAt    time.Time
	ExpiresAt    time.Time
	LastActivity time.Time
	IPAddress    string
	UserAgent    string
	Active       bool
}

Session represents an authenticated session

func (*Session) IsExpired

func (s *Session) IsExpired() bool

IsExpired checks if the session has expired. IsExpired checks if the session has expired.

func (*Session) IsValid

func (s *Session) IsValid() bool

IsValid checks if the session is valid and not expired. IsValid checks if the session is valid and not expired.

func (*Session) Refresh

func (s *Session) Refresh(duration time.Duration)

Refresh updates the session expiration time. Refresh updates the session expiration time.

type User

type User struct {
	ID            string
	Email         string
	Name          string
	Provider      Provider
	ProviderID    string
	Role          Role
	Permissions   []Permission
	Attributes    map[string]interface{}
	SessionID     string
	Authenticated bool
	LastLogin     time.Time
	CreatedAt     time.Time
}

User represents an authenticated user

func (*User) HasPermission

func (u *User) HasPermission(perm Permission) bool

HasPermission checks if the user has a specific permission. HasPermission checks if the user has a specific permission.

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin returns true if user has admin role. IsAdmin returns true if user has admin role.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL