|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "encoding/hex" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | +) |
| 12 | + |
| 13 | +// aiAccessGranted is the package-level gate for AI and embedding features. |
| 14 | +// It is set once during startup by ValidateAPIAccess(). |
| 15 | +var aiAccessGranted = false |
| 16 | + |
| 17 | +// CreateAPIKey generates a 32-character random API key, stores it in the |
| 18 | +// access table paired with the given email, and prints it to the screen. |
| 19 | +// Usage: scmd --create-api "user@example.com" |
| 20 | +func CreateAPIKey(email string) { |
| 21 | + email = strings.TrimSpace(email) |
| 22 | + if email == "" { |
| 23 | + log.Fatal("Usage: scmd --create-api \"user@example.com\"") |
| 24 | + } |
| 25 | + |
| 26 | + // Ensure the database is initialised |
| 27 | + if err := InitDB(); err != nil { |
| 28 | + log.Fatalf("Database connection failed: %v", err) |
| 29 | + } |
| 30 | + defer CloseDB() |
| 31 | + |
| 32 | + // Generate 16 random bytes → 32 hex characters |
| 33 | + raw := make([]byte, 16) |
| 34 | + if _, err := rand.Read(raw); err != nil { |
| 35 | + log.Fatalf("Failed to generate random key: %v", err) |
| 36 | + } |
| 37 | + apiKey := strings.ToUpper(hex.EncodeToString(raw)) |
| 38 | + |
| 39 | + accessTbl := os.Getenv("ACCESS_TB") |
| 40 | + if accessTbl == "" { |
| 41 | + accessTbl = "access" |
| 42 | + } |
| 43 | + |
| 44 | + // Upsert: if the email already exists update the key, otherwise insert |
| 45 | + query := fmt.Sprintf(` |
| 46 | + INSERT INTO %s (email, api_key) |
| 47 | + VALUES ($1, $2) |
| 48 | + ON CONFLICT (email) DO UPDATE SET api_key = EXCLUDED.api_key`, accessTbl) |
| 49 | + |
| 50 | + if _, err := db.Exec(query, email, apiKey); err != nil { |
| 51 | + log.Fatalf("Failed to store API key: %v", err) |
| 52 | + } |
| 53 | + |
| 54 | + fmt.Println() |
| 55 | + fmt.Println("======================================================") |
| 56 | + fmt.Printf(" Email : %s\n", email) |
| 57 | + fmt.Printf(" API Key : %s\n", apiKey) |
| 58 | + fmt.Println() |
| 59 | + |
| 60 | + // Automatically write / update API_ACCESS in the .env file |
| 61 | + if err := writeAPIAccessToEnv(apiKey); err != nil { |
| 62 | + fmt.Printf(" ⚠ Could not update .env automatically: %v\n", err) |
| 63 | + fmt.Println(" Add this line manually to your .env file:") |
| 64 | + fmt.Printf(" API_ACCESS=%s\n", apiKey) |
| 65 | + } else { |
| 66 | + fmt.Println(" ✅ API_ACCESS has been written to your .env file.") |
| 67 | + } |
| 68 | + fmt.Println("======================================================") |
| 69 | + fmt.Println() |
| 70 | +} |
| 71 | + |
| 72 | +// writeAPIAccessToEnv updates or appends API_ACCESS=<key> in the .env file |
| 73 | +// found in the current working directory. |
| 74 | +func writeAPIAccessToEnv(apiKey string) error { |
| 75 | + // Locate the .env file |
| 76 | + cwd, err := os.Getwd() |
| 77 | + if err != nil { |
| 78 | + return err |
| 79 | + } |
| 80 | + envPath := []string{cwd} |
| 81 | + |
| 82 | + // Also check executable directory as fallback |
| 83 | + if execPath, err2 := os.Executable(); err2 == nil { |
| 84 | + envPath = append(envPath, filepath.Dir(execPath)) |
| 85 | + } |
| 86 | + |
| 87 | + var filePath string |
| 88 | + for _, dir := range envPath { |
| 89 | + p := filepath.Join(dir, ".env") |
| 90 | + if _, statErr := os.Stat(p); statErr == nil { |
| 91 | + filePath = p |
| 92 | + break |
| 93 | + } |
| 94 | + } |
| 95 | + if filePath == "" { |
| 96 | + return fmt.Errorf(".env file not found") |
| 97 | + } |
| 98 | + |
| 99 | + // Read existing content |
| 100 | + raw, err := os.ReadFile(filePath) |
| 101 | + if err != nil { |
| 102 | + return err |
| 103 | + } |
| 104 | + |
| 105 | + lines := strings.Split(string(raw), "\n") |
| 106 | + newLine := "API_ACCESS=" + apiKey |
| 107 | + found := false |
| 108 | + |
| 109 | + for i, line := range lines { |
| 110 | + trimmed := strings.TrimSpace(line) |
| 111 | + if strings.HasPrefix(trimmed, "API_ACCESS=") { |
| 112 | + lines[i] = newLine |
| 113 | + found = true |
| 114 | + break |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + if !found { |
| 119 | + lines = append(lines, newLine) |
| 120 | + } |
| 121 | + |
| 122 | + return os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644) |
| 123 | +} |
| 124 | + |
| 125 | +// ValidateAPIAccess checks whether the API_ACCESS key in the .env file |
| 126 | +// matches an entry in the access table. Sets aiAccessGranted accordingly. |
| 127 | +// Returns true if access is granted or if no access table / key is configured |
| 128 | +// (so existing installs without the access system still work). |
| 129 | +func ValidateAPIAccess() bool { |
| 130 | + apiKey := strings.TrimSpace(os.Getenv("API_ACCESS")) |
| 131 | + |
| 132 | + // If API_ACCESS is not set in .env, allow unrestricted access (backward-compatible) |
| 133 | + if apiKey == "" { |
| 134 | + aiAccessGranted = true |
| 135 | + return true |
| 136 | + } |
| 137 | + |
| 138 | + if db == nil { |
| 139 | + log.Println("⚠ API access validation skipped: database not connected") |
| 140 | + aiAccessGranted = false |
| 141 | + return false |
| 142 | + } |
| 143 | + |
| 144 | + accessTbl := os.Getenv("ACCESS_TB") |
| 145 | + if accessTbl == "" { |
| 146 | + accessTbl = "access" |
| 147 | + } |
| 148 | + |
| 149 | + var count int |
| 150 | + query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE api_key = $1", accessTbl) |
| 151 | + err := db.QueryRow(query, apiKey).Scan(&count) |
| 152 | + if err != nil { |
| 153 | + log.Printf("⚠ API access check failed: %v", err) |
| 154 | + aiAccessGranted = false |
| 155 | + return false |
| 156 | + } |
| 157 | + |
| 158 | + if count > 0 { |
| 159 | + aiAccessGranted = true |
| 160 | + log.Println("✓ API access validated") |
| 161 | + return true |
| 162 | + } |
| 163 | + |
| 164 | + log.Println("✗ API access denied: key not found in database") |
| 165 | + aiAccessGranted = false |
| 166 | + return false |
| 167 | +} |
| 168 | + |
| 169 | +// requireAIAccess returns true if AI features are unlocked. |
| 170 | +// Call this at the top of any AI/embedding function. |
| 171 | +func requireAIAccess() bool { |
| 172 | + if !aiAccessGranted { |
| 173 | + fmt.Println("⛔ AI features are locked. Add a valid API_ACCESS key to your .env") |
| 174 | + fmt.Println(" Generate one with: scmd --create-api \"your@email.com\"") |
| 175 | + } |
| 176 | + return aiAccessGranted |
| 177 | +} |
0 commit comments