geofence

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README ΒΆ

Geofencing Plugin

Enterprise-grade geographic fencing and location-based security for AuthSome. Control access based on user location, detect VPNs/proxies, monitor travel patterns, and enforce GPS-based authentication.

Features

🌍 Geographic Restrictions
  • Country/Region Controls: Allowlist or blocklist specific countries and regions
  • City-Level Restrictions: Fine-grained access control at city level
  • Geofencing: Define circular or polygonal geographic boundaries
  • Distance-Based Controls: Maximum distance from reference points
  • Time-Based Rules: Different restrictions by time of day/week
πŸ” IP Geolocation
  • Multiple Providers: MaxMind, IPInfo.io, ipapi.com, ipgeolocation.io
  • Automatic Fallback: Switch to backup provider on failure
  • Caching: Efficient caching to minimize API calls
  • High Accuracy: Support for multiple accuracy levels
πŸ“± GPS-Based Authentication
  • Device GPS: Require GPS coordinates from mobile devices
  • Accuracy Validation: Enforce minimum/maximum accuracy thresholds
  • Geofence Matching: Verify coordinates within defined geofences
  • Timestamp Validation: Prevent replay attacks with timestamp checks
πŸ›‘οΈ VPN/Proxy Detection
  • VPN Detection: Identify and block VPN connections
  • Proxy Detection: Detect HTTP/SOCKS proxies
  • Tor Detection: Block Tor exit nodes
  • Datacenter Detection: Identify datacenter IPs
  • Fraud Scoring: Risk scoring for suspicious connections
🏒 Corporate Network Detection
  • Network Ranges: Define corporate IP ranges (CIDR)
  • DNS-Based Detection: Verify expected DNS servers
  • Certificate-Based: Require trusted certificates
  • Hybrid Mode: Allow external with additional verification
✈️ Travel Notifications
  • Impossible Travel Detection: Flag physically impossible travel speeds
  • Distance Thresholds: Alert on significant location changes
  • Travel Approval: Require admin approval for suspicious travel
  • Notification Channels: Email, SMS, push, webhooks
  • Trusted Destinations: Whitelist frequent locations

Installation

1. Enable the Plugin
package main

import (
    "github.com/xraph/authsome"
    "github.com/xraph/authsome/plugins/enterprise/geofence"
)

func main() {
    auth := authsome.New(
        authsome.WithDatabase(db),
        authsome.WithForgeApp(app),
    )

    // Register geofence plugin
    geofencePlugin := geofence.NewPlugin()
    auth.RegisterPlugin(geofencePlugin)

    // Initialize
    auth.Initialize(context.Background())
}
2. Configuration

Add to your configuration file (config.yaml):

auth:
  geofence:
    enabled: true
    
    # Geographic Restrictions
    restrictions:
      defaultAction: allow  # or "deny"
      strictMode: false
      allowedCountries: []
      blockedCountries: ["KP", "IR", "SY"]  # Example: sanctioned countries
      maxDistanceKm: 0  # 0 = unlimited
      
    # Geolocation Provider
    geolocation:
      provider: maxmind  # maxmind, ipapi, ipinfo, ipgeolocation
      maxmindLicenseKey: "your-license-key"
      maxmindDatabasePath: "/path/to/GeoLite2-City.mmdb"
      fallbackProvider: ipapi
      ipapiKey: "your-api-key"
      cacheDuration: 24h
      timeout: 5s
      
    # VPN/Proxy Detection
    detection:
      detectVpn: true
      blockVpn: false  # Set to true to block VPNs
      detectProxy: true
      blockProxy: false
      detectTor: true
      blockTor: false
      provider: ipqs  # ipqs, proxycheck, vpnapi
      ipqsKey: "your-ipqs-key"
      ipqsStrictness: 1  # 0-3
      ipqsMinScore: 75.0
      cacheDuration: 1h
      
    # GPS Authentication
    gps:
      enabled: false
      requireGps: false
      maxAccuracyMeters: 1000
      maxSpeedKmh: 1000
      validateTimestamp: true
      maxTimestampAge: 5m
      
    # Travel Notifications
    travel:
      enabled: true
      minDistanceKm: 500  # Trigger at 500km
      maxSpeedKmh: 900    # Flag impossible travel
      notifyUser: true
      notifyAdmin: false
      requireApproval: false
      emailNotify: true
      autoApproveAfter: 24h
      trustFrequentDest: true
      
    # Session Management
    session:
      trackLocation: true
      updateInterval: 5m
      validateOnRequest: true
      invalidateOnViolation: false
      gracePeriod: 10m
      maxViolations: 3
      
    # API Configuration
    api:
      basePath: /auth/geofence
      enableManagement: true
      enableValidation: true
      enableMetrics: true
      
    # Security
    security:
      rateLimitEnabled: true
      maxChecksPerMinute: 60
      auditViolations: true
      storeLocations: true
      locationRetention: 2160h  # 90 days
      anonymizeOldData: true

Usage

Creating Geofence Rules
Block Specific Countries
rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "Block Sanctioned Countries",
    Description: "Prevent access from sanctioned countries",
    Enabled: true,
    Priority: 100,
    RuleType: "country",
    BlockedCountries: []string{"KP", "IR", "SY", "CU"},
    Action: "deny",
    NotifyAdmin: true,
}

err := service.repo.CreateRule(ctx, rule)
Allow Only Specific Regions
rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "US Only",
    Description: "Allow access only from United States",
    Enabled: true,
    Priority: 90,
    RuleType: "country",
    AllowedCountries: []string{"US"},
    Action: "deny",
    RequireMFA: true,  # Require MFA for violations
}
Circular Geofence (Office Radius)
centerLat := 37.7749
centerLon := -122.4194
radiusKm := 10.0

rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "Office Geofence",
    Description: "Access only within 10km of San Francisco office",
    Enabled: true,
    Priority: 80,
    RuleType: "geofence",
    GeofenceType: "circle",
    CenterLat: &centerLat,
    CenterLon: &centerLon,
    RadiusKm: &radiusKm,
    Action: "deny",
}
Polygonal Geofence (Campus)
// Define polygon coordinates (latitude, longitude pairs)
coordinates := [][2]float64{
    {37.7749, -122.4194},
    {37.7750, -122.4180},
    {37.7735, -122.4175},
    {37.7730, -122.4190},
}

rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "Campus Boundary",
    Description: "Access only within campus boundaries",
    Enabled: true,
    Priority: 85,
    RuleType: "geofence",
    GeofenceType: "polygon",
    Coordinates: coordinates,
    Action: "deny",
}
Block VPNs and Proxies
rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "Block Anonymous Connections",
    Description: "Prevent VPN, proxy, and Tor access",
    Enabled: true,
    Priority: 95,
    RuleType: "detection",
    BlockVPN: true,
    BlockProxy: true,
    BlockTor: true,
    Action: "deny",
    NotifyAdmin: true,
}
Time-Based Restrictions
timeRestrictions := []geofence.TimeRestrictionRule{
    {
        AllowedDays: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"},
        StartHour: 9,   # 9 AM
        EndHour: 17,    # 5 PM
        Timezone: "America/New_York",
    },
}

rule := &geofence.GeofenceRule{
    AppID: orgID,
    Name: "Business Hours Only",
    Description: "Access only during business hours",
    Enabled: true,
    Priority: 70,
    RuleType: "time",
    TimeRestrictions: timeRestrictions,
    Action: "deny",
}
Using Middleware
Automatic Geofence Checking
// Apply geofence middleware to protected routes
protected := router.Group("/api")
protected.Use(geofencePlugin.Middleware())

protected.GET("/data", handlers.GetData)
protected.POST("/action", handlers.PerformAction)
Country-Specific Middleware
// Require requests from specific countries
usOnly := geofencePlugin.Middleware().RequireCountry("US", "CA")
router.Group("/us-only").Use(usOnly)
Block VPN Middleware
// Block all VPN connections
noVPN := geofencePlugin.Middleware().BlockVPN
router.Group("/sensitive").Use(noVPN)
Manual Location Checks
// Perform ad-hoc location check
req := &geofence.LocationCheckRequest{
    UserID: userID,
    AppID: orgID,
    IPAddress: "8.8.8.8",
    EventType: "login",
}

result, err := geofencePlugin.Service().CheckLocation(ctx, req)
if err != nil {
    // Handle error
}

if !result.Allowed {
    // Access denied
    log.Printf("Access denied: %s", result.Reason)
}

if result.RequireMFA {
    // Enforce MFA
}

if result.TravelAlert {
    // Handle travel alert
}
Managing Trusted Locations
// Add a trusted location
trustedLoc := &geofence.TrustedLocation{
    UserID: userID,
    AppID: orgID,
    Name: "Home",
    Country: "United States",
    CountryCode: "US",
    City: "San Francisco",
    Latitude: 37.7749,
    Longitude: -122.4194,
    RadiusKm: 2.0,
    AutoApprove: true,
    SkipMFA: false,
}

err := service.repo.CreateTrustedLocation(ctx, trustedLoc)
Handling Travel Alerts
// Get pending travel alerts for organization
alerts, err := service.repo.GetPendingTravelAlerts(ctx, appID)

for _, alert := range alerts {
    if alert.Severity == "critical" {
        // Notify admin
        log.Printf("Critical travel alert for user %s: %.0f km in %s", 
            alert.UserID, alert.DistanceKm, alert.TimeDifference)
    }
}

// Approve travel
err = service.repo.ApproveTravel(ctx, alert.ID, adminUserID)

// Or deny travel
err = service.repo.DenyTravel(ctx, alert.ID, adminUserID)

API Endpoints

Rule Management
# Create rule
POST /auth/geofence/rules

# List rules
GET /auth/geofence/rules

# Get specific rule
GET /auth/geofence/rules/:id

# Update rule
PUT /auth/geofence/rules/:id

# Delete rule
DELETE /auth/geofence/rules/:id
Location Validation
# Check location
POST /auth/geofence/check
{
  "ipAddress": "8.8.8.8",
  "userId": "user-id",
  "eventType": "login"
}

# IP lookup
GET /auth/geofence/lookup/8.8.8.8
Travel Alerts
# List travel alerts
GET /auth/geofence/travel-alerts?status=pending

# Get specific alert
GET /auth/geofence/travel-alerts/:id

# Approve travel
POST /auth/geofence/travel-alerts/:id/approve

# Deny travel
POST /auth/geofence/travel-alerts/:id/deny
Trusted Locations
# Create trusted location
POST /auth/geofence/trusted-locations

# List trusted locations
GET /auth/geofence/trusted-locations

# Update trusted location
PUT /auth/geofence/trusted-locations/:id

# Delete trusted location
DELETE /auth/geofence/trusted-locations/:id
Violations
# List violations
GET /auth/geofence/violations?limit=50

# Get specific violation
GET /auth/geofence/violations/:id

# Resolve violation
POST /auth/geofence/violations/:id/resolve
{
  "resolution": "approved_exception"
}

Use Cases

1. Compliance with Data Residency Laws
// Only allow access from EU for GDPR compliance
rule := &geofence.GeofenceRule{
    Name: "GDPR Data Residency",
    AllowedCountries: []string{"DE", "FR", "IT", "ES", "NL", "BE", "AT", "IE"},
    Action: "deny",
}
2. Prevent Fraud from High-Risk Countries
// Block countries known for high fraud rates
rule := &geofence.GeofenceRule{
    Name: "Fraud Prevention",
    BlockedCountries: []string{"NG", "PK", "BD", "RO"},
    BlockVPN: true,
    BlockProxy: true,
    Action: "deny",
    NotifyAdmin: true,
}
3. Office-Only Access for Sensitive Operations
// Require physical presence at office for admin operations
rule := &geofence.GeofenceRule{
    Name: "Admin Office Only",
    GeofenceType: "circle",
    CenterLat: &officeLat,
    CenterLon: &officeLon,
    RadiusKm: &radius,
    Action: "deny",
    RequireMFA: true,
}
4. Detect Account Takeover
// Monitor for impossible travel patterns
config.Travel.Enabled = true
config.Travel.MaxSpeedKmh = 900  # Commercial aircraft speed
config.Travel.RequireApproval = true
config.Travel.NotifyUser = true
config.Travel.NotifyAdmin = true
5. Regional Licensing Restrictions
// Enforce software licensing by region
rule := &geofence.GeofenceRule{
    Name: "North America License",
    AllowedCountries: []string{"US", "CA", "MX"},
    Action: "deny",
}

Session Security Notifications

The geofence plugin integrates with the notification system to automatically alert users about security-relevant session events.

New Location Login Notifications

Automatically notify users when they log in from a significantly different location:

auth:
  geofence:
    notifications:
      enabled: true
      newLocationEnabled: true
      newLocationThresholdKm: 100  # Trigger at 100km distance from last location

How it works:

  1. User signs in from a new location
  2. Geofence plugin detects location change > threshold
  3. Email sent to user with location details
  4. Location stored for future comparisons

Example notification:

"We noticed a new sign-in to your account from San Francisco, CA (500 km from previous location: Los Angeles, CA) at 2025-12-14 10:30 AM. IP: 8.8.8.8"

Suspicious Login Detection

Automatically detect and notify users about suspicious login patterns:

auth:
  geofence:
    notifications:
      enabled: true
      suspiciousLoginEnabled: true
      suspiciousLoginScoreThreshold: 75.0  # IPQS fraud score threshold
      impossibleTravelEnabled: true
      vpnDetectionEnabled: true
      proxyDetectionEnabled: true
      torDetectionEnabled: true

Detection triggers:

  • Impossible Travel: e.g., 5000km in 1 hour (faster than aircraft)
  • VPN Usage: VPN connection detected (configurable providers)
  • Proxy Detection: HTTP/SOCKS proxy detected
  • Tor Exit Node: Connection from Tor network
  • High Fraud Score: IPQS score above threshold (default: 75/100)

Example notifications:

"Suspicious login detected: Impossible travel - 8500 km in 2.5 hours (3400 km/h, max: 900 km/h). Please verify this was you."

"Suspicious login detected: VPN detected - NordVPN. If this wasn't you, secure your account immediately."

Configuration Reference
auth:
  geofence:
    # Enable notification integration
    notifications:
      enabled: true
      
      # New location alerts
      newLocationEnabled: true
      newLocationThresholdKm: 100  # Distance threshold in km
      
      # Suspicious login alerts
      suspiciousLoginEnabled: true
      suspiciousLoginScoreThreshold: 75.0  # 0-100 fraud score
      
      # Detection types for suspicious login
      impossibleTravelEnabled: true
      vpnDetectionEnabled: true
      proxyDetectionEnabled: true
      torDetectionEnabled: true
    
    # Geolocation provider (required for location tracking)
    geolocation:
      provider: maxmind
      maxmindLicenseKey: "your-license-key"
      maxmindDatabasePath: "/path/to/GeoLite2-City.mmdb"
    
    # Detection provider (required for suspicious login)
    detection:
      detectVpn: true
      detectProxy: true
      detectTor: true
      provider: ipqs
      ipqsKey: "your-ipqs-key"
      ipqsStrictness: 1
Disabling Notifications

To disable session security notifications while keeping geofencing active:

auth:
  geofence:
    enabled: true  # Geofencing still active
    notifications:
      enabled: false  # Disable notifications

Or disable specific notification types:

auth:
  geofence:
    notifications:
      enabled: true
      newLocationEnabled: false  # Disable new location alerts
      suspiciousLoginEnabled: true  # Keep suspicious login alerts

Multi-Tenancy Support

The geofencing plugin fully supports AuthSome's multi-tenancy:

// App-wide rules
rule.AppID = appID
rule.UserID = nil  // Applies to all users in app

// User-specific rules
rule.AppID = appID
rule.UserID = &specificUserID  // Only for this user

Performance Considerations

Caching
  • Geolocation: Cached for 24h by default (configurable)
  • Detection: Cached for 1h by default
  • Database Cache: Persistent caching layer for geolocation data
  • Memory Cache: In-memory LRU cache for frequently accessed IPs
Rate Limiting
  • Per-Minute Limits: Default 60 checks/minute
  • Per-Hour Limits: Default 1000 checks/hour
  • Configurable per organization
Database Optimization
  • Indexed tables for fast queries
  • Automatic cleanup of old location events
  • Optimized geospatial queries

Privacy & Compliance

Data Retention
security:
  locationRetention: 2160h  # 90 days
  anonymizeOldData: true    # Auto-anonymize after retention
security:
  consentRequired: true     # Require user consent
  allowOptOut: false        # Allow users to opt out
GDPR Compliance
  • Users can request location data export
  • Automatic data anonymization
  • Consent tracking
  • Right to be forgotten support

Security Best Practices

  1. Use Strict Mode for critical operations
  2. Enable VPN/Proxy Detection for sensitive data
  3. Implement Travel Notifications to detect account takeovers
  4. Regular Rule Audits to ensure policies are current
  5. Monitor Violations for security incidents
  6. Use Trusted Locations to reduce false positives
  7. Enable Audit Logging for compliance
  8. Test Fallback Providers to ensure availability

Troubleshooting

Geolocation Provider Issues
// Test provider health
err := geofencePlugin.Health(ctx)
if err != nil {
    log.Printf("Provider unhealthy: %v", err)
}

// Check provider configuration
provider := geofencePlugin.Service().geoProvider
log.Printf("Using provider: %s", provider.Name())
False Positives
  1. Add trusted locations for frequent users
  2. Adjust accuracy thresholds
  3. Enable grace periods
  4. Use detection confidence scores
Performance Issues
  1. Increase cache durations
  2. Use MaxMind local database instead of API
  3. Enable database caching
  4. Optimize rule priorities

License

Enterprise feature - requires AuthSome Enterprise license.

Support

For issues and questions:

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type APIConfig ΒΆ

type APIConfig struct {
	BasePath         string `json:"basePath" yaml:"basePath"`
	EnableManagement bool   `json:"enableManagement" yaml:"enableManagement"`
	EnableValidation bool   `json:"enableValidation" yaml:"enableValidation"`
	EnableMetrics    bool   `json:"enableMetrics" yaml:"enableMetrics"`
	EnableRealtime   bool   `json:"enableRealtime" yaml:"enableRealtime"` // WebSocket for live tracking
}

APIConfig configures geofencing API endpoints

type BunRepository ΒΆ

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

BunRepository implements Repository using Bun ORM

func (*BunRepository) ApproveTravel ΒΆ

func (r *BunRepository) ApproveTravel(ctx context.Context, alertID xid.ID, approvedBy xid.ID) error

func (*BunRepository) CreateLocationEvent ΒΆ

func (r *BunRepository) CreateLocationEvent(ctx context.Context, event *LocationEvent) error

Location Events

func (*BunRepository) CreateRule ΒΆ

func (r *BunRepository) CreateRule(ctx context.Context, rule *GeofenceRule) error

Rules

func (*BunRepository) CreateTravelAlert ΒΆ

func (r *BunRepository) CreateTravelAlert(ctx context.Context, alert *TravelAlert) error

Travel Alerts

func (*BunRepository) CreateTrustedLocation ΒΆ

func (r *BunRepository) CreateTrustedLocation(ctx context.Context, location *TrustedLocation) error

Trusted Locations

func (*BunRepository) CreateViolation ΒΆ

func (r *BunRepository) CreateViolation(ctx context.Context, violation *GeofenceViolation) error

Violations

func (*BunRepository) DeleteExpiredCache ΒΆ

func (r *BunRepository) DeleteExpiredCache(ctx context.Context) (int64, error)

func (*BunRepository) DeleteOldLocationEvents ΒΆ

func (r *BunRepository) DeleteOldLocationEvents(ctx context.Context, before time.Time) (int64, error)

func (*BunRepository) DeleteRule ΒΆ

func (r *BunRepository) DeleteRule(ctx context.Context, id xid.ID) error

func (*BunRepository) DeleteTrustedLocation ΒΆ

func (r *BunRepository) DeleteTrustedLocation(ctx context.Context, id xid.ID) error

func (*BunRepository) DenyTravel ΒΆ

func (r *BunRepository) DenyTravel(ctx context.Context, alertID xid.ID, deniedBy xid.ID) error

func (*BunRepository) GetAppViolations ΒΆ added in v0.0.6

func (r *BunRepository) GetAppViolations(ctx context.Context, appID xid.ID, limit int) ([]*GeofenceViolation, error)

func (*BunRepository) GetCachedGeoData ΒΆ

func (r *BunRepository) GetCachedGeoData(ctx context.Context, ip string) (*GeoCache, error)

Geo Cache

func (*BunRepository) GetLastLocation ΒΆ added in v0.0.6

func (r *BunRepository) GetLastLocation(ctx context.Context, userID xid.ID, appID xid.ID) (*GeoData, error)

GetLastLocation retrieves the most recent location for a user as GeoData

func (*BunRepository) GetLastLocationEvent ΒΆ

func (r *BunRepository) GetLastLocationEvent(ctx context.Context, userID xid.ID) (*LocationEvent, error)

func (*BunRepository) GetLocationEvent ΒΆ

func (r *BunRepository) GetLocationEvent(ctx context.Context, id xid.ID) (*LocationEvent, error)

func (*BunRepository) GetPendingTravelAlerts ΒΆ

func (r *BunRepository) GetPendingTravelAlerts(ctx context.Context, appID xid.ID) ([]*TravelAlert, error)

func (*BunRepository) GetRule ΒΆ

func (r *BunRepository) GetRule(ctx context.Context, id xid.ID) (*GeofenceRule, error)

func (*BunRepository) GetRulesByApp ΒΆ added in v0.0.6

func (r *BunRepository) GetRulesByApp(ctx context.Context, appID xid.ID) ([]*GeofenceRule, error)

func (*BunRepository) GetRulesByUser ΒΆ

func (r *BunRepository) GetRulesByUser(ctx context.Context, userID xid.ID) ([]*GeofenceRule, error)

func (*BunRepository) GetTravelAlert ΒΆ

func (r *BunRepository) GetTravelAlert(ctx context.Context, id xid.ID) (*TravelAlert, error)

func (*BunRepository) GetTrustedLocation ΒΆ

func (r *BunRepository) GetTrustedLocation(ctx context.Context, id xid.ID) (*TrustedLocation, error)

func (*BunRepository) GetUnresolvedViolations ΒΆ

func (r *BunRepository) GetUnresolvedViolations(ctx context.Context, appID xid.ID) ([]*GeofenceViolation, error)

func (*BunRepository) GetUserLocationHistory ΒΆ

func (r *BunRepository) GetUserLocationHistory(ctx context.Context, userID xid.ID, limit int) ([]*LocationEvent, error)

func (*BunRepository) GetUserTravelAlerts ΒΆ

func (r *BunRepository) GetUserTravelAlerts(ctx context.Context, userID xid.ID, status string) ([]*TravelAlert, error)

func (*BunRepository) GetUserTrustedLocations ΒΆ

func (r *BunRepository) GetUserTrustedLocations(ctx context.Context, userID xid.ID) ([]*TrustedLocation, error)

func (*BunRepository) GetUserViolations ΒΆ

func (r *BunRepository) GetUserViolations(ctx context.Context, userID xid.ID, limit int) ([]*GeofenceViolation, error)

func (*BunRepository) GetViolation ΒΆ

func (r *BunRepository) GetViolation(ctx context.Context, id xid.ID) (*GeofenceViolation, error)

func (*BunRepository) IsLocationTrusted ΒΆ

func (r *BunRepository) IsLocationTrusted(ctx context.Context, userID xid.ID, lat, lon float64) (bool, *TrustedLocation, error)

func (*BunRepository) ListEnabledRules ΒΆ

func (r *BunRepository) ListEnabledRules(ctx context.Context, appID xid.ID, userID *xid.ID) ([]*GeofenceRule, error)

func (*BunRepository) ResolveViolation ΒΆ

func (r *BunRepository) ResolveViolation(ctx context.Context, id xid.ID, resolvedBy xid.ID, resolution string) error

func (*BunRepository) SetCachedGeoData ΒΆ

func (r *BunRepository) SetCachedGeoData(ctx context.Context, cache *GeoCache) error

func (*BunRepository) UpdateRule ΒΆ

func (r *BunRepository) UpdateRule(ctx context.Context, rule *GeofenceRule) error

func (*BunRepository) UpdateTravelAlert ΒΆ

func (r *BunRepository) UpdateTravelAlert(ctx context.Context, alert *TravelAlert) error

func (*BunRepository) UpdateTrustedLocation ΒΆ

func (r *BunRepository) UpdateTrustedLocation(ctx context.Context, location *TrustedLocation) error

type CachedDetection ΒΆ

type CachedDetection struct {
	Data      *DetectionResult
	ExpiresAt time.Time
}

CachedDetection represents cached detection data

type CachedGeo ΒΆ

type CachedGeo struct {
	Data      *GeoData
	ExpiresAt time.Time
}

CachedGeo represents cached geolocation data

type Config ΒΆ

type Config struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Geographic Restrictions
	Restrictions RestrictionConfig `json:"restrictions" yaml:"restrictions"`

	// IP Geolocation
	Geolocation GeolocationConfig `json:"geolocation" yaml:"geolocation"`

	// GPS-Based Authentication
	GPS GPSConfig `json:"gps" yaml:"gps"`

	// VPN/Proxy Detection
	Detection DetectionConfig `json:"detection" yaml:"detection"`

	// Corporate Network Detection
	Corporate CorporateConfig `json:"corporate" yaml:"corporate"`

	// Travel Notifications
	Travel TravelConfig `json:"travel" yaml:"travel"`

	// Session Management
	Session SessionConfig `json:"session" yaml:"session"`

	// API Endpoints
	API APIConfig `json:"api" yaml:"api"`

	// Security & Audit
	Security SecurityConfig `json:"security" yaml:"security"`

	// Session Security Notifications
	Notifications NotificationConfig `json:"notifications" yaml:"notifications"`
}

Config holds the geofencing plugin configuration

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns the default geofencing configuration

func (*Config) Validate ΒΆ

func (c *Config) Validate() error

Validate validates the configuration

type CorporateConfig ΒΆ

type CorporateConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Network Ranges
	Networks       []string `json:"networks" yaml:"networks"` // CIDR ranges
	RequireNetwork bool     `json:"requireNetwork" yaml:"requireNetwork"`

	// DNS-Based Detection
	RequiredDNS []string `json:"requiredDns" yaml:"requiredDns"` // Expected DNS servers

	// Certificate-Based Detection
	RequireCert  bool     `json:"requireCert" yaml:"requireCert"`
	TrustedCerts []string `json:"trustedCerts" yaml:"trustedCerts"` // Cert fingerprints

	// Hybrid Detection
	AllowExternal bool `json:"allowExternal" yaml:"allowExternal"` // Allow external if other auth strong
	RequireMFA    bool `json:"requireMfa" yaml:"requireMfa"`       // Require MFA for external
}

CorporateConfig configures corporate network detection

type DetectionConfig ΒΆ

type DetectionConfig struct {
	// VPN Detection
	DetectVPN   bool     `json:"detectVpn" yaml:"detectVpn"`
	BlockVPN    bool     `json:"blockVpn" yaml:"blockVpn"`
	AllowedVPNs []string `json:"allowedVpns" yaml:"allowedVpns"` // Whitelisted VPN providers

	// Proxy Detection
	DetectProxy    bool     `json:"detectProxy" yaml:"detectProxy"`
	BlockProxy     bool     `json:"blockProxy" yaml:"blockProxy"`
	AllowedProxies []string `json:"allowedProxies" yaml:"allowedProxies"`

	// Tor Detection
	DetectTor bool `json:"detectTor" yaml:"detectTor"`
	BlockTor  bool `json:"blockTor" yaml:"blockTor"`

	// Datacenter Detection
	DetectDatacenter bool `json:"detectDatacenter" yaml:"detectDatacenter"`
	BlockDatacenter  bool `json:"blockDatacenter" yaml:"blockDatacenter"`

	// Detection Services
	Provider       string            `json:"provider" yaml:"provider"` // ipqs, proxycheck, vpnapi
	ProviderConfig map[string]string `json:"providerConfig" yaml:"providerConfig"`

	// IPQualityScore
	IPQSKey        string  `json:"ipqsKey" yaml:"ipqsKey"`
	IPQSStrictness int     `json:"ipqsStrictness" yaml:"ipqsStrictness"` // 0-3
	IPQSMinScore   float64 `json:"ipqsMinScore" yaml:"ipqsMinScore"`     // 0-100

	// ProxyCheck.io
	ProxyCheckKey string `json:"proxycheckKey" yaml:"proxycheckKey"`

	// VPNapi.io
	VPNAPIKey string `json:"vpnapiKey" yaml:"vpnapiKey"`

	// Caching
	CacheDuration time.Duration `json:"cacheDuration" yaml:"cacheDuration"`
	CacheMaxSize  int           `json:"cacheMaxSize" yaml:"cacheMaxSize"`
}

DetectionConfig configures VPN/proxy detection

type DetectionProvider ΒΆ

type DetectionProvider interface {
	Check(ctx context.Context, ip string) (*DetectionResult, error)
	Name() string
}

DetectionProvider defines the interface for VPN/Proxy/Tor detection

type DetectionResult ΒΆ

type DetectionResult struct {
	IPAddress    string
	IsVPN        bool
	IsProxy      bool
	IsTor        bool
	IsDatacenter bool
	VPNProvider  string
	FraudScore   *float64
	Provider     string
}

DetectionResult represents VPN/proxy detection results

type ErrorResponse ΒΆ

type ErrorResponse = responses.ErrorResponse

Response types - use shared responses from core

type GPSConfig ΒΆ

type GPSConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Coordinate Requirements
	RequireGPS        bool    `json:"requireGps" yaml:"requireGps"`
	MaxAccuracyMeters float64 `json:"maxAccuracyMeters" yaml:"maxAccuracyMeters"`
	MinAccuracyMeters float64 `json:"minAccuracyMeters" yaml:"minAccuracyMeters"`

	// Geofencing
	Geofences          []Geofence `json:"geofences" yaml:"geofences"`
	RequireInsideFence bool       `json:"requireInsideFence" yaml:"requireInsideFence"`

	// Movement Detection
	MaxSpeedKmh    float64       `json:"maxSpeedKmh" yaml:"maxSpeedKmh"` // Alert on impossible travel speed
	MinTimeBetween time.Duration `json:"minTimeBetween" yaml:"minTimeBetween"`

	// Validation
	ValidateTimestamp bool          `json:"validateTimestamp" yaml:"validateTimestamp"`
	MaxTimestampAge   time.Duration `json:"maxTimestampAge" yaml:"maxTimestampAge"`
}

GPSConfig configures GPS-based authentication

type GPSData ΒΆ

type GPSData struct {
	Latitude       float64
	Longitude      float64
	AccuracyMeters float64
	Timestamp      time.Time
}

GPSData represents GPS coordinates from a device

type GeoCache ΒΆ

type GeoCache struct {
	bun.BaseModel `bun:"table:geo_cache,alias:gc"`

	IPAddress string `bun:"ip_address,pk,notnull" json:"ipAddress"`

	// Geolocation Data
	Country     string   `bun:"country" json:"country"`
	CountryCode string   `bun:"country_code" json:"countryCode"`
	Region      string   `bun:"region" json:"region"`
	City        string   `bun:"city" json:"city"`
	Latitude    *float64 `bun:"latitude" json:"latitude,omitempty"`
	Longitude   *float64 `bun:"longitude" json:"longitude,omitempty"`
	AccuracyKm  *float64 `bun:"accuracy_km" json:"accuracyKm,omitempty"`

	// Detection Data
	IsVPN        bool     `bun:"is_vpn" json:"isVpn"`
	IsProxy      bool     `bun:"is_proxy" json:"isProxy"`
	IsTor        bool     `bun:"is_tor" json:"isTor"`
	IsDatacenter bool     `bun:"is_datacenter" json:"isDatacenter"`
	VPNProvider  string   `bun:"vpn_provider" json:"vpnProvider,omitempty"`
	FraudScore   *float64 `bun:"fraud_score" json:"fraudScore,omitempty"`

	// Network Info
	ASN          string `bun:"asn" json:"asn,omitempty"`
	ISP          string `bun:"isp" json:"isp,omitempty"`
	Organization string `bun:"organization" json:"organization,omitempty"`

	// Cache Metadata
	Provider  string    `bun:"provider,notnull" json:"provider"` // Which provider gave us this data
	CachedAt  time.Time `bun:"cached_at,notnull,default:current_timestamp" json:"cachedAt"`
	ExpiresAt time.Time `bun:"expires_at,notnull" json:"expiresAt"`
	HitCount  int       `bun:"hit_count" json:"hitCount"`
}

GeoCache represents cached geolocation data

type GeoData ΒΆ

type GeoData struct {
	IPAddress    string
	Country      string
	CountryCode  string // ISO 3166-1 alpha-2
	Region       string
	City         string
	Latitude     *float64
	Longitude    *float64
	AccuracyKm   *float64
	ASN          string
	ISP          string
	Organization string
	Provider     string
}

GeoData represents geolocation information

type GeoProvider ΒΆ

type GeoProvider interface {
	Lookup(ctx context.Context, ip string) (*GeoData, error)
	Name() string
}

GeoProvider defines the interface for geolocation providers

type Geofence ΒΆ

type Geofence struct {
	ID          string `json:"id" yaml:"id"`
	Name        string `json:"name" yaml:"name"`
	Description string `json:"description" yaml:"description"`
	Type        string `json:"type" yaml:"type"` // "circle", "polygon"

	// Circle
	CenterLat float64 `json:"centerLat" yaml:"centerLat"`
	CenterLon float64 `json:"centerLon" yaml:"centerLon"`
	RadiusKm  float64 `json:"radiusKm" yaml:"radiusKm"`

	// Polygon (array of [lat, lon] pairs)
	Coordinates [][2]float64 `json:"coordinates" yaml:"coordinates"`

	// Rules
	Action string   `json:"action" yaml:"action"` // "allow" or "deny"
	Users  []string `json:"users" yaml:"users"`   // Specific user IDs (empty = all)
	Roles  []string `json:"roles" yaml:"roles"`   // Specific roles (empty = all)
}

Geofence defines a geographic boundary

type GeofenceCheckResponse ΒΆ

type GeofenceCheckResponse struct {
	Allowed bool   `json:"allowed" example:"true"`
	Country string `json:"country,omitempty" example:"US"`
}

type GeofenceErrorResponse ΒΆ

type GeofenceErrorResponse struct {
	Error string `json:"error" example:"Error message"`
}

DTOs for geofence routes

type GeofenceEventResponse ΒΆ

type GeofenceEventResponse struct {
	ID string `json:"id" example:"event_123"`
}

type GeofenceEventsResponse ΒΆ

type GeofenceEventsResponse struct {
	Events []interface{} `json:"events"`
}

type GeofenceLocationAnalyticsResponse ΒΆ

type GeofenceLocationAnalyticsResponse struct {
	Analytics interface{} `json:"analytics"`
}

type GeofenceLookupResponse ΒΆ

type GeofenceLookupResponse struct {
	Country   string  `json:"country" example:"US"`
	City      string  `json:"city,omitempty" example:"San Francisco"`
	Latitude  float64 `json:"latitude,omitempty" example:"37.7749"`
	Longitude float64 `json:"longitude,omitempty" example:"-122.4194"`
}

type GeofenceMetricsResponse ΒΆ

type GeofenceMetricsResponse struct {
	Metrics interface{} `json:"metrics"`
}

type GeofenceRule ΒΆ

type GeofenceRule struct {
	bun.BaseModel `bun:"table:geofence_rules,alias:gr"`

	ID          xid.ID  `bun:"id,pk,type:varchar(20)" json:"id"`
	AppID       xid.ID  `bun:"app_id,type:varchar(20),notnull" json:"appId"`
	UserID      *xid.ID `bun:"user_id,type:varchar(20)" json:"userId,omitempty"` // Null = app-wide
	Name        string  `bun:"name,notnull" json:"name"`
	Description string  `bun:"description" json:"description"`
	Enabled     bool    `bun:"enabled,notnull" json:"enabled"`
	Priority    int     `bun:"priority,notnull" json:"priority"` // Higher = evaluated first

	// Rule Type
	RuleType string `bun:"rule_type,notnull" json:"ruleType"` // country, region, city, geofence, distance

	// Geographic Criteria (JSON)
	AllowedCountries []string `bun:"allowed_countries,type:jsonb" json:"allowedCountries,omitempty"`
	BlockedCountries []string `bun:"blocked_countries,type:jsonb" json:"blockedCountries,omitempty"`
	AllowedRegions   []string `bun:"allowed_regions,type:jsonb" json:"allowedRegions,omitempty"`
	BlockedRegions   []string `bun:"blocked_regions,type:jsonb" json:"blockedRegions,omitempty"`
	AllowedCities    []string `bun:"allowed_cities,type:jsonb" json:"allowedCities,omitempty"`
	BlockedCities    []string `bun:"blocked_cities,type:jsonb" json:"blockedCities,omitempty"`

	// Geofence Data (JSON)
	GeofenceType string       `bun:"geofence_type" json:"geofenceType,omitempty"` // circle, polygon
	CenterLat    *float64     `bun:"center_lat" json:"centerLat,omitempty"`
	CenterLon    *float64     `bun:"center_lon" json:"centerLon,omitempty"`
	RadiusKm     *float64     `bun:"radius_km" json:"radiusKm,omitempty"`
	Coordinates  [][2]float64 `bun:"coordinates,type:jsonb" json:"coordinates,omitempty"`

	// Distance Restrictions
	MaxDistanceKm  *float64    `bun:"max_distance_km" json:"maxDistanceKm,omitempty"`
	ReferencePoint *[2]float64 `bun:"reference_point,type:jsonb" json:"referencePoint,omitempty"` // [lat, lon]

	// Time Restrictions (JSON)
	TimeRestrictions []TimeRestrictionRule `bun:"time_restrictions,type:jsonb" json:"timeRestrictions,omitempty"`

	// Detection Settings
	BlockVPN        bool `bun:"block_vpn" json:"blockVpn"`
	BlockProxy      bool `bun:"block_proxy" json:"blockProxy"`
	BlockTor        bool `bun:"block_tor" json:"blockTor"`
	BlockDatacenter bool `bun:"block_datacenter" json:"blockDatacenter"`

	// Actions
	Action      string `bun:"action,notnull" json:"action"` // allow, deny, mfa_required, notify
	RequireMFA  bool   `bun:"require_mfa" json:"requireMfa"`
	NotifyUser  bool   `bun:"notify_user" json:"notifyUser"`
	NotifyAdmin bool   `bun:"notify_admin" json:"notifyAdmin"`

	// Metadata
	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	CreatedBy xid.ID    `bun:"created_by,type:varchar(20)" json:"createdBy"`
	UpdatedBy *xid.ID   `bun:"updated_by,type:varchar(20)" json:"updatedBy,omitempty"`
}

GeofenceRule represents a geographic restriction rule

type GeofenceRuleResponse ΒΆ

type GeofenceRuleResponse struct {
	ID string `json:"id" example:"rule_123"`
}

type GeofenceRulesResponse ΒΆ

type GeofenceRulesResponse struct {
	Rules []interface{} `json:"rules"`
}

type GeofenceStatusResponse ΒΆ

type GeofenceStatusResponse struct {
	Status string `json:"status" example:"success"`
}

type GeofenceTravelAlertResponse ΒΆ

type GeofenceTravelAlertResponse struct {
	ID string `json:"id" example:"alert_123"`
}

type GeofenceTravelAlertsResponse ΒΆ

type GeofenceTravelAlertsResponse struct {
	TravelAlerts []interface{} `json:"travel_alerts"`
}

type GeofenceTrustedLocationResponse ΒΆ

type GeofenceTrustedLocationResponse struct {
	ID string `json:"id" example:"trusted_123"`
}

type GeofenceTrustedLocationsResponse ΒΆ

type GeofenceTrustedLocationsResponse struct {
	TrustedLocations []interface{} `json:"trusted_locations"`
}

type GeofenceViolation ΒΆ

type GeofenceViolation struct {
	bun.BaseModel `bun:"table:geofence_violations,alias:gv"`

	ID     xid.ID `bun:"id,pk,type:varchar(20)" json:"id"`
	UserID xid.ID `bun:"user_id,type:varchar(20),notnull" json:"userId"`
	AppID  xid.ID `bun:"app_id,type:varchar(20),notnull" json:"appId"`
	RuleID xid.ID `bun:"rule_id,type:varchar(20),notnull" json:"ruleId"`

	// Violation Details
	ViolationType string `bun:"violation_type,notnull" json:"violationType"` // blocked_country, vpn_detected, etc.
	Severity      string `bun:"severity,notnull" json:"severity"`            // low, medium, high, critical
	Action        string `bun:"action,notnull" json:"action"`                // blocked, flagged, mfa_required

	// Location Context
	IPAddress   string   `bun:"ip_address,notnull" json:"ipAddress"`
	Country     string   `bun:"country" json:"country"`
	CountryCode string   `bun:"country_code" json:"countryCode"`
	City        string   `bun:"city" json:"city"`
	Latitude    *float64 `bun:"latitude" json:"latitude,omitempty"`
	Longitude   *float64 `bun:"longitude" json:"longitude,omitempty"`

	// Detection Info
	IsVPN        bool `bun:"is_vpn" json:"isVpn"`
	IsProxy      bool `bun:"is_proxy" json:"isProxy"`
	IsTor        bool `bun:"is_tor" json:"isTor"`
	IsDatacenter bool `bun:"is_datacenter" json:"isDatacenter"`

	// Response
	Blocked       bool `bun:"blocked" json:"blocked"`
	UserNotified  bool `bun:"user_notified" json:"userNotified"`
	AdminNotified bool `bun:"admin_notified" json:"adminNotified"`

	// Resolution
	Resolved   bool       `bun:"resolved" json:"resolved"`
	ResolvedAt *time.Time `bun:"resolved_at" json:"resolvedAt,omitempty"`
	ResolvedBy *xid.ID    `bun:"resolved_by,type:varchar(20)" json:"resolvedBy,omitempty"`
	Resolution string     `bun:"resolution" json:"resolution,omitempty"`

	// References
	LocationEventID *xid.ID `bun:"location_event_id,type:varchar(20)" json:"locationEventId,omitempty"`
	SessionID       *xid.ID `bun:"session_id,type:varchar(20)" json:"sessionId,omitempty"`

	// Metadata
	CreatedAt time.Time              `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time              `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	Metadata  map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`
}

GeofenceViolation represents a geofence policy violation

type GeofenceViolationAnalyticsResponse ΒΆ

type GeofenceViolationAnalyticsResponse struct {
	Analytics interface{} `json:"analytics"`
}

type GeofenceViolationResponse ΒΆ

type GeofenceViolationResponse struct {
	ID string `json:"id" example:"violation_123"`
}

type GeofenceViolationsResponse ΒΆ

type GeofenceViolationsResponse struct {
	Violations []interface{} `json:"violations"`
}

type GeolocationConfig ΒΆ

type GeolocationConfig struct {
	// Primary Provider
	Provider         string            `json:"provider" yaml:"provider"` // maxmind, ipapi, ipinfo, ipgeolocation
	ProviderConfig   map[string]string `json:"providerConfig" yaml:"providerConfig"`
	FallbackProvider string            `json:"fallbackProvider" yaml:"fallbackProvider"`

	// MaxMind GeoIP2
	MaxMindLicenseKey   string `json:"maxmindLicenseKey" yaml:"maxmindLicenseKey"`
	MaxMindDatabasePath string `json:"maxmindDatabasePath" yaml:"maxmindDatabasePath"`
	MaxMindAutoUpdate   bool   `json:"maxmindAutoUpdate" yaml:"maxmindAutoUpdate"`

	// IPInfo.io
	IPInfoToken string `json:"ipinfoToken" yaml:"ipinfoToken"`

	// ipapi.com
	IPAPIKey string `json:"ipapiKey" yaml:"ipapiKey"`

	// ipgeolocation.io
	IPGeolocationKey string `json:"ipgeolocationKey" yaml:"ipgeolocationKey"`

	// Caching
	CacheDuration time.Duration `json:"cacheDuration" yaml:"cacheDuration"`
	CacheMaxSize  int           `json:"cacheMaxSize" yaml:"cacheMaxSize"`

	// Performance
	Timeout    time.Duration `json:"timeout" yaml:"timeout"`
	MaxRetries int           `json:"maxRetries" yaml:"maxRetries"`

	// Accuracy Requirements
	MinAccuracyKm float64 `json:"minAccuracyKm" yaml:"minAccuracyKm"` // Minimum accuracy in km
}

GeolocationConfig configures IP geolocation services

type Handler ΒΆ

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

Handler handles HTTP requests for geofencing

func NewHandler ΒΆ

func NewHandler(service *Service, config *Config) *Handler

NewHandler creates a new geofencing handler

func (*Handler) ApproveTravelAlert ΒΆ

func (h *Handler) ApproveTravelAlert(c forge.Context) error

ApproveTravelAlert approves a travel alert

func (*Handler) CheckLocation ΒΆ

func (h *Handler) CheckLocation(c forge.Context) error

CheckLocation performs a geofence check

func (*Handler) CreateRule ΒΆ

func (h *Handler) CreateRule(c forge.Context) error

CreateRule creates a new geofence rule

func (*Handler) CreateTrustedLocation ΒΆ

func (h *Handler) CreateTrustedLocation(c forge.Context) error

CreateTrustedLocation creates a trusted location

func (*Handler) DeleteRule ΒΆ

func (h *Handler) DeleteRule(c forge.Context) error

DeleteRule deletes a geofence rule

func (*Handler) DeleteTrustedLocation ΒΆ

func (h *Handler) DeleteTrustedLocation(c forge.Context) error

DeleteTrustedLocation deletes a trusted location

func (*Handler) DenyTravelAlert ΒΆ

func (h *Handler) DenyTravelAlert(c forge.Context) error

DenyTravelAlert denies a travel alert

func (*Handler) GetLocationAnalytics ΒΆ

func (h *Handler) GetLocationAnalytics(c forge.Context) error

GetLocationAnalytics returns location analytics

func (*Handler) GetLocationEvent ΒΆ

func (h *Handler) GetLocationEvent(c forge.Context) error

GetLocationEvent gets a specific location event

func (*Handler) GetMetrics ΒΆ

func (h *Handler) GetMetrics(c forge.Context) error

GetMetrics returns geofencing metrics

func (*Handler) GetRule ΒΆ

func (h *Handler) GetRule(c forge.Context) error

GetRule gets a specific geofence rule

func (*Handler) GetTravelAlert ΒΆ

func (h *Handler) GetTravelAlert(c forge.Context) error

GetTravelAlert gets a specific travel alert

func (*Handler) GetTrustedLocation ΒΆ

func (h *Handler) GetTrustedLocation(c forge.Context) error

GetTrustedLocation gets a specific trusted location

func (*Handler) GetViolation ΒΆ

func (h *Handler) GetViolation(c forge.Context) error

GetViolation gets a specific violation

func (*Handler) GetViolationAnalytics ΒΆ

func (h *Handler) GetViolationAnalytics(c forge.Context) error

GetViolationAnalytics returns violation analytics

func (*Handler) ListLocationEvents ΒΆ

func (h *Handler) ListLocationEvents(c forge.Context) error

ListLocationEvents lists location events for the authenticated user

func (*Handler) ListRules ΒΆ

func (h *Handler) ListRules(c forge.Context) error

ListRules lists all geofence rules for an organization

func (*Handler) ListTravelAlerts ΒΆ

func (h *Handler) ListTravelAlerts(c forge.Context) error

ListTravelAlerts lists travel alerts for the authenticated user

func (*Handler) ListTrustedLocations ΒΆ

func (h *Handler) ListTrustedLocations(c forge.Context) error

ListTrustedLocations lists trusted locations for the authenticated user

func (*Handler) ListViolations ΒΆ

func (h *Handler) ListViolations(c forge.Context) error

ListViolations lists geofence violations

func (*Handler) LookupIP ΒΆ

func (h *Handler) LookupIP(c forge.Context) error

LookupIP performs IP geolocation lookup

func (*Handler) ResolveViolation ΒΆ

func (h *Handler) ResolveViolation(c forge.Context) error

ResolveViolation resolves a geofence violation

func (*Handler) UpdateRule ΒΆ

func (h *Handler) UpdateRule(c forge.Context) error

UpdateRule updates a geofence rule

func (*Handler) UpdateTrustedLocation ΒΆ

func (h *Handler) UpdateTrustedLocation(c forge.Context) error

UpdateTrustedLocation updates a trusted location

type IPAPIProvider ΒΆ

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

IPAPIProvider implements GeoProvider using ipapi.com

func NewIPAPIProvider ΒΆ

func NewIPAPIProvider(apiKey string) *IPAPIProvider

NewIPAPIProvider creates a new ipapi.com provider

func (*IPAPIProvider) Lookup ΒΆ

func (p *IPAPIProvider) Lookup(ctx context.Context, ip string) (*GeoData, error)

func (*IPAPIProvider) Name ΒΆ

func (p *IPAPIProvider) Name() string

type IPGeolocationProvider ΒΆ

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

IPGeolocationProvider implements GeoProvider using ipgeolocation.io

func NewIPGeolocationProvider ΒΆ

func NewIPGeolocationProvider(apiKey string) *IPGeolocationProvider

NewIPGeolocationProvider creates a new ipgeolocation.io provider

func (*IPGeolocationProvider) Lookup ΒΆ

func (p *IPGeolocationProvider) Lookup(ctx context.Context, ip string) (*GeoData, error)

func (*IPGeolocationProvider) Name ΒΆ

func (p *IPGeolocationProvider) Name() string

type IPInfoProvider ΒΆ

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

IPInfoProvider implements GeoProvider using ipinfo.io

func NewIPInfoProvider ΒΆ

func NewIPInfoProvider(token string) *IPInfoProvider

NewIPInfoProvider creates a new ipinfo.io provider

func (*IPInfoProvider) Lookup ΒΆ

func (p *IPInfoProvider) Lookup(ctx context.Context, ip string) (*GeoData, error)

func (*IPInfoProvider) Name ΒΆ

func (p *IPInfoProvider) Name() string

type IPQSProvider ΒΆ

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

IPQSProvider implements DetectionProvider using IPQualityScore

func NewIPQSProvider ΒΆ

func NewIPQSProvider(apiKey string, strictness int, minScore float64) *IPQSProvider

NewIPQSProvider creates a new IPQualityScore provider

func (*IPQSProvider) Check ΒΆ

func (p *IPQSProvider) Check(ctx context.Context, ip string) (*DetectionResult, error)

func (*IPQSProvider) Name ΒΆ

func (p *IPQSProvider) Name() string

type LocationCheckRequest ΒΆ

type LocationCheckRequest struct {
	UserID    xid.ID
	AppID     xid.ID
	SessionID *xid.ID
	IPAddress string
	UserAgent string
	EventType string // "login", "request", "manual_check"
	GPS       *GPSData
}

LocationCheckRequest represents a geofence check request

type LocationCheckResult ΒΆ

type LocationCheckResult struct {
	Allowed       bool
	Reason        string
	RuleName      string
	RequireMFA    bool
	Notify        bool
	Violations    []string
	TravelAlert   bool
	TravelAlertID *xid.ID
}

LocationCheckResult represents the result of a geofence check

type LocationEvent ΒΆ

type LocationEvent struct {
	bun.BaseModel `bun:"table:location_events,alias:le"`

	ID        xid.ID  `bun:"id,pk,type:varchar(20)" json:"id"`
	UserID    xid.ID  `bun:"user_id,type:varchar(20),notnull" json:"userId"`
	AppID     xid.ID  `bun:"app_id,type:varchar(20),notnull" json:"appId"`
	SessionID *xid.ID `bun:"session_id,type:varchar(20)" json:"sessionId,omitempty"`

	// Location Data
	IPAddress   string   `bun:"ip_address,notnull" json:"ipAddress"`
	Country     string   `bun:"country" json:"country"`
	CountryCode string   `bun:"country_code" json:"countryCode"` // ISO 3166-1 alpha-2
	Region      string   `bun:"region" json:"region"`
	City        string   `bun:"city" json:"city"`
	Latitude    *float64 `bun:"latitude" json:"latitude,omitempty"`
	Longitude   *float64 `bun:"longitude" json:"longitude,omitempty"`
	AccuracyKm  *float64 `bun:"accuracy_km" json:"accuracyKm,omitempty"`

	// GPS Data (if available)
	GPSLatitude  *float64   `bun:"gps_latitude" json:"gpsLatitude,omitempty"`
	GPSLongitude *float64   `bun:"gps_longitude" json:"gpsLongitude,omitempty"`
	GPSAccuracy  *float64   `bun:"gps_accuracy" json:"gpsAccuracy,omitempty"` // meters
	GPSTimestamp *time.Time `bun:"gps_timestamp" json:"gpsTimestamp,omitempty"`

	// Detection Results
	IsVPN        bool     `bun:"is_vpn" json:"isVpn"`
	IsProxy      bool     `bun:"is_proxy" json:"isProxy"`
	IsTor        bool     `bun:"is_tor" json:"isTor"`
	IsDatacenter bool     `bun:"is_datacenter" json:"isDatacenter"`
	VPNProvider  string   `bun:"vpn_provider" json:"vpnProvider,omitempty"`
	FraudScore   *float64 `bun:"fraud_score" json:"fraudScore,omitempty"`

	// Network Info
	ASN            string `bun:"asn" json:"asn,omitempty"`
	ISP            string `bun:"isp" json:"isp,omitempty"`
	Organization   string `bun:"organization" json:"organization,omitempty"`
	ConnectionType string `bun:"connection_type" json:"connectionType,omitempty"` // cable, cellular, etc.

	// Context
	UserAgent   string `bun:"user_agent" json:"userAgent,omitempty"`
	EventType   string `bun:"event_type,notnull" json:"eventType"`     // login, request, manual_check
	EventResult string `bun:"event_result,notnull" json:"eventResult"` // allowed, denied, flagged
	RuleName    string `bun:"rule_name" json:"ruleName,omitempty"`     // Which rule triggered

	// Distance from previous location
	DistanceKm   *float64       `bun:"distance_km" json:"distanceKm,omitempty"`
	TimeFromPrev *time.Duration `bun:"time_from_prev" json:"timeFromPrev,omitempty"`
	SpeedKmh     *float64       `bun:"speed_kmh" json:"speedKmh,omitempty"` // Calculated speed

	// Metadata
	Timestamp time.Time              `bun:"timestamp,notnull,default:current_timestamp" json:"timestamp"`
	Metadata  map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`
}

LocationEvent represents a recorded location event

type MaxMindProvider ΒΆ

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

MaxMindProvider implements GeoProvider using MaxMind GeoIP2

func NewMaxMindProvider ΒΆ

func NewMaxMindProvider(licenseKey, databasePath string) *MaxMindProvider

NewMaxMindProvider creates a new MaxMind provider

func (*MaxMindProvider) Lookup ΒΆ

func (p *MaxMindProvider) Lookup(ctx context.Context, ip string) (*GeoData, error)

func (*MaxMindProvider) Name ΒΆ

func (p *MaxMindProvider) Name() string

type MessageResponse ΒΆ

type MessageResponse = responses.MessageResponse

type Middleware ΒΆ

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

Middleware provides geofence checking middleware

func NewMiddleware ΒΆ

func NewMiddleware(service *Service, config *Config) *Middleware

NewMiddleware creates a new geofence middleware

func (*Middleware) BlockProxy ΒΆ

func (m *Middleware) BlockProxy(next func(forge.Context) error) func(forge.Context) error

BlockProxy middleware blocks requests from proxies

func (*Middleware) BlockTor ΒΆ

func (m *Middleware) BlockTor(next func(forge.Context) error) func(forge.Context) error

BlockTor middleware blocks requests from Tor exit nodes

func (*Middleware) BlockVPN ΒΆ

func (m *Middleware) BlockVPN(next func(forge.Context) error) func(forge.Context) error

BlockVPN middleware blocks requests from VPNs

func (*Middleware) CheckGeofence ΒΆ

func (m *Middleware) CheckGeofence(next func(forge.Context) error) func(forge.Context) error

CheckGeofence middleware checks geofence rules for each request

func (*Middleware) RequireCountry ΒΆ

func (m *Middleware) RequireCountry(countries ...string) func(next func(forge.Context) error) func(forge.Context) error

RequireCountry middleware requires the request to come from specific countries

func (*Middleware) RequireLocation ΒΆ

func (m *Middleware) RequireLocation(next func(forge.Context) error) func(forge.Context) error

RequireLocation middleware requires geofence check to pass This is a stronger enforcement than CheckGeofence

type NotificationConfig ΒΆ added in v0.0.6

type NotificationConfig struct {
	// General
	Enabled bool `json:"enabled" yaml:"enabled"`

	// New Location Notifications
	NewLocationEnabled     bool    `json:"newLocationEnabled" yaml:"newLocationEnabled"`
	NewLocationThresholdKm float64 `json:"newLocationThresholdKm" yaml:"newLocationThresholdKm"` // Trigger at N km distance

	// Suspicious Login Notifications
	SuspiciousLoginEnabled        bool    `json:"suspiciousLoginEnabled" yaml:"suspiciousLoginEnabled"`
	SuspiciousLoginScoreThreshold float64 `json:"suspiciousLoginScoreThreshold" yaml:"suspiciousLoginScoreThreshold"` // IPQS fraud score threshold

	// Detection Types
	ImpossibleTravelEnabled bool `json:"impossibleTravelEnabled" yaml:"impossibleTravelEnabled"`
	VpnDetectionEnabled     bool `json:"vpnDetectionEnabled" yaml:"vpnDetectionEnabled"`
	ProxyDetectionEnabled   bool `json:"proxyDetectionEnabled" yaml:"proxyDetectionEnabled"`
	TorDetectionEnabled     bool `json:"torDetectionEnabled" yaml:"torDetectionEnabled"`
}

NotificationConfig configures session security notifications

type Plugin ΒΆ

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

Plugin implements the AuthSome plugin interface for geofencing

func NewPlugin ΒΆ

func NewPlugin() *Plugin

NewPlugin creates a new geofencing plugin

func (*Plugin) Config ΒΆ

func (p *Plugin) Config() *Config

Config returns the plugin configuration

func (*Plugin) Description ΒΆ

func (p *Plugin) Description() string

Description returns the plugin description

func (*Plugin) Health ΒΆ

func (p *Plugin) Health(ctx context.Context) error

Health checks plugin health

func (*Plugin) ID ΒΆ

func (p *Plugin) ID() string

ID returns the plugin identifier

func (*Plugin) Init ΒΆ

func (p *Plugin) Init(auth interface{}) error

Init initializes the plugin with AuthSome dependencies

func (*Plugin) Middleware ΒΆ

func (p *Plugin) Middleware() func(next func(forge.Context) error) func(forge.Context) error

Middleware returns the geofence middleware for automatic checks

func (*Plugin) Migrate ΒΆ

func (p *Plugin) Migrate() error

Migrate performs database migrations

func (*Plugin) Name ΒΆ

func (p *Plugin) Name() string

Name returns the plugin name

func (*Plugin) RegisterHooks ΒΆ

func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error

RegisterHooks registers plugin hooks with the hook registry

func (*Plugin) RegisterRoutes ΒΆ

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes registers HTTP routes for the plugin

func (*Plugin) RegisterServiceDecorators ΒΆ

func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error

RegisterServiceDecorators allows plugins to replace core services with decorated versions

func (*Plugin) Service ΒΆ

func (p *Plugin) Service() *Service

Service returns the geofencing service for direct access

func (*Plugin) Shutdown ΒΆ

func (p *Plugin) Shutdown(ctx context.Context) error

Shutdown cleanly shuts down the plugin

func (*Plugin) Version ΒΆ

func (p *Plugin) Version() string

Version returns the plugin version

type ProxyCheckProvider ΒΆ

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

ProxyCheckProvider implements DetectionProvider using proxycheck.io

func NewProxyCheckProvider ΒΆ

func NewProxyCheckProvider(apiKey string) *ProxyCheckProvider

NewProxyCheckProvider creates a new proxycheck.io provider

func (*ProxyCheckProvider) Check ΒΆ

func (*ProxyCheckProvider) Name ΒΆ

func (p *ProxyCheckProvider) Name() string

type Repository ΒΆ

type Repository interface {
	// Rules
	CreateRule(ctx context.Context, rule *GeofenceRule) error
	GetRule(ctx context.Context, id xid.ID) (*GeofenceRule, error)
	GetRulesByApp(ctx context.Context, appID xid.ID) ([]*GeofenceRule, error)
	GetRulesByUser(ctx context.Context, userID xid.ID) ([]*GeofenceRule, error)
	UpdateRule(ctx context.Context, rule *GeofenceRule) error
	DeleteRule(ctx context.Context, id xid.ID) error
	ListEnabledRules(ctx context.Context, appID xid.ID, userID *xid.ID) ([]*GeofenceRule, error)

	// Location Events
	CreateLocationEvent(ctx context.Context, event *LocationEvent) error
	GetLocationEvent(ctx context.Context, id xid.ID) (*LocationEvent, error)
	GetUserLocationHistory(ctx context.Context, userID xid.ID, limit int) ([]*LocationEvent, error)
	GetLastLocationEvent(ctx context.Context, userID xid.ID) (*LocationEvent, error)
	GetLastLocation(ctx context.Context, userID xid.ID, appID xid.ID) (*GeoData, error)
	DeleteOldLocationEvents(ctx context.Context, before time.Time) (int64, error)

	// Travel Alerts
	CreateTravelAlert(ctx context.Context, alert *TravelAlert) error
	GetTravelAlert(ctx context.Context, id xid.ID) (*TravelAlert, error)
	GetUserTravelAlerts(ctx context.Context, userID xid.ID, status string) ([]*TravelAlert, error)
	GetPendingTravelAlerts(ctx context.Context, appID xid.ID) ([]*TravelAlert, error)
	UpdateTravelAlert(ctx context.Context, alert *TravelAlert) error
	ApproveTravel(ctx context.Context, alertID xid.ID, approvedBy xid.ID) error
	DenyTravel(ctx context.Context, alertID xid.ID, deniedBy xid.ID) error

	// Trusted Locations
	CreateTrustedLocation(ctx context.Context, location *TrustedLocation) error
	GetTrustedLocation(ctx context.Context, id xid.ID) (*TrustedLocation, error)
	GetUserTrustedLocations(ctx context.Context, userID xid.ID) ([]*TrustedLocation, error)
	UpdateTrustedLocation(ctx context.Context, location *TrustedLocation) error
	DeleteTrustedLocation(ctx context.Context, id xid.ID) error
	IsLocationTrusted(ctx context.Context, userID xid.ID, lat, lon float64) (bool, *TrustedLocation, error)

	// Violations
	CreateViolation(ctx context.Context, violation *GeofenceViolation) error
	GetViolation(ctx context.Context, id xid.ID) (*GeofenceViolation, error)
	GetUserViolations(ctx context.Context, userID xid.ID, limit int) ([]*GeofenceViolation, error)
	GetAppViolations(ctx context.Context, appID xid.ID, limit int) ([]*GeofenceViolation, error)
	GetUnresolvedViolations(ctx context.Context, appID xid.ID) ([]*GeofenceViolation, error)
	ResolveViolation(ctx context.Context, id xid.ID, resolvedBy xid.ID, resolution string) error

	// Geo Cache
	GetCachedGeoData(ctx context.Context, ip string) (*GeoCache, error)
	SetCachedGeoData(ctx context.Context, cache *GeoCache) error
	DeleteExpiredCache(ctx context.Context) (int64, error)
}

Repository defines the interface for geofence data storage

func NewBunRepository ΒΆ

func NewBunRepository(db *bun.DB) Repository

NewBunRepository creates a new Bun-based repository

type RestrictionConfig ΒΆ

type RestrictionConfig struct {
	// Country/Region Controls
	AllowedCountries []string `json:"allowedCountries" yaml:"allowedCountries"` // ISO 3166-1 alpha-2
	BlockedCountries []string `json:"blockedCountries" yaml:"blockedCountries"` // ISO 3166-1 alpha-2
	AllowedRegions   []string `json:"allowedRegions" yaml:"allowedRegions"`     // US: state codes, etc.
	BlockedRegions   []string `json:"blockedRegions" yaml:"blockedRegions"`

	// City-Level Controls
	AllowedCities []string `json:"allowedCities" yaml:"allowedCities"`
	BlockedCities []string `json:"blockedCities" yaml:"blockedCities"`

	// Time-Based Restrictions
	TimeRestrictions []TimeRestriction `json:"timeRestrictions" yaml:"timeRestrictions"`

	// Distance-Based Restrictions
	MaxDistanceKm float64 `json:"maxDistanceKm" yaml:"maxDistanceKm"` // Max distance from reference point

	// Behavior
	DefaultAction string `json:"defaultAction" yaml:"defaultAction"` // "allow" or "deny"
	StrictMode    bool   `json:"strictMode" yaml:"strictMode"`       // Deny on lookup failure
}

RestrictionConfig configures geographic restrictions

type RulesResponse ΒΆ

type RulesResponse struct {
	Rules interface{} `json:"rules"`
	Count int         `json:"count"`
}

type SecurityConfig ΒΆ

type SecurityConfig struct {
	// Rate Limiting
	RateLimitEnabled   bool `json:"rateLimitEnabled" yaml:"rateLimitEnabled"`
	MaxChecksPerMinute int  `json:"maxChecksPerMinute" yaml:"maxChecksPerMinute"`
	MaxChecksPerHour   int  `json:"maxChecksPerHour" yaml:"maxChecksPerHour"`

	// Audit Logging
	AuditAllChecks  bool `json:"auditAllChecks" yaml:"auditAllChecks"`
	AuditViolations bool `json:"auditViolations" yaml:"auditViolations"`
	AuditTravel     bool `json:"auditTravel" yaml:"auditTravel"`

	// Data Storage
	StoreLocations    bool          `json:"storeLocations" yaml:"storeLocations"`
	LocationRetention time.Duration `json:"locationRetention" yaml:"locationRetention"`
	AnonymizeOldData  bool          `json:"anonymizeOldData" yaml:"anonymizeOldData"`

	// Privacy
	ConsentRequired bool `json:"consentRequired" yaml:"consentRequired"`
	AllowOptOut     bool `json:"allowOptOut" yaml:"allowOptOut"`

	// Notifications
	NotifyOnViolation bool `json:"notifyOnViolation" yaml:"notifyOnViolation"`
	NotifyOnAnomaly   bool `json:"notifyOnAnomaly" yaml:"notifyOnAnomaly"`
}

SecurityConfig configures security settings

type Service ΒΆ

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

Service handles geofencing operations

func NewService ΒΆ

func NewService(
	config *Config,
	repo Repository,
	geoProvider GeoProvider,
	detectionProvider DetectionProvider,
	auditService *audit.Service,
	notificationService *notification.Service,
	authInst interface{},
) *Service

NewService creates a new geofencing service

func (*Service) CheckLocation ΒΆ

func (s *Service) CheckLocation(ctx context.Context, req *LocationCheckRequest) (*LocationCheckResult, error)

CheckLocation performs a comprehensive geofence check

func (*Service) CheckSessionSecurity ΒΆ added in v0.0.6

func (s *Service) CheckSessionSecurity(ctx context.Context, userID xid.ID, appID xid.ID, ipAddress string) error

CheckSessionSecurity performs location and security checks for a session

func (*Service) GetDetection ΒΆ

func (s *Service) GetDetection(ctx context.Context, ip string) (*DetectionResult, error)

GetDetection gets VPN/proxy detection data for an IP address

func (*Service) GetGeolocation ΒΆ

func (s *Service) GetGeolocation(ctx context.Context, ip string) (*GeoData, error)

GetGeolocation gets geolocation data for an IP address

type SessionConfig ΒΆ

type SessionConfig struct {
	// Location Tracking
	TrackLocation  bool          `json:"trackLocation" yaml:"trackLocation"`
	UpdateInterval time.Duration `json:"updateInterval" yaml:"updateInterval"`

	// Session Validation
	ValidateOnRequest     bool `json:"validateOnRequest" yaml:"validateOnRequest"`
	InvalidateOnViolation bool `json:"invalidateOnViolation" yaml:"invalidateOnViolation"`

	// Grace Period
	GracePeriod   time.Duration `json:"gracePeriod" yaml:"gracePeriod"` // Allow brief violations
	MaxViolations int           `json:"maxViolations" yaml:"maxViolations"`
}

SessionConfig configures geofence session management

type StaticDetectionProvider ΒΆ

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

StaticDetectionProvider implements a simple rule-based detection Useful for testing or when external APIs are not available

func NewStaticDetectionProvider ΒΆ

func NewStaticDetectionProvider() *StaticDetectionProvider

NewStaticDetectionProvider creates a new static detection provider

func (*StaticDetectionProvider) AddDatacenter ΒΆ

func (p *StaticDetectionProvider) AddDatacenter(ip string)

AddDatacenter marks an IP as datacenter

func (*StaticDetectionProvider) AddProxy ΒΆ

func (p *StaticDetectionProvider) AddProxy(ip string)

AddProxy marks an IP as a proxy

func (*StaticDetectionProvider) AddTor ΒΆ

func (p *StaticDetectionProvider) AddTor(ip string)

AddTor marks an IP as Tor

func (*StaticDetectionProvider) AddVPN ΒΆ

func (p *StaticDetectionProvider) AddVPN(ip string)

AddVPN marks an IP as a VPN

func (*StaticDetectionProvider) Check ΒΆ

func (*StaticDetectionProvider) Name ΒΆ

func (p *StaticDetectionProvider) Name() string

type StatusResponse ΒΆ

type StatusResponse = responses.StatusResponse

type SuccessResponse ΒΆ

type SuccessResponse = responses.SuccessResponse

type TimeRestriction ΒΆ

type TimeRestriction struct {
	Countries   []string `json:"countries" yaml:"countries"`
	AllowedDays []string `json:"allowedDays" yaml:"allowedDays"` // Monday, Tuesday, etc.
	StartHour   int      `json:"startHour" yaml:"startHour"`     // 0-23
	EndHour     int      `json:"endHour" yaml:"endHour"`         // 0-23
	Timezone    string   `json:"timezone" yaml:"timezone"`       // IANA timezone
}

TimeRestriction defines time-based access rules

type TimeRestrictionRule ΒΆ

type TimeRestrictionRule struct {
	AllowedDays []string `json:"allowedDays"` // Monday, Tuesday, etc.
	StartHour   int      `json:"startHour"`   // 0-23
	EndHour     int      `json:"endHour"`     // 0-23
	Timezone    string   `json:"timezone"`    // IANA timezone
}

TimeRestrictionRule defines time-based access rules

type TravelAlert ΒΆ

type TravelAlert struct {
	bun.BaseModel `bun:"table:travel_alerts,alias:ta"`

	ID     xid.ID `bun:"id,pk,type:varchar(20)" json:"id"`
	UserID xid.ID `bun:"user_id,type:varchar(20),notnull" json:"userId"`
	AppID  xid.ID `bun:"app_id,type:varchar(20),notnull" json:"appId"`

	// Alert Type
	AlertType string `bun:"alert_type,notnull" json:"alertType"` // impossible_travel, new_location, anomaly
	Severity  string `bun:"severity,notnull" json:"severity"`    // low, medium, high, critical

	// Location Context
	FromCountry string   `bun:"from_country" json:"fromCountry"`
	FromCity    string   `bun:"from_city" json:"fromCity"`
	FromLat     *float64 `bun:"from_lat" json:"fromLat,omitempty"`
	FromLon     *float64 `bun:"from_lon" json:"fromLon,omitempty"`
	ToCountry   string   `bun:"to_country" json:"toCountry"`
	ToCity      string   `bun:"to_city" json:"toCity"`
	ToLat       *float64 `bun:"to_lat" json:"toLat,omitempty"`
	ToLon       *float64 `bun:"to_lon" json:"toLon,omitempty"`

	// Travel Metrics
	DistanceKm      float64       `bun:"distance_km,notnull" json:"distanceKm"`
	TimeDifference  time.Duration `bun:"time_difference,notnull" json:"timeDifference"`
	CalculatedSpeed float64       `bun:"calculated_speed,notnull" json:"calculatedSpeed"` // km/h

	// Status
	Status           string     `bun:"status,notnull" json:"status"` // pending, approved, denied, auto_approved
	RequiresApproval bool       `bun:"requires_approval" json:"requiresApproval"`
	ApprovedBy       *xid.ID    `bun:"approved_by,type:varchar(20)" json:"approvedBy,omitempty"`
	ApprovedAt       *time.Time `bun:"approved_at" json:"approvedAt,omitempty"`

	// Notifications
	UserNotified  bool       `bun:"user_notified" json:"userNotified"`
	AdminNotified bool       `bun:"admin_notified" json:"adminNotified"`
	NotifiedAt    *time.Time `bun:"notified_at" json:"notifiedAt,omitempty"`

	// Resolution
	ResolvedAt *time.Time `bun:"resolved_at" json:"resolvedAt,omitempty"`
	Resolution string     `bun:"resolution" json:"resolution,omitempty"`

	// References
	LocationEventID xid.ID `bun:"location_event_id,type:varchar(20)" json:"locationEventId"`

	// Metadata
	CreatedAt time.Time              `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time              `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	Metadata  map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`
}

TravelAlert represents a travel notification/alert

type TravelConfig ΒΆ

type TravelConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Detection Thresholds
	MinDistanceKm  float64       `json:"minDistanceKm" yaml:"minDistanceKm"`   // Trigger distance
	MinTimeBetween time.Duration `json:"minTimeBetween" yaml:"minTimeBetween"` // Minimum time between locations
	MaxSpeedKmh    float64       `json:"maxSpeedKmh" yaml:"maxSpeedKmh"`       // Impossible travel speed

	// Notification Settings
	NotifyUser      bool          `json:"notifyUser" yaml:"notifyUser"`
	NotifyAdmin     bool          `json:"notifyAdmin" yaml:"notifyAdmin"`
	RequireApproval bool          `json:"requireApproval" yaml:"requireApproval"` // Block until approved
	ApprovalTimeout time.Duration `json:"approvalTimeout" yaml:"approvalTimeout"`

	// Channels
	EmailNotify   bool `json:"emailNotify" yaml:"emailNotify"`
	SMSNotify     bool `json:"smsNotify" yaml:"smsNotify"`
	PushNotify    bool `json:"pushNotify" yaml:"pushNotify"`
	WebhookNotify bool `json:"webhookNotify" yaml:"webhookNotify"`

	// Auto-Approval
	AutoApproveAfter  time.Duration `json:"autoApproveAfter" yaml:"autoApproveAfter"`
	TrustFrequentDest bool          `json:"trustFrequentDest" yaml:"trustFrequentDest"` // Trust frequent destinations
}

TravelConfig configures travel notifications

type TrustedLocation ΒΆ

type TrustedLocation struct {
	bun.BaseModel `bun:"table:trusted_locations,alias:tl"`

	ID     xid.ID `bun:"id,pk,type:varchar(20)" json:"id"`
	UserID xid.ID `bun:"user_id,type:varchar(20),notnull" json:"userId"`
	AppID  xid.ID `bun:"app_id,type:varchar(20),notnull" json:"appId"`

	// Location
	Name        string  `bun:"name,notnull" json:"name"` // e.g., "Home", "Office"
	Description string  `bun:"description" json:"description"`
	Country     string  `bun:"country,notnull" json:"country"`
	CountryCode string  `bun:"country_code,notnull" json:"countryCode"`
	Region      string  `bun:"region" json:"region"`
	City        string  `bun:"city" json:"city"`
	Latitude    float64 `bun:"latitude" json:"latitude"`
	Longitude   float64 `bun:"longitude" json:"longitude"`
	RadiusKm    float64 `bun:"radius_km,notnull" json:"radiusKm"` // Trust radius

	// Trust Settings
	AutoApprove bool `bun:"auto_approve" json:"autoApprove"`
	SkipMFA     bool `bun:"skip_mfa" json:"skipMfa"`

	// Usage Statistics
	UsageCount  int        `bun:"usage_count" json:"usageCount"`
	FirstUsedAt time.Time  `bun:"first_used_at" json:"firstUsedAt"`
	LastUsedAt  *time.Time `bun:"last_used_at" json:"lastUsedAt,omitempty"`

	// Metadata
	CreatedAt time.Time  `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time  `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	ExpiresAt *time.Time `bun:"expires_at" json:"expiresAt,omitempty"`
}

TrustedLocation represents a user's trusted location

type VPNAPIProvider ΒΆ

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

VPNAPIProvider implements DetectionProvider using vpnapi.io

func NewVPNAPIProvider ΒΆ

func NewVPNAPIProvider(apiKey string) *VPNAPIProvider

NewVPNAPIProvider creates a new vpnapi.io provider

func (*VPNAPIProvider) Check ΒΆ

func (p *VPNAPIProvider) Check(ctx context.Context, ip string) (*DetectionResult, error)

func (*VPNAPIProvider) Name ΒΆ

func (p *VPNAPIProvider) Name() string

Jump to

Keyboard shortcuts

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