# Güvenlik ve Authentication - FikoYT

## 🔐 Authentication Sistemi

### JWT Token Management
```go
// Token generation
func GenerateJWT(user *User) (string, error) {
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "user_id": user.ID,
        "email":   user.Email,
        "exp":     time.Now().Add(24 * time.Hour).Unix(),
        "iat":     time.Now().Unix(),
    })

    return token.SignedString([]byte(os.Getenv("JWT_SECRET")))
}
```

### Session Management
```go
// MongoDB-backed sessions
SessionConfig = session.Config{
    Storage: MongoStore,
    CookieSecure: true,
    CookieHTTPOnly: true,
    CookieSameSite: "lax",
    Expiration: 24 * time.Hour,
    KeyLookup: "cookie:sid",
}
```

## 🛡️ Security Middleware Chain

### Request Validation
```go
// Rate limiting
app.Use(limiter.New(limiter.Config{
    Max: 100,
    Expiration: 1 * time.Minute,
    KeyGenerator: func(c *fiber.Ctx) string {
        return c.IP()
    },
}))

// CORS protection
app.Use(cors.New(cors.Config{
    AllowOrigins: []string{"https://fikoyt.com", "https://fikoyt-zorro.com"},
    AllowCredentials: true,
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
}))
```

### Input Sanitization
```go
// XSS protection
func sanitizeInput(input string) string {
    // HTML encode
    input = html.EscapeString(input)

    // Remove potential script tags
    re := regexp.MustCompile(`(?i)<script.*?>.*?</script>`)
    input = re.ReplaceAllString(input, "")

    // SQL injection protection
    input = strings.ReplaceAll(input, "'", "''")

    return input
}
```

## 🔒 Database Security

### MongoDB Security
```javascript
// Role-based access control
db.createRole({
    role: "fikoyt_read_only",
    privileges: [{
        resource: { db: "fikoyt", collection: "" },
        actions: ["find", "count"]
    }],
    roles: []
});

// Field-level encryption
db.createCollection("users", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            properties: {
                email: {
                    bsonType: "string",
                    pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
                },
                password: {
                    bsonType: "string",
                    minLength: 8,
                    description: "Minimum 8 characters"
                }
            }
        }
    }
});
```

### Encryption at Rest
```go
// AES-256 encryption for sensitive data
func EncryptData(data []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    nonce := make([]byte, gcm.NonceSize())
    if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }

    return gcm.Seal(nonce, nonce, data, nil), nil
}
```

## 🔍 Security Headers

### HTTP Security Headers
```go
func SecurityHeaders() fiber.Handler {
    return func(c *fiber.Ctx) error {
        c.Set("X-Content-Type-Options", "nosniff")
        c.Set("X-Frame-Options", "DENY")
        c.Set("X-XSS-Protection", "1; mode=block")
        c.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
        c.Set("Content-Security-Policy",
            "default-src 'self'; " +
            "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
            "style-src 'self' 'unsafe-inline'; " +
            "img-src 'self' data: https:; " +
            "connect-src 'self' wss: https:;")
        return c.Next()
    }
}
```

## 🔑 Password Security

### Hashing and Salting
```go
// bcrypt with salt
func HashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    return string(bytes), err
}

func CheckPasswordHash(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}
```

### Password Policy
```typescript
// Frontend validation
const passwordPolicy = {
    minLength: 8,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSpecialChars: true,
    preventCommonPasswords: true
};

function validatePassword(password: string): boolean {
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    return regex.test(password);
}
```

## 🔒 API Security

### API Key Management
```go
type APIKey struct {
    ID        string `json:"id"`
    Key       string `json:"key"`
    Name      string `json:"name"`
    Scopes    []string `json:"scopes"`
    CreatedAt time.Time `json:"created_at"`
    ExpiresAt time.Time `json:"expires_at"`
}

func ValidateAPIKey(c *fiber.Ctx) error {
    key := c.Get("X-API-Key")
    if key == "" {
        return c.Status(401).JSON(fiber.Map{
            "error": "API key required",
        })
    }

    // Validate against database
    apiKey := FindAPIKey(key)
    if apiKey == nil || time.Now().After(apiKey.ExpiresAt) {
        return c.Status(401).JSON(fiber.Map{
            "error": "Invalid or expired API key",
        })
    }

    c.Locals("api_key", apiKey)
    return c.Next()
}
```

### Request Signing
```go
// HMAC-SHA256 request signing
func SignRequest(secret string, method string, path string, body []byte, timestamp string) string {
    message := method + path + string(body) + timestamp
    h := hmac.New(sha256.New, []byte(secret))
    h.Write([]byte(message))
    return hex.EncodeToString(h.Sum(nil))
}
```

## 🛡️ DDoS Protection

### Rate Limiting by IP
```go
type RateLimiter struct {
    requests map[string][]time.Time
    mutex    sync.RWMutex
    limit    int
    window   time.Duration
}

func (rl *RateLimiter) Check(ip string) bool {
    rl.mutex.Lock()
    defer rl.mutex.Unlock()

    now := time.Now()
    if requests, exists := rl.requests[ip]; exists {
        // Remove old requests
        valid := requests[0]
        if now.Sub(valid) > rl.window {
            rl.requests[ip] = []time.Time{now}
            return true
        }

        // Check limit
        if len(requests) >= rl.limit {
            return false
        }

        rl.requests[ip] = append(requests, now)
    } else {
        rl.requests[ip] = []time.Time{now}
    }

    return true
}
```

## 🔍 Security Monitoring

### Intrusion Detection
```go
// Suspicious activity detection
func DetectSuspiciousActivity(user *User, req *fiber.Ctx) {
    // Check for unusual patterns
    if isSuspiciousIP(req.IP()) {
        logSecurityEvent("Suspicious IP", map[string]interface{}{
            "ip": req.IP(),
            "user": user.ID,
            "time": time.Now(),
        })
    }

    // Check for rapid requests
    if isRapidRequests(user.ID) {
        blockUserTemporarily(user.ID)
    }
}
```

### Audit Logging
```go
type AuditLog struct {
    ID        string `bson:"_id"`
    UserID    string `bson:"user_id"`
    Action    string `bson:"action"`
    Resource  string `bson:"resource"`
    IP        string `bson:"ip"`
    UserAgent string `bson:"user_agent"`
    Timestamp time.Time `bson:"timestamp"`
    Success   bool   `bson:"success"`
    Details   interface{} `bson:"details"`
}

func LogAudit(event AuditLog) error {
    collection := db.Collection("audit_logs")
    _, err := collection.InsertOne(context.Background(), event)
    return err
}
```

## 🔐 Cross-Site Security

### CSRF Protection
```typescript
// Angular CSRF protection
export class CsrfInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const csrfToken = this.getCookie('XSRF-TOKEN');

        if (csrfToken) {
            req = req.clone({
                setHeaders: {
                    'X-XSRF-TOKEN': csrfToken
                }
            });
        }

        return next.handle(req);
    }
}
```

### SameSite Cookies
```go
// Secure cookie configuration
func SetSecureCookie(c *fiber.Ctx, name, value string) {
    c.Cookie(&fiber.Cookie{
        Name: name,
        Value: value,
        Secure: true,
        HTTPOnly: true,
        SameSite: "strict",
        MaxAge: 3600, // 1 hour
    })
}
```

## 🚨 Security Best Practices

### Checklist
- [ ] HTTPS zorunlu tüm production ortamlarda
- [ ] Güçlü password policy uygulama
- [ ] Input validation tüm endpoint'lerde
- [ ] Rate limiting DDoS önleme
- [ ] Regular security audits
- [ ] Dependency güncellemeleri
- [ ] Security headers eklenmiş
- [ ] SQL injection protection
- [ ] XSS protection enabled
- [ ] CSRF protection active
- [ ] File upload validation
- [ ] Secure backup procedures

### Incident Response
1. **Detection**: Monitor sistemleri
2. **Containment**: Hızlı müdahale
3. **Investigation**: Log analizi
4. **Resolution**: Güvenlik açığı kapatma
5. **Recovery**: Sistemi normale döndürme
6. **Review**: Process iyileştirme

---
2025-11-06