auth

package
v0.0.0-...-53b5d8b Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	UserContextKey contextKey = "user"
)

Variables

View Source
var (
	ErrUserNotFound       = errors.New("user not found")
	ErrInvalidCredentials = errors.New("invalid credentials")
	ErrUserExists         = errors.New("user already exists")
	ErrInvalidToken       = errors.New("invalid or expired token")
	ErrTOTPRequired       = errors.New("2FA code required")
	ErrInvalidTOTPCode    = errors.New("invalid 2FA code")
)

Functions

func GenerateBackupCodes

func GenerateBackupCodes() ([]string, error)

GenerateBackupCodes generates a set of one-time use backup codes

func GenerateTOTPSecret

func GenerateTOTPSecret(username string, config *TOTPConfig) (*otp.Key, error)

GenerateTOTPSecret generates a new TOTP secret for a user

func GetTOTPQRCode

func GetTOTPQRCode(key *otp.Key) string

GetTOTPQRCode returns a QR code URL for the TOTP secret

func RequireRole

func RequireRole(roles ...Role) func(http.Handler) http.Handler

RequireRole creates middleware that checks if the authenticated user has the required role

Types

type AuthHandler

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

Update AuthHandler to include UserService

func NewAuthHandler

func NewAuthHandler(store UserStore, tokenMgr *TokenManager, cfg *config.Config, emailSvc EmailService) *AuthHandler

Update constructor

func (*AuthHandler) Disable2FA

func (h *AuthHandler) Disable2FA(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) GitHubCallback

func (h *AuthHandler) GitHubCallback(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) GitHubLogin

func (h *AuthHandler) GitHubLogin(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) InitiatePasswordReset

func (h *AuthHandler) InitiatePasswordReset(w http.ResponseWriter, r *http.Request)

Add new handler methods

func (*AuthHandler) Login

func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Register

func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) RegisterRoutes

func (h *AuthHandler) RegisterRoutes(mux *http.ServeMux)

Update RegisterRoutes to include new endpoints

func (*AuthHandler) ResetPassword

func (h *AuthHandler) ResetPassword(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Setup2FA

func (h *AuthHandler) Setup2FA(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Verify2FA

func (h *AuthHandler) Verify2FA(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Verify2FALogin

func (h *AuthHandler) Verify2FALogin(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) VerifyEmail

func (h *AuthHandler) VerifyEmail(w http.ResponseWriter, r *http.Request)

type EmailService

type EmailService interface {
	SendVerificationEmail(to, token string) error
	SendPasswordResetEmail(to, token string) error
}

type FileUserStore

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

func NewFileUserStore

func NewFileUserStore(path string) (*FileUserStore, error)

func (*FileUserStore) Authenticate

func (s *FileUserStore) Authenticate(username, password string) (*User, error)

func (*FileUserStore) CreateUser

func (s *FileUserStore) CreateUser(username, password string, role Role) error

func (*FileUserStore) DeleteUser

func (s *FileUserStore) DeleteUser(username string) error

func (*FileUserStore) GetUser

func (s *FileUserStore) GetUser(username string) (*User, error)

func (*FileUserStore) GetUserByEmail

func (s *FileUserStore) GetUserByEmail(email string) (*User, error)

func (*FileUserStore) ListUsers

func (s *FileUserStore) ListUsers() ([]*User, error)

func (*FileUserStore) UpdateUser

func (s *FileUserStore) UpdateUser(user *User) error

type GitCredentials

type GitCredentials struct {
	AccessToken   string               `json:"-"` // GitHub access token
	Username      string               `json:"username"`
	Organizations []GitHubOrganization `json:"organizations,omitempty"`
	Teams         []GitHubTeam         `json:"teams,omitempty"`
}

GitCredentials stores Git-specific credentials and org memberships

type GitHubOAuth

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

func NewGitHubOAuth

func NewGitHubOAuth(clientID, clientSecret, callbackURL string, store UserStore, tokenMgr *TokenManager) *GitHubOAuth

func (*GitHubOAuth) HandleCallback

func (gh *GitHubOAuth) HandleCallback(w http.ResponseWriter, r *http.Request)

func (*GitHubOAuth) HandleCode

func (gh *GitHubOAuth) HandleCode(code string) (*User, error)

func (*GitHubOAuth) HandleLogin

func (gh *GitHubOAuth) HandleLogin(w http.ResponseWriter, r *http.Request)

type GitHubOrganization

type GitHubOrganization struct {
	Name  string `json:"name"`
	Login string `json:"login"`
}

type GitHubTeam

type GitHubTeam struct {
	Name string `json:"name"`
	Slug string `json:"slug"`
}

type NoopEmailService

type NoopEmailService struct{}

NoopEmailService is a no-op implementation of EmailService that doesn't actually send emails

func NewNoopEmailService

func NewNoopEmailService() *NoopEmailService

func (*NoopEmailService) SendPasswordResetEmail

func (s *NoopEmailService) SendPasswordResetEmail(to, token string) error

func (*NoopEmailService) SendVerificationEmail

func (s *NoopEmailService) SendVerificationEmail(to, token string) error

type PermissionStore

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

func NewPermissionStore

func NewPermissionStore(repoDir string, checker *RepoPermissionChecker) (*PermissionStore, error)

func (*PermissionStore) CheckAccess

func (s *PermissionStore) CheckAccess(user *User) (bool, error)

func (*PermissionStore) RefreshFromGitHub

func (s *PermissionStore) RefreshFromGitHub(user *User) error

type RateLimiter

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

func NewRateLimiter

func NewRateLimiter(maxAttempts int, windowDuration, lockoutDuration time.Duration) *RateLimiter

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware(next http.Handler) http.Handler

type RepoPermissionChecker

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

RepoPermissionChecker validates repository access permissions

func NewRepoPermissionChecker

func NewRepoPermissionChecker(store UserStore) *RepoPermissionChecker

func (*RepoPermissionChecker) HasRepoAccess

func (pc *RepoPermissionChecker) HasRepoAccess(user *User, owner, repo string) error

HasRepoAccess checks if a user has access to a specific repository

func (*RepoPermissionChecker) RequireRepoAccess

func (pc *RepoPermissionChecker) RequireRepoAccess(owner, repo string) func(http.Handler) http.Handler

RequireRepoAccess creates middleware that checks if the user has access to the repository

type RepoPermissions

type RepoPermissions struct {
	OrganizationName string            `json:"org_name"`
	RepositoryName   string            `json:"repo_name"`
	TeamAccess       map[string]string `json:"team_access"` // team -> access level
	UserAccess       map[string]string `json:"user_access"` // username -> access level
	LastUpdated      time.Time         `json:"last_updated"`
}

type Role

type Role string
const (
	RoleAdmin  Role = "admin"
	RoleMember Role = "member"
	RoleGuest  Role = "guest"
)

type TOTPConfig

type TOTPConfig struct {
	Issuer string
	Period uint
	Digits otp.Digits
}

TOTPConfig holds configuration for generating TOTP secrets

func NewDefaultTOTPConfig

func NewDefaultTOTPConfig(issuer string) *TOTPConfig

NewDefaultTOTPConfig creates a default TOTP configuration

type TokenManager

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

func NewTokenManager

func NewTokenManager(secretKey string, store UserStore) *TokenManager

func (*TokenManager) AuthMiddleware

func (tm *TokenManager) AuthMiddleware(next http.Handler) http.Handler

AuthMiddleware creates a middleware that validates JWT tokens

func (*TokenManager) GenerateTokenPair

func (tm *TokenManager) GenerateTokenPair(user *User) (*TokenPair, error)

func (*TokenManager) IsTokenRevoked

func (tm *TokenManager) IsTokenRevoked(tokenString string) bool

func (*TokenManager) RefreshToken

func (tm *TokenManager) RefreshToken(refreshToken string) (*TokenPair, error)

func (*TokenManager) RevokeToken

func (tm *TokenManager) RevokeToken(tokenString string)

func (*TokenManager) ValidateToken

func (tm *TokenManager) ValidateToken(tokenString string) (*User, error)

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
}

type User

type User struct {
	Username          string          `json:"username"`
	Password          []byte          `json:"-"`
	Email             string          `json:"email"`
	EmailVerified     bool            `json:"email_verified"`
	VerificationToken string          `json:"-"`
	ResetToken        string          `json:"-"`
	ResetTokenExpiry  time.Time       `json:"-"`
	Role              Role            `json:"role"`
	CreatedAt         time.Time       `json:"created_at"`
	LastLoginAt       time.Time       `json:"last_login_at"`
	Git               *GitCredentials `json:"git,omitempty"`
	AuthType          string          `json:"auth_type"`
	FailedAttempts    int             `json:"-"`
	LockedUntil       time.Time       `json:"-"`
	TOTPEnabled       bool            `json:"totp_enabled"`
	TOTPSecret        string          `json:"-"`
	TOTPBackupCodes   []string        `json:"-"`
}

func NewUser

func NewUser(username, password string, role Role) (*User, error)

NewUser creates a new user with a hashed password

func (*User) HasGitHubOrg

func (u *User) HasGitHubOrg(orgName string) bool

HasGitHubOrg checks if the user is a member of the specified GitHub organization

func (*User) HasGitHubTeam

func (u *User) HasGitHubTeam(orgName, teamSlug string) bool

HasGitHubTeam checks if the user is a member of the specified GitHub team

func (*User) IncrementFailedAttempts

func (u *User) IncrementFailedAttempts()

IncrementFailedAttempts increases the failed login attempts counter and locks the account if necessary

func (*User) IsAccountLocked

func (u *User) IsAccountLocked() bool

IsAccountLocked checks if the account is temporarily locked due to too many failed attempts

func (*User) IsEmailVerificationPending

func (u *User) IsEmailVerificationPending() bool

IsEmailVerificationPending returns true if email verification is pending

func (*User) IsGitHubUser

func (u *User) IsGitHubUser() bool

IsGitHubUser returns true if the user was authenticated via GitHub

func (*User) IsPasswordResetTokenValid

func (u *User) IsPasswordResetTokenValid(token string) bool

IsPasswordResetTokenValid checks if the password reset token is valid and not expired

func (*User) IsTOTPRequired

func (u *User) IsTOTPRequired() bool

IsTOTPRequired returns true if 2FA is enabled and required

func (*User) ResetFailedAttempts

func (u *User) ResetFailedAttempts()

ResetFailedAttempts resets the failed attempts counter after successful login

func (*User) ValidatePassword

func (u *User) ValidatePassword(password string) bool

ValidatePassword checks if the provided password matches the stored hash

func (*User) ValidateTOTPCode

func (u *User) ValidateTOTPCode(code string) bool

ValidateTOTPCode checks if the provided TOTP code is valid

type UserService

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

func NewUserService

func NewUserService(store UserStore, emailService EmailService) *UserService

func (*UserService) InitiateEmailVerification

func (s *UserService) InitiateEmailVerification(user *User) error

func (*UserService) InitiatePasswordReset

func (s *UserService) InitiatePasswordReset(email string) error

func (*UserService) ResetPassword

func (s *UserService) ResetPassword(username, token, newPassword string) error

func (*UserService) VerifyEmail

func (s *UserService) VerifyEmail(username, token string) error

type UserStore

type UserStore interface {
	CreateUser(username string, password string, role Role) error
	GetUser(username string) (*User, error)
	GetUserByEmail(email string) (*User, error)
	UpdateUser(user *User) error
	DeleteUser(username string) error
	ListUsers() ([]*User, error)
	Authenticate(username, password string) (*User, error)
}

Jump to

Keyboard shortcuts

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