auth

package
v0.0.0-...-70a5fc5 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: GPL-3.0 Imports: 19 Imported by: 0

README

Bakend Auth System

Bu paket, HTTP'den bağımsız, esnek, güvenli ve production-ready bir authentication/authorization sistemi sağlar.

Özellikler

  • HTTP'den Bağımsız: Pure Go context tabanlı auth sistemi.
  • Flexible Token Providers: Simple HMAC ve JWT token desteği.
  • Session Management:
    • Redis Session Store: Production için ölçeklenebilir session yönetimi.
    • Memory Session Store: Test ve geliştirme için.
  • Permission/Role System:
    • Database Permission Provider: Veritabanı tabanlı dinamik yetki yönetimi (Caching destekli).
    • Static Permission Provider: Test ve basit senaryolar için.
  • Security:
    • Refresh Token Rotation: Token çalınmasına karşı ekstra güvenlik.
    • Secure Defaults: Güvenli varsayılan konfigürasyonlar.
  • Middleware Support: Type-safe handler wrapper'ları ve HTTP middleware entegrasyonu.
  • Config Integration: Merkezi konfigürasyon yönetimi.
  • Elastic APM Integration: Detaylı tracing ve monitoring.

Kurulum ve Konfigürasyon

1. Auth Config

Auth sistemi, merkezi bir AuthConfig yapısı ile yönetilir.

package main

import (
    "github.com/Deepreo/bakend/modules/auth"
    "time"
)

func main() {
    // Varsayılan konfigürasyon
    config := auth.DefaultAuthConfig()
    
    // Özelleştirme
    config.UseJWT = true
    config.JWT.SecretKey = "your-very-secure-secret-key-min-32-chars"
    config.JWT.AccessTokenExpiration = 15 * time.Minute
    config.JWT.RefreshTokenExpiration = 7 * 24 * time.Hour
    config.JWT.Issuer = "bakend"
    
    // Redis ayarları
    config.RedisURL = "localhost:6379"
    config.RedisPrefix = "bakend:session:"
    
    // Auth sistemini oluştur
    authSystem, err := auth.NewAuthSystemWithConfig(config)
    if err != nil {
        panic(err)
    }
}
2. Provider Seçimi

Production ortamında Redis ve Database provider'larının kullanılması önerilir.

// Redis Client
redisClient := redis.NewClient(&redis.Options{Addr: config.RedisURL})

// Database Connection (pgx)
dbPool, _ := pgxpool.New(ctx, dbURL)

// Cache (Redis tabanlı)
cache := NewRedisCache(redisClient) 

// Builder ile sistem oluşturma
authSystem, err := auth.NewAuthBuilder().
    WithConfig(config).
    WithSessionStore(auth.NewRedisSessionStore(redisClient, config.RedisPrefix)).
    WithPermissionProvider(auth.NewSQLPermissionProvider(dbPool, cache)).
    Build()

Kullanım

1. Token İşlemleri
// Token oluştur (Login)
userID := uuid.New()
authCtx := auth.NewAuthContext(userID, uuid.New(), "user@example.com", "John Doe", true)
tokenPair, err := authSystem.Service.GenerateTokens(ctx, authCtx)

// Token yenileme (Refresh Token Rotation)
// Bu işlem eski session'ı iptal eder ve yeni bir session oluşturur.
newTokenPair, err := authSystem.Service.RefreshToken(ctx, tokenPair.RefreshToken)
2. Middleware Kullanımı

Handler'larınızı type-safe wrapper'lar ile koruyun.

// Handler tanımı
type CreateUserHandler struct {
    service UserService
}

func (h *CreateUserHandler) Handle(ctx context.Context, req *CreateUserRequest) (*CreateUserResponse, error) {
    // Auth context otomatik olarak ctx içinde
    authCtx, _ := auth.FromContext(ctx)
    // ...
}

// Wrapper kullanımı
handler := auth.WithAuthHandlerFromContext(
    authSystem.Service,
    &CreateUserHandler{},
    &auth.AuthRequiredOptions{
        RequireVerification: true,
        RequiredPermissions: []string{"user.create"},
        RequiredRoles:       []string{"admin"},
    },
)
3. Permission Kontrolü
// Context üzerinden kontrol
if err := auth.RequirePermission(ctx, "document.edit"); err != nil {
    return err // ErrPermissionDenied
}

// AuthContext üzerinden kontrol
authCtx, _ := auth.FromContext(ctx)
if authCtx.HasRole("manager") {
    // ...
}

Veritabanı Şeması (SQLPermissionProvider)

SQLPermissionProvider aşağıdaki tablo yapısını bekler:

CREATE TABLE roles (
    id UUID PRIMARY KEY,
    name VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE permissions (
    id UUID PRIMARY KEY,
    name VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE user_roles (
    user_id UUID NOT NULL,
    role_id UUID NOT NULL REFERENCES roles(id),
    PRIMARY KEY (user_id, role_id)
);

CREATE TABLE role_permissions (
    role_id UUID NOT NULL REFERENCES roles(id),
    permission_id UUID NOT NULL REFERENCES permissions(id),
    PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE user_permissions (
    user_id UUID NOT NULL,
    permission_id UUID NOT NULL REFERENCES permissions(id),
    PRIMARY KEY (user_id, permission_id)
);

Güvenlik Özellikleri

Refresh Token Rotation

Bir refresh token kullanıldığında, o token'a bağlı olan session iptal edilir (revoke) ve yeni bir session oluşturulur. Bu, çalınan refresh token'ların tekrar kullanılmasını engeller ve "token reuse" saldırılarını tespit etmeyi sağlar.

Caching

SQLPermissionProvider, performans için yetkileri cache'ler. CacheInterface implementasyonu sağlanarak (örn. Redis) veritabanı yükü azaltılır. Cache süresi varsayılan olarak 5 dakikadır.

Test

Modül kapsamlı unit testlere sahiptir.

go test -v ./modules/auth/...

Testler için NewTestAuthSystem helper'ı kullanılabilir. Bu helper, in-memory bileşenleri kullanarak hızlı test ortamı sağlar.

Documentation

Index

Constants

View Source
const (
	AuthContextKey contextKey = "auth_context"
	AuthTokenKey   contextKey = "auth_token"
)
View Source
const (
	SpanAuthTokenValidation   = "auth.token.validation"
	SpanAuthPermissionCheck   = "auth.permission.check"
	SpanAuthRoleCheck         = "auth.role.check"
	SpanAuthVerificationCheck = "auth.verification.check"
	SpanAuthContextCreation   = "auth.context.creation"
	SpanAuthHandlerWrapper    = "auth.handler.wrapper"
	SpanAuthOptionalWrapper   = "auth.optional.wrapper"
)

APM Span names

Variables

View Source
var (
	ErrAuthContextNotFound = errors.New("auth context not found")
	ErrInvalidAuthContext  = errors.AuthError(errors.New("invalid auth context"))
	ErrTokenExpired        = errors.AuthError(errors.New("token expired"))
	ErrPermissionDenied    = errors.PermissionError(errors.New("permission denied"))
	ErrRoleNotFound        = errors.PermissionError(errors.New("role not found"))
	ErrUserNotVerified     = errors.PermissionError(errors.New("user email not verified"))
	ErrInvalidTokenType    = errors.AuthError(errors.New("invalid token type"))
)

Functions

func CreateBearerToken

func CreateBearerToken(token string) string

CreateBearerToken, token'ı "Bearer token" formatına çevirir

func ExampleAuthenticatedHandler

func ExampleAuthenticatedHandler()

ExampleAuthenticatedHandler, authentication decorator kullanım örneği

func ExampleBusinessLogic

func ExampleBusinessLogic()

ExampleBusinessLogic, business logic'te auth context kullanım örneği

func ExampleConfigUsage

func ExampleConfigUsage()

ExampleConfigUsage, konfigürasyon kullanım örneği

func ExampleMiddlewareIntegration

func ExampleMiddlewareIntegration()

ExampleMiddlewareIntegration, middleware entegrasyon örneği

func ExamplePermissionGuard

func ExamplePermissionGuard()

ExamplePermissionGuard, permission guard kullanım örneği

func ExampleUsage

func ExampleUsage()

ExampleUsage, auth sisteminin temel kullanım örneği

func ExtractTokenFromBearer

func ExtractTokenFromBearer(bearerToken string) string

ExtractTokenFromBearer, "Bearer token" formatından token'ı çıkarır

func GetCompanyID

func GetCompanyID(ctx context.Context) (uuid.UUID, error)

GetCompanyID, context'ten company ID'yi alır

func GetTokenFromContext

func GetTokenFromContext(ctx context.Context) string

GetTokenFromContext, context'ten token'ı çıkarır

func GetUserID

func GetUserID(ctx context.Context) (uuid.UUID, error)

GetUserID, context'ten user ID'yi alır

func HasPermissionInContext

func HasPermissionInContext(ctx context.Context, permission string) bool

HasPermissionInContext, context'teki kullanıcının belirtilen permission'a sahip olup olmadığını kontrol eder

func HasRoleInContext

func HasRoleInContext(ctx context.Context, role string) bool

HasRoleInContext, context'teki kullanıcının belirtilen role'e sahip olup olmadığını kontrol eder

func StartAuthSpan

func StartAuthSpan(ctx context.Context, name, spanType string) (*apm.Span, context.Context)

StartAuthSpan, auth işlemleri için APM span başlatır

func StartAuthSpanWithOperation

func StartAuthSpanWithOperation(ctx context.Context, operation, spanType string) (*apm.Span, context.Context)

StartAuthSpanWithOperation, operation bilgisi ile auth span başlatır

func TraceAuthOperation

func TraceAuthOperation(ctx context.Context, operation string, fn func(context.Context) error) error

TraceAuthOperation, auth işlemini APM ile trace eder

func TraceAuthOperationWithResult

func TraceAuthOperationWithResult[T any](ctx context.Context, operation string, fn func(context.Context) (T, error)) (T, error)

TraceAuthOperationWithResult, sonuçlu auth işlemini APM ile trace eder

func WithAuthContext

func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context

WithAuthContext, context'e AuthContext ekler

func WithAuthHandler

func WithAuthHandler[R core.Request, Res core.Response](
	authService AuthService,
	handler core.HandlerInterface[R, Res],
	tokenExtractor func(R) string,
	options *AuthRequiredOptions,
) core.HandlerInterface[R, Res]

WithAuthHandler, jenerik handler'ları authentication ile sarar

func WithAuthHandlerFromContext

func WithAuthHandlerFromContext[R core.Request, Res core.Response](
	authService AuthService,
	handler core.HandlerInterface[R, Res],
	options *AuthRequiredOptions,
) core.HandlerInterface[R, Res]

WithAuthHandlerFromContext, context'ten token çıkararak handler'ları authentication ile sarar

func WithOptionalAuthHandler

func WithOptionalAuthHandler[R core.Request, Res core.Response](
	authService AuthService,
	handler core.HandlerInterface[R, Res],
	tokenExtractor func(R) string,
) core.HandlerInterface[R, Res]

WithOptionalAuthHandler, jenerik handler'ları opsiyonel authentication ile sarar

func WithOptionalAuthHandlerFromContext

func WithOptionalAuthHandlerFromContext[R core.Request, Res core.Response](
	authService AuthService,
	handler core.HandlerInterface[R, Res],
) core.HandlerInterface[R, Res]

WithOptionalAuthHandlerFromContext, context'ten token çıkararak handler'ları opsiyonel authentication ile sarar

func WithToken

func WithToken(ctx context.Context, token string) context.Context

WithToken, context'e token ekler

Types

type AuthBuilder

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

AuthBuilder, auth sistemi oluşturucu

func NewAuthBuilder

func NewAuthBuilder() *AuthBuilder

NewAuthBuilder, yeni auth builder oluşturur

func (*AuthBuilder) Build

func (b *AuthBuilder) Build() (*AuthSystem, error)

Build, auth sistemini oluşturur

func (*AuthBuilder) WithConfig

func (b *AuthBuilder) WithConfig(config *AuthConfig) *AuthBuilder

WithConfig, builder'a config ekler

func (*AuthBuilder) WithPermissionProvider

func (b *AuthBuilder) WithPermissionProvider(provider PermissionProvider) *AuthBuilder

WithPermissionProvider, custom permission provider ekler

func (*AuthBuilder) WithSessionStore

func (b *AuthBuilder) WithSessionStore(store SessionStore) *AuthBuilder

WithSessionStore, custom session store ekler

func (*AuthBuilder) WithTokenProvider

func (b *AuthBuilder) WithTokenProvider(provider TokenProvider) *AuthBuilder

WithTokenProvider, custom token provider ekler

type AuthConfig

type AuthConfig struct {
	Token   *SimpleTokenConfig `mapstructure:"token" json:"token"`
	JWT     *JWTConfig         `mapstructure:"jwt" json:"jwt"`
	Session *SessionConfig     `mapstructure:"session" json:"session"`
	Enabled bool               `mapstructure:"enabled" json:"enabled"`
	UseJWT  bool               `mapstructure:"use_jwt" json:"use_jwt"`
}

AuthConfig, auth sistemi konfigürasyonu

func DefaultAuthConfig

func DefaultAuthConfig() *AuthConfig

DefaultAuthConfig, varsayılan auth konfigürasyonu

func (*AuthConfig) Validate

func (c *AuthConfig) Validate() error

Validate, auth konfigürasyonunu doğrular

type AuthContext

type AuthContext struct {
	UserID      uuid.UUID `json:"user_id"`
	Email       string    `json:"email"`
	CompanyID   uuid.UUID `json:"company_id"`
	FullName    string    `json:"full_name"`
	IsVerified  bool      `json:"is_verified"`
	Permissions []string  `json:"permissions"`
	Roles       []string  `json:"roles"`
	TokenType   string    `json:"token_type"` // "access" veya "refresh"
	IssuedAt    time.Time `json:"issued_at"`
	ExpiresAt   time.Time `json:"expires_at"`
	SessionID   string    `json:"session_id"`
}

AuthContext, authentication ve authorization bilgilerini taşır

func FromContext

func FromContext(ctx context.Context) (*AuthContext, error)

FromContext, context'ten AuthContext'i alır

func MustFromContext

func MustFromContext(ctx context.Context) *AuthContext

MustFromContext, context'ten AuthContext'i alır, bulamazsa panic yapar

func NewAuthContext

func NewAuthContext(userID, companyID uuid.UUID, email, fullName string, isVerified bool) *AuthContext

NewAuthContext, yeni bir AuthContext oluşturur

func RequireAuth

func RequireAuth(ctx context.Context) (*AuthContext, error)

RequireAuth, basit authentication kontrolü yapar

func RequirePermission

func RequirePermission(ctx context.Context, permission string) (*AuthContext, error)

RequirePermission, belirtilen permission gereksinimini kontrol eder

func RequireRole

func RequireRole(ctx context.Context, role string) (*AuthContext, error)

RequireRole, belirtilen role gereksinimini kontrol eder

func RequireVerifiedUser

func RequireVerifiedUser(ctx context.Context) (*AuthContext, error)

RequireVerifiedUser, doğrulanmış kullanıcı gereksinimi kontrol eder

func (*AuthContext) Clone

func (ac *AuthContext) Clone() *AuthContext

Clone, AuthContext'in bir kopyasını oluşturur

func (*AuthContext) HasAllPermissions

func (ac *AuthContext) HasAllPermissions(permissions ...string) bool

HasAllPermissions, belirtilen tüm permission'lara sahip mi kontrol eder

func (*AuthContext) HasAnyPermission

func (ac *AuthContext) HasAnyPermission(permissions ...string) bool

HasAnyPermission, belirtilen permission'lardan herhangi birine sahip mi kontrol eder

func (*AuthContext) HasAnyRole

func (ac *AuthContext) HasAnyRole(roles ...string) bool

HasAnyRole, belirtilen role'lerden herhangi birine sahip mi kontrol eder

func (*AuthContext) HasPermission

func (ac *AuthContext) HasPermission(permission string) bool

HasPermission, belirtilen permission'a sahip mi kontrol eder

func (*AuthContext) HasRole

func (ac *AuthContext) HasRole(role string) bool

HasRole, belirtilen role'e sahip mi kontrol eder

func (*AuthContext) IsAccessToken

func (ac *AuthContext) IsAccessToken() bool

IsAccessToken, access token mi kontrol eder

func (*AuthContext) IsExpired

func (ac *AuthContext) IsExpired() bool

IsExpired, token'ın süresi bitmiş mi kontrol eder

func (*AuthContext) IsRefreshToken

func (ac *AuthContext) IsRefreshToken() bool

IsRefreshToken, refresh token mi kontrol eder

func (*AuthContext) RequireAccessToken

func (ac *AuthContext) RequireAccessToken() error

RequireAccessToken, access token olmasını gerektirir

func (*AuthContext) RequireAnyPermission

func (ac *AuthContext) RequireAnyPermission(permissions ...string) error

RequireAnyPermission, belirtilen permission'lardan herhangi birine sahip olunmasını gerektirir

func (*AuthContext) RequirePermission

func (ac *AuthContext) RequirePermission(permission string) error

RequirePermission, belirtilen permission'a sahip olunmasını gerektirir

func (*AuthContext) RequireRole

func (ac *AuthContext) RequireRole(role string) error

RequireRole, belirtilen role'e sahip olunmasını gerektirir

func (*AuthContext) RequireVerification

func (ac *AuthContext) RequireVerification() error

RequireVerification, kullanıcının doğrulanmış olmasını gerektirir

func (*AuthContext) Validate

func (ac *AuthContext) Validate() error

Validate, AuthContext'in geçerli olduğunu kontrol eder

func (*AuthContext) WithExpiration

func (ac *AuthContext) WithExpiration(duration time.Duration) *AuthContext

WithExpiration, token'ın bitiş süresini belirler

func (*AuthContext) WithPermissions

func (ac *AuthContext) WithPermissions(permissions ...string) *AuthContext

WithPermissions, AuthContext'e permission'lar ekler

func (*AuthContext) WithRoles

func (ac *AuthContext) WithRoles(roles ...string) *AuthContext

WithRoles, AuthContext'e roller ekler

func (*AuthContext) WithSessionID

func (ac *AuthContext) WithSessionID(sessionID string) *AuthContext

WithSessionID, session ID'sini belirler

func (*AuthContext) WithTokenType

func (ac *AuthContext) WithTokenType(tokenType string) *AuthContext

WithTokenType, token tipini belirler

type AuthDecorator

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

AuthDecorator, fonksiyonları authentication ile sarar

func NewAuthDecorator

func NewAuthDecorator(authService AuthService) *AuthDecorator

NewAuthDecorator, yeni bir AuthDecorator oluşturur

func (*AuthDecorator) WithAuth

func (d *AuthDecorator) WithAuth(
	handler AuthenticatedHandler,
	tokenExtractor func(interface{}) string,
	options *AuthRequiredOptions,
) AuthenticatedHandler

WithAuth, handler'ı authentication ile sarar

func (*AuthDecorator) WithOptionalAuth

func (d *AuthDecorator) WithOptionalAuth(
	handler AuthenticatedHandler,
	tokenExtractor func(interface{}) string,
) AuthenticatedHandler

WithOptionalAuth, handler'ı opsiyonel authentication ile sarar

type AuthMiddleware

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

AuthMiddleware, authentication işlemlerini yönetir

func NewAuthMiddleware

func NewAuthMiddleware(authService AuthService) *AuthMiddleware

NewAuthMiddleware, yeni bir AuthMiddleware oluşturur

func (*AuthMiddleware) WithAuthRequired

func (m *AuthMiddleware) WithAuthRequired(ctx context.Context, token string, options *AuthRequiredOptions) (context.Context, error)

WithAuthRequired, context'e authentication gereksinimlerini ekler

func (*AuthMiddleware) WithOptionalAuth

func (m *AuthMiddleware) WithOptionalAuth(ctx context.Context, token string) context.Context

WithOptionalAuth, opsiyonel authentication işlemi yapar

type AuthRequiredOptions

type AuthRequiredOptions struct {
	RequireVerification bool
	RequiredPermissions []string
	RequiredRoles       []string
	TokenType           string // "access" veya "refresh", boşsa "access" varsayılır
}

AuthRequiredOptions, authentication gereksinimlerini tanımlar

type AuthService

type AuthService interface {
	// Token işlemleri
	GenerateTokens(ctx context.Context, authCtx *AuthContext) (*TokenPair, error)
	ValidateToken(ctx context.Context, token, tokenType string) (*AuthContext, error)
	RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error)
	RevokeToken(ctx context.Context, token string) error

	// Session işlemleri
	CreateSession(ctx context.Context, authCtx *AuthContext) error
	GetSession(ctx context.Context, sessionID string) (*AuthContext, error)
	UpdateSession(ctx context.Context, sessionID string, authCtx *AuthContext) error
	RevokeSession(ctx context.Context, sessionID string) error
	RevokeAllSessions(ctx context.Context, userID uuid.UUID) error

	// Permission işlemleri
	GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error)
	GetUserRoles(ctx context.Context, userID uuid.UUID) ([]string, error)
	HasPermission(ctx context.Context, userID uuid.UUID, permission string) (bool, error)
	HasRole(ctx context.Context, userID uuid.UUID, role string) (bool, error)
}

AuthService, authentication işlemlerini yönetir

func NewAuthService

func NewAuthService(
	tokenProvider TokenProvider,
	sessionStore SessionStore,
	permissionProvider PermissionProvider,
) AuthService

NewAuthService, yeni bir AuthService oluşturur

type AuthServiceImpl

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

AuthServiceImpl, AuthService'in varsayılan implementasyonu

func (*AuthServiceImpl) CreateSession

func (s *AuthServiceImpl) CreateSession(ctx context.Context, authCtx *AuthContext) error

CreateSession, yeni session oluşturur

func (*AuthServiceImpl) GenerateTokens

func (s *AuthServiceImpl) GenerateTokens(ctx context.Context, authCtx *AuthContext) (*TokenPair, error)

GenerateTokens, AuthContext için access ve refresh token oluşturur

func (*AuthServiceImpl) GetSession

func (s *AuthServiceImpl) GetSession(ctx context.Context, sessionID string) (*AuthContext, error)

GetSession, session'ı getirir

func (*AuthServiceImpl) GetUserPermissions

func (s *AuthServiceImpl) GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserPermissions, kullanıcının permission'larını getirir

func (*AuthServiceImpl) GetUserRoles

func (s *AuthServiceImpl) GetUserRoles(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserRoles, kullanıcının role'lerini getirir

func (*AuthServiceImpl) HasPermission

func (s *AuthServiceImpl) HasPermission(ctx context.Context, userID uuid.UUID, permission string) (bool, error)

HasPermission, kullanıcının belirtilen permission'a sahip olup olmadığını kontrol eder

func (*AuthServiceImpl) HasRole

func (s *AuthServiceImpl) HasRole(ctx context.Context, userID uuid.UUID, role string) (bool, error)

HasRole, kullanıcının belirtilen role'e sahip olup olmadığını kontrol eder

func (*AuthServiceImpl) RefreshToken

func (s *AuthServiceImpl) RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error)

RefreshToken, refresh token kullanarak yeni token çifti oluşturur

func (*AuthServiceImpl) RevokeAllSessions

func (s *AuthServiceImpl) RevokeAllSessions(ctx context.Context, userID uuid.UUID) error

RevokeAllSessions, kullanıcının tüm session'larını iptal eder

func (*AuthServiceImpl) RevokeSession

func (s *AuthServiceImpl) RevokeSession(ctx context.Context, sessionID string) error

RevokeSession, session'ı iptal eder

func (*AuthServiceImpl) RevokeToken

func (s *AuthServiceImpl) RevokeToken(ctx context.Context, token string) error

RevokeToken, token'ı iptal eder

func (*AuthServiceImpl) UpdateSession

func (s *AuthServiceImpl) UpdateSession(ctx context.Context, sessionID string, authCtx *AuthContext) error

UpdateSession, session'ı günceller

func (*AuthServiceImpl) ValidateToken

func (s *AuthServiceImpl) ValidateToken(ctx context.Context, token string, tokenType string) (*AuthContext, error)

ValidateToken, token'ı doğrular ve AuthContext döner

type AuthSystem

type AuthSystem struct {
	Config             *AuthConfig
	Service            AuthService
	Middleware         *AuthMiddleware
	Decorator          *AuthDecorator
	PermissionGuard    *PermissionGuard
	TokenProvider      TokenProvider
	SessionStore       SessionStore
	PermissionProvider PermissionProvider
}

AuthSystem, tüm auth bileşenlerini içeren sistem

func NewAuthSystemWithConfig

func NewAuthSystemWithConfig(config *AuthConfig) (*AuthSystem, error)

NewAuthSystemWithConfig, konfigürasyon ile auth sistemi oluşturur

func NewDefaultAuthSystem

func NewDefaultAuthSystem() (*AuthSystem, error)

NewDefaultAuthSystem, varsayılan auth sistemi oluşturur

func NewDisabledAuthSystem

func NewDisabledAuthSystem() *AuthSystem

NewDisabledAuthSystem, kapalı auth sistemi oluşturur (test için)

func NewTestAuthSystem

func NewTestAuthSystem() (*AuthSystem, error)

NewTestAuthSystem, test ortamı için auth sistemi oluşturur

func NewTestAuthSystemWithJWT

func NewTestAuthSystemWithJWT() (*AuthSystem, error)

NewTestAuthSystemWithJWT, JWT ile test ortamı için auth sistemi oluşturur

func (*AuthSystem) IsEnabled

func (s *AuthSystem) IsEnabled() bool

IsEnabled, auth sisteminin aktif olup olmadığını kontrol eder

func (*AuthSystem) SetupTestUser

func (s *AuthSystem) SetupTestUser(userID string, email string, fullName string, roles []string) error

SetupTestUser, test kullanıcısı oluşturur

func (*AuthSystem) Shutdown

func (s *AuthSystem) Shutdown()

Shutdown, auth sistemini kapatır (cleanup işlemleri için)

type AuthenticatedHandler

type AuthenticatedHandler func(ctx context.Context, req interface{}) (interface{}, error)

AuthenticatedHandler, authentication gereksinimi olan handler'lar için tip tanımı

type CacheInterface

type CacheInterface interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value []byte, expiration time.Duration) error
	Del(ctx context.Context, key string) error
}

CacheInterface, cache işlemlerini soyutlar

func NewRedisCache

func NewRedisCache(client *redis.Client, prefix string) CacheInterface

NewRedisCache, yeni bir RedisCache oluşturur

type DBInterface

type DBInterface interface {
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}

DBInterface, veritabanı işlemlerini soyutlar (pgx uyumlu)

type DatabasePermissionProvider

type DatabasePermissionProvider interface {
	PermissionProvider

	// Database-specific methods
	LoadUserPermissions(ctx context.Context, userID uuid.UUID) error
	LoadUserRoles(ctx context.Context, userID uuid.UUID) error
	SaveUserPermissions(ctx context.Context, userID uuid.UUID, permissions []string) error
	SaveUserRoles(ctx context.Context, userID uuid.UUID, roles []string) error
	InvalidateUserCache(userID uuid.UUID)
	InvalidateRoleCache(role string)
}

DatabasePermissionProvider interfacesi - gerçek implementasyon için

type GenericHandlerDecorator

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

GenericHandlerDecorator, jenerik handler'lar için authentication decorator'u

func NewGenericHandlerDecorator

func NewGenericHandlerDecorator(authService AuthService) *GenericHandlerDecorator

NewGenericHandlerDecorator, yeni bir GenericHandlerDecorator oluşturur

type JWTClaims

type JWTClaims struct {
	UserID      string   `json:"user_id"`
	Email       string   `json:"email"`
	FullName    string   `json:"full_name"`
	CompanyID   *string  `json:"company_id,omitempty"`
	IsVerified  bool     `json:"is_verified"`
	Permissions []string `json:"permissions"`
	Roles       []string `json:"roles"`
	TokenType   string   `json:"token_type"`
	SessionID   string   `json:"session_id"`
	jwt.RegisteredClaims
}

JWTClaims, JWT token'ında saklanan claim'leri temsil eder

type JWTConfig

type JWTConfig struct {
	SecretKey              string        `mapstructure:"secret_key" json:"secret_key"`
	AccessTokenExpiration  time.Duration `mapstructure:"access_token_expiration" json:"access_token_expiration"`
	RefreshTokenExpiration time.Duration `mapstructure:"refresh_token_expiration" json:"refresh_token_expiration"`
	Issuer                 string        `mapstructure:"issuer" json:"issuer"`
}

JWTConfig, JWT konfigürasyon yapısı

func DefaultJWTConfig

func DefaultJWTConfig() *JWTConfig

DefaultJWTConfig, varsayılan JWT konfigürasyonu

func (*JWTConfig) CreateTokenProvider

func (c *JWTConfig) CreateTokenProvider() (TokenProvider, error)

CreateTokenProvider, konfigürasyona göre token provider oluşturur

func (*JWTConfig) Validate

func (c *JWTConfig) Validate() error

Validate, JWT konfigürasyonunu doğrular

type JWTTokenProvider

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

JWTTokenProvider, JWT tabanlı token provider implementasyonu

func (*JWTTokenProvider) GenerateAccessToken

func (p *JWTTokenProvider) GenerateAccessToken(authCtx *AuthContext) (string, error)

GenerateAccessToken, access token oluşturur

func (*JWTTokenProvider) GenerateRefreshToken

func (p *JWTTokenProvider) GenerateRefreshToken(authCtx *AuthContext) (string, error)

GenerateRefreshToken, refresh token oluşturur

func (*JWTTokenProvider) GetRefreshTokenExpiration

func (p *JWTTokenProvider) GetRefreshTokenExpiration() time.Duration

GetRefreshTokenExpiration, refresh token süresini döner

func (*JWTTokenProvider) GetTokenExpiration

func (p *JWTTokenProvider) GetTokenExpiration() time.Duration

GetTokenExpiration, access token süresini döner

func (*JWTTokenProvider) ValidateAccessToken

func (p *JWTTokenProvider) ValidateAccessToken(tokenString string) (*AuthContext, error)

ValidateAccessToken, access token'ı doğrular

func (*JWTTokenProvider) ValidateRefreshToken

func (p *JWTTokenProvider) ValidateRefreshToken(tokenString string) (*AuthContext, error)

ValidateRefreshToken, refresh token'ı doğrular

type MemorySessionStore

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

MemorySessionStore, memory'de session saklayan implementasyon

func (*MemorySessionStore) Delete

func (s *MemorySessionStore) Delete(ctx context.Context, sessionID string) error

Delete, session'ı siler

func (*MemorySessionStore) DeleteAllForUser

func (s *MemorySessionStore) DeleteAllForUser(ctx context.Context, userID uuid.UUID) error

DeleteAllForUser, kullanıcının tüm session'larını siler

func (*MemorySessionStore) Exists

func (s *MemorySessionStore) Exists(ctx context.Context, sessionID string) (bool, error)

Exists, session'ın var olup olmadığını kontrol eder

func (*MemorySessionStore) Get

func (s *MemorySessionStore) Get(ctx context.Context, sessionID string) (*AuthContext, error)

Get, session'ı getirir

func (*MemorySessionStore) GetAllUserSessions

func (s *MemorySessionStore) GetAllUserSessions(ctx context.Context, userID uuid.UUID) ([]*AuthContext, error)

GetAllUserSessions, kullanıcının tüm aktif session'larını döner

func (*MemorySessionStore) GetStats

func (s *MemorySessionStore) GetStats() *SessionStats

func (*MemorySessionStore) GetUserSessionCount

func (s *MemorySessionStore) GetUserSessionCount(ctx context.Context, userID uuid.UUID) int

GetUserSessionCount, kullanıcının aktif session sayısını döner

func (*MemorySessionStore) Set

func (s *MemorySessionStore) Set(ctx context.Context, sessionID string, authCtx *AuthContext, expiration time.Duration) error

Set, session'ı saklar

func (*MemorySessionStore) StopCleanup

func (s *MemorySessionStore) StopCleanup()

StopCleanup, cleanup goroutine'ini durdurur

type PermissionGuard

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

PermissionGuard, permission tabanlı guard işlemleri yapar

func NewPermissionGuard

func NewPermissionGuard(authService AuthService) *PermissionGuard

NewPermissionGuard, yeni bir PermissionGuard oluşturur

func RequirePermissionGuard

func RequirePermissionGuard(ctx context.Context) *PermissionGuard

RequirePermissionGuard, permission guard helper

func (*PermissionGuard) CheckAnyPermission

func (g *PermissionGuard) CheckAnyPermission(ctx context.Context, permissions ...string) error

CheckAnyPermission, context'teki kullanıcının permission'larından herhangi birine sahip olup olmadığını kontrol eder

func (*PermissionGuard) CheckPermission

func (g *PermissionGuard) CheckPermission(ctx context.Context, permission string) error

CheckPermission, context'teki kullanıcının permission'ını kontrol eder

func (*PermissionGuard) CheckRole

func (g *PermissionGuard) CheckRole(ctx context.Context, role string) error

CheckRole, context'teki kullanıcının role'ünü kontrol eder

type PermissionProvider

type PermissionProvider interface {
	GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error)
	GetUserRoles(ctx context.Context, userID uuid.UUID) ([]string, error)
	GetRolePermissions(ctx context.Context, role string) ([]string, error)
}

PermissionProvider, kullanıcı permission ve role bilgilerini sağlar

func NewSQLPermissionProvider

func NewSQLPermissionProvider(db DBInterface, cache CacheInterface) PermissionProvider

NewSQLPermissionProvider, yeni bir SQLPermissionProvider oluşturur

func NewStaticPermissionProvider

func NewStaticPermissionProvider() PermissionProvider

NewStaticPermissionProvider, yeni bir static permission provider oluşturur

type RedisCache

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

RedisCache, CacheInterface'i implement eden Redis adaptörü

func (*RedisCache) Del

func (c *RedisCache) Del(ctx context.Context, key string) error

Del, cache'den veri siler

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, error)

Get, cache'den veri okur

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value []byte, expiration time.Duration) error

Set, cache'e veri yazar

type RedisSessionStore

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

RedisSessionStore, Redis tabanlı session store implementasyonu

func (*RedisSessionStore) Delete

func (s *RedisSessionStore) Delete(ctx context.Context, sessionID string) error

Delete, session'ı Redis'ten siler

func (*RedisSessionStore) DeleteAllForUser

func (s *RedisSessionStore) DeleteAllForUser(ctx context.Context, userID uuid.UUID) error

DeleteAllForUser, kullanıcının tüm session'larını siler

func (*RedisSessionStore) Exists

func (s *RedisSessionStore) Exists(ctx context.Context, sessionID string) (bool, error)

Exists, session'ın var olup olmadığını kontrol eder

func (*RedisSessionStore) Get

func (s *RedisSessionStore) Get(ctx context.Context, sessionID string) (*AuthContext, error)

Get, session'ı Redis'ten getirir

func (*RedisSessionStore) Set

func (s *RedisSessionStore) Set(ctx context.Context, sessionID string, authCtx *AuthContext, expiration time.Duration) error

Set, session'ı Redis'e kaydeder

type SQLPermissionProvider

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

SQLPermissionProvider, veritabanı tabanlı permission provider

func (*SQLPermissionProvider) GetRolePermissions

func (p *SQLPermissionProvider) GetRolePermissions(ctx context.Context, role string) ([]string, error)

GetRolePermissions, rolün permission'larını veritabanından getirir

func (*SQLPermissionProvider) GetUserPermissions

func (p *SQLPermissionProvider) GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserPermissions, kullanıcının permission'larını veritabanından getirir

func (*SQLPermissionProvider) GetUserRoles

func (p *SQLPermissionProvider) GetUserRoles(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserRoles, kullanıcının rollerini veritabanından getirir

type SessionConfig

type SessionConfig struct {
	CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
	MaxSessions     int           `mapstructure:"max_sessions_per_user" json:"max_sessions_per_user"`
}

SessionConfig, session konfigürasyonu

func DefaultSessionConfig

func DefaultSessionConfig() *SessionConfig

DefaultSessionConfig, varsayılan session konfigürasyonu

type SessionData

type SessionData struct {
	AuthContext *AuthContext `json:"auth_context"`
	ExpiresAt   time.Time    `json:"expires_at"`
	CreatedAt   time.Time    `json:"created_at"`
	UpdatedAt   time.Time    `json:"updated_at"`
}

SessionData, session verilerini tutar

func (*SessionData) IsExpired

func (s *SessionData) IsExpired() bool

IsExpired, session'ın süresi bitmiş mi kontrol eder

type SessionStats

type SessionStats struct {
	TotalSessions   int            `json:"total_sessions"`
	ExpiredSessions int            `json:"expired_sessions"`
	ActiveSessions  int            `json:"active_sessions"`
	UserSessions    map[string]int `json:"user_sessions"`
}

GetStats, session store istatistiklerini döner

type SessionStore

type SessionStore interface {
	Set(ctx context.Context, sessionID string, authCtx *AuthContext, expiration time.Duration) error
	Get(ctx context.Context, sessionID string) (*AuthContext, error)
	Delete(ctx context.Context, sessionID string) error
	DeleteAllForUser(ctx context.Context, userID uuid.UUID) error
	Exists(ctx context.Context, sessionID string) (bool, error)
}

SessionStore, session verilerini saklar

func NewMemorySessionStore

func NewMemorySessionStore(cleanupInterval time.Duration) SessionStore

NewMemorySessionStore, yeni bir memory session store oluşturur

func NewRedisSessionStore

func NewRedisSessionStore(client *redis.Client, prefix string) SessionStore

NewRedisSessionStore, yeni bir RedisSessionStore oluşturur

type SimpleTokenConfig

type SimpleTokenConfig struct {
	SecretKey              string        `mapstructure:"secret_key" json:"secret_key"`
	AccessTokenExpiration  time.Duration `mapstructure:"access_token_expiration" json:"access_token_expiration"`
	RefreshTokenExpiration time.Duration `mapstructure:"refresh_token_expiration" json:"refresh_token_expiration"`
	Issuer                 string        `mapstructure:"issuer" json:"issuer"`
}

SimpleTokenConfig, Simple token konfigürasyon yapısı

func DefaultSimpleTokenConfig

func DefaultSimpleTokenConfig() *SimpleTokenConfig

DefaultSimpleTokenConfig, varsayılan Simple token konfigürasyonu

func (*SimpleTokenConfig) CreateTokenProvider

func (c *SimpleTokenConfig) CreateTokenProvider() (TokenProvider, error)

CreateTokenProvider, konfigürasyona göre token provider oluşturur

func (*SimpleTokenConfig) Validate

func (c *SimpleTokenConfig) Validate() error

Validate, Simple token konfigürasyonunu doğrular

type SimpleTokenPayload

type SimpleTokenPayload struct {
	UserID      string   `json:"user_id"`
	Email       string   `json:"email"`
	FullName    string   `json:"full_name"`
	CompanyID   *string  `json:"company_id,omitempty"`
	IsVerified  bool     `json:"is_verified"`
	Permissions []string `json:"permissions"`
	Roles       []string `json:"roles"`
	TokenType   string   `json:"token_type"`
	SessionID   string   `json:"session_id"`
	IssuedAt    int64    `json:"issued_at"`
	ExpiresAt   int64    `json:"expires_at"`
	Issuer      string   `json:"issuer"`
}

SimpleTokenPayload, basit token'da saklanan veri yapısı

type SimpleTokenProvider

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

SimpleTokenProvider, basit HMAC tabanlı token provider implementasyonu

func (*SimpleTokenProvider) GenerateAccessToken

func (p *SimpleTokenProvider) GenerateAccessToken(authCtx *AuthContext) (string, error)

GenerateAccessToken, access token oluşturur

func (*SimpleTokenProvider) GenerateRefreshToken

func (p *SimpleTokenProvider) GenerateRefreshToken(authCtx *AuthContext) (string, error)

GenerateRefreshToken, refresh token oluşturur

func (*SimpleTokenProvider) GetRefreshTokenExpiration

func (p *SimpleTokenProvider) GetRefreshTokenExpiration() time.Duration

GetRefreshTokenExpiration, refresh token süresini döner

func (*SimpleTokenProvider) GetTokenExpiration

func (p *SimpleTokenProvider) GetTokenExpiration() time.Duration

GetTokenExpiration, access token süresini döner

func (*SimpleTokenProvider) ValidateAccessToken

func (p *SimpleTokenProvider) ValidateAccessToken(tokenString string) (*AuthContext, error)

ValidateAccessToken, access token'ı doğrular

func (*SimpleTokenProvider) ValidateRefreshToken

func (p *SimpleTokenProvider) ValidateRefreshToken(tokenString string) (*AuthContext, error)

ValidateRefreshToken, refresh token'ı doğrular

type StaticPermissionProvider

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

StaticPermissionProvider, statik permission verisi sağlayan basit implementasyon Gerçek uygulamada bu veriler veritabanından gelecek

func (*StaticPermissionProvider) AddRolePermission

func (p *StaticPermissionProvider) AddRolePermission(role string, permission string)

AddRolePermission, role'e permission ekler

func (*StaticPermissionProvider) AddUserPermission

func (p *StaticPermissionProvider) AddUserPermission(userID uuid.UUID, permission string)

AddUserPermission, kullanıcıya doğrudan permission ekler

func (*StaticPermissionProvider) AddUserRole

func (p *StaticPermissionProvider) AddUserRole(userID uuid.UUID, role string)

AddUserRole, kullanıcıya role ekler

func (*StaticPermissionProvider) DefineRole

func (p *StaticPermissionProvider) DefineRole(role string, permissions []string)

DefineRole, yeni bir role tanımlar ve permission'larını belirler

func (*StaticPermissionProvider) GetAllPermissions

func (p *StaticPermissionProvider) GetAllPermissions() []string

GetAllPermissions, sistemdeki tüm mevcut permission'ları döner

func (*StaticPermissionProvider) GetAllRoles

func (p *StaticPermissionProvider) GetAllRoles() []string

GetAllRoles, tanımlı tüm rolleri döner

func (*StaticPermissionProvider) GetRolePermissions

func (p *StaticPermissionProvider) GetRolePermissions(ctx context.Context, role string) ([]string, error)

GetRolePermissions, bir role'ün permission'larını döner

func (*StaticPermissionProvider) GetUserPermissions

func (p *StaticPermissionProvider) GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserPermissions, kullanıcının doğrudan permission'larını ve role'lerinden gelen permission'larını döner

func (*StaticPermissionProvider) GetUserRoles

func (p *StaticPermissionProvider) GetUserRoles(ctx context.Context, userID uuid.UUID) ([]string, error)

GetUserRoles, kullanıcının role'lerini döner

func (*StaticPermissionProvider) RemoveRolePermission

func (p *StaticPermissionProvider) RemoveRolePermission(role string, permission string)

RemoveRolePermission, role'den permission kaldırır

func (*StaticPermissionProvider) RemoveUserPermission

func (p *StaticPermissionProvider) RemoveUserPermission(userID uuid.UUID, permission string)

RemoveUserPermission, kullanıcıdan doğrudan permission kaldırır

func (*StaticPermissionProvider) RemoveUserRole

func (p *StaticPermissionProvider) RemoveUserRole(userID uuid.UUID, role string)

RemoveUserRole, kullanıcıdan role kaldırır

func (*StaticPermissionProvider) SetUserPermissions

func (p *StaticPermissionProvider) SetUserPermissions(userID uuid.UUID, permissions []string)

SetUserPermissions, kullanıcının doğrudan permission'larını belirler

func (*StaticPermissionProvider) SetUserRoles

func (p *StaticPermissionProvider) SetUserRoles(userID uuid.UUID, roles []string)

SetUserRoles, kullanıcının role'lerini belirler

type TokenPair

type TokenPair struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	TokenType    string    `json:"token_type"`
	ExpiresIn    int64     `json:"expires_in"`
	ExpiresAt    time.Time `json:"expires_at"`
}

TokenPair, access ve refresh token çiftini temsil eder

type TokenProvider

type TokenProvider interface {
	GenerateAccessToken(authCtx *AuthContext) (string, error)
	GenerateRefreshToken(authCtx *AuthContext) (string, error)
	ValidateAccessToken(token string) (*AuthContext, error)
	ValidateRefreshToken(token string) (*AuthContext, error)
	GetTokenExpiration() time.Duration
	GetRefreshTokenExpiration() time.Duration
}

TokenProvider, token oluşturma ve doğrulama işlemlerini yapar

func NewJWTTokenProvider

func NewJWTTokenProvider(
	secretKey string,
	accessTokenExpiration time.Duration,
	refreshTokenExpiration time.Duration,
	issuer string,
) TokenProvider

NewJWTTokenProvider, yeni bir JWT token provider oluşturur

func NewSimpleTokenProvider

func NewSimpleTokenProvider(
	secretKey string,
	accessTokenExpiration time.Duration,
	refreshTokenExpiration time.Duration,
	issuer string,
) TokenProvider

NewSimpleTokenProvider, yeni bir Simple token provider oluşturur

Jump to

Keyboard shortcuts

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