example_auth

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 7 Imported by: 0

README

Auth Package Examples

This directory contains examples demonstrating how to use the auth package, which provides authentication and authorization utilities for Go applications. The package offers functionality for JWT token handling, middleware integration, user information retrieval, and authorization checks.

Examples

1. Quickstart Example

quickstart_example.go

Demonstrates the basic setup and usage of the auth package.

Key concepts:

  • Creating an auth configuration
  • Initializing an auth instance
  • Using auth middleware for HTTP handlers
  • Checking if a user is authorized to perform an operation
  • Getting a user ID from the context
2. Auth Instance Example

auth_instance_example.go

Shows how to create and configure an auth instance.

Key concepts:

  • Creating an auth instance with custom configuration
  • Handling initialization errors
  • Auth instance lifecycle management
3. Authorization Example

authorization_example.go

Demonstrates how to perform authorization checks.

Key concepts:

  • Checking permissions and roles
  • Role-based access control
  • Permission-based authorization
  • Handling authorization errors
4. Configuration Example

configuration_example.go

Shows how to configure the auth package.

Key concepts:

  • Setting up JWT configuration
  • Configuring token validation parameters
  • Setting up OIDC integration
  • Using default and custom configurations
5. Context Utilities Example

context_utilities_example.go

Demonstrates working with auth-related information in context.

Key concepts:

  • Adding auth information to context
  • Retrieving auth information from context
  • Context propagation with auth data
6. Error Handling Example

error_handling_example.go

Shows how to handle various auth-related errors.

Key concepts:

  • Handling token validation errors
  • Dealing with authorization failures
  • Graceful error recovery
  • Error types and classification
7. Middleware Example

middleware_example.go

Demonstrates how to use auth middleware with HTTP servers.

Key concepts:

  • Integrating auth middleware with HTTP handlers
  • Protecting routes with authentication
  • Customizing middleware behavior
8. Token Handling Example

token_handling_example.go

Shows how to work with JWT tokens.

Key concepts:

  • Generating JWT tokens
  • Validating tokens
  • Extracting claims from tokens
  • Token refresh strategies
9. User Info Example

user_info_example.go

Demonstrates how to work with user information.

Key concepts:

  • Retrieving user details
  • Working with user profiles
  • Handling user-related operations

Running the Examples

To run any of the examples, use the go run command:

go run examples/auth/quickstart_example.go

Additional Resources

For more information about the auth package, see the auth package documentation.

Documentation

Overview

Example usage of creating an Auth instance

Example demonstrating authorization concepts

Example usage of the Auth module configuration

Example demonstrating context utilities for authentication

Example demonstrating error handling in the auth module

Example usage of the Auth middleware

Example usage of the Auth module for a quick start

Example demonstrating the concept of token handling in authentication

Example demonstrating how to get user information from the context

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidToken     = errors.New("invalid token")
	ErrTokenExpired     = errors.New("token expired")
	ErrInvalidSignature = errors.New("invalid signature")
	ErrMissingClaims    = errors.New("missing claims")
)

Define error types

Functions

func AddUserIDToContext

func AddUserIDToContext(ctx context.Context, userID string) context.Context

AddUserIDToContext adds a user ID to the context

func AddUserIDToCtx

func AddUserIDToCtx(ctx context.Context, userID string) context.Context

AddUserIDToCtx adds a user ID to the context

func AddUserRolesToCtx

func AddUserRolesToCtx(ctx context.Context, roles []string) context.Context

AddUserRolesToCtx adds user roles to the context

func GetContext

func GetContext(err error, key string) (string, bool)

GetContext gets context information from an error

func GetMessage

func GetMessage(err error) (string, bool)

GetMessage gets the error message

func GetOp

func GetOp(err error) (string, bool)

GetOp gets the operation that caused the error

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) (string, bool)

GetUserIDFromContext gets the user ID from the context

func GetUserIDFromCtx

func GetUserIDFromCtx(ctx context.Context) (string, bool)

GetUserIDFromCtx gets the user ID from the context

func GetUserRolesFromCtx

func GetUserRolesFromCtx(ctx context.Context) ([]string, bool)

GetUserRolesFromCtx gets the user roles from the context

func IsUserAuthenticated

func IsUserAuthenticated(ctx context.Context) bool

IsUserAuthenticated checks if the user is authenticated

func SimulateTokenValidation

func SimulateTokenValidation(token string) error

SimulateTokenValidation simulates token validation with error handling

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds a user ID to the context

Types

type AuthService

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

AuthService simulates an auth service with authorization capabilities

func NewAuthService

func NewAuthService() *AuthService

NewAuthService creates a new auth service

func (*AuthService) HasRole

func (a *AuthService) HasRole(ctx context.Context, role string) (bool, error)

HasRole checks if the user has a specific role

func (*AuthService) IsAdmin

func (a *AuthService) IsAdmin(ctx context.Context) (bool, error)

IsAdmin checks if the user has admin role

func (*AuthService) IsAuthorized

func (a *AuthService) IsAuthorized(ctx context.Context, operation string) (bool, error)

IsAuthorized checks if the user is authorized to perform an operation

type ContextError

type ContextError struct {
	Op      string            // Operation that caused the error
	Err     error             // Original error
	Message string            // Human-readable error message
	Context map[string]string // Additional context information
}

ContextError represents an error with context information

func NewError

func NewError(op string, err error, message string) *ContextError

NewError creates a new context error

func (*ContextError) Error

func (e *ContextError) Error() string

Error implements the error interface

func (*ContextError) Unwrap

func (e *ContextError) Unwrap() error

Unwrap returns the wrapped error

func (*ContextError) WithContext

func (e *ContextError) WithContext(key, value string) *ContextError

WithContext adds context information to the error

type ContextKey

type ContextKey string

ContextKey is a type for context keys to avoid collisions

const (
	UserIDKey    ContextKey = "userID"
	UserRolesKey ContextKey = "userRoles"
)

Context keys

type MockAuth

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

MockAuth simulates an auth service

func NewMockAuth

func NewMockAuth(secretKey, issuer string) *MockAuth

NewMockAuth creates a new mock auth service

func (*MockAuth) GenerateToken

func (a *MockAuth) GenerateToken(userID string, roles []string) string

GenerateToken creates a mock token

func (*MockAuth) ValidateToken

func (a *MockAuth) ValidateToken(token string) (*MockClaims, error)

ValidateToken validates a mock token and returns claims

type MockClaims

type MockClaims struct {
	Subject   string
	Roles     []string
	Issuer    string
	ExpiresAt time.Time
}

MockClaims represents the data stored in a JWT token

type UserInfo

type UserInfo struct {
	ID    string
	Roles []string
	Email string
}

UserInfo represents user information

type UserInfoService

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

UserInfoService simulates a user information service

func NewUserInfoService

func NewUserInfoService() *UserInfoService

NewUserInfoService creates a new user information service

func (*UserInfoService) GetUserEmail

func (a *UserInfoService) GetUserEmail(ctx context.Context) (string, error)

GetUserEmail gets the user email from the context

func (*UserInfoService) GetUserID

func (a *UserInfoService) GetUserID(ctx context.Context) (string, error)

GetUserID gets the user ID from the context

func (*UserInfoService) GetUserRoles

func (a *UserInfoService) GetUserRoles(ctx context.Context) ([]string, error)

GetUserRoles gets the user roles from the context

Jump to

Keyboard shortcuts

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