Brijesh's Git Server — argus-core @ 5e54080a940f236c483faa37881d3b3e0bcdbf1d

Logging service

internal/auth/utils.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
package auth

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
)

const (
	// APIKeyPrefix is the prefix for all API keys
	APIKeyPrefix = "argus"
	// APIKeyBytes is the number of random bytes to generate for the API key
	APIKeyBytes = 32
)

// generateAPIKey generates a new API key with format: argus_<random-string>
// The random string is base64 encoded and URL safe
func generateAPIKey() (string, error) {
	// Generate random bytes
	randomBytes := make([]byte, APIKeyBytes)
	_, err := rand.Read(randomBytes)
	if err != nil {
		return "", fmt.Errorf("failed to generate random bytes: %w", err)
	}

	// Encode as base64 and make it URL safe
	// Use RawURLEncoding to avoid special characters like '/' and '+'
	randomString := base64.RawURLEncoding.EncodeToString(randomBytes)

	// Format: argus_<random-string>
	return fmt.Sprintf("%s_%s", APIKeyPrefix, randomString), nil
}

// hashAPIKey creates a SHA-256 hash of the API key
// This is what we'll store in the database
func hashAPIKey(key string) string {
	// Create SHA-256 hash
	hasher := sha256.New()
	hasher.Write([]byte(key))

	// Convert to hex string
	return hex.EncodeToString(hasher.Sum(nil))
}

// validateAPIKeyFormat checks if the API key has the correct format
func validateAPIKeyFormat(key string) bool {
	// Check if key starts with the correct prefix
	if len(key) < len(APIKeyPrefix)+2 { // +2 for '_' and at least one character
		return false
	}

	prefix := key[:len(APIKeyPrefix)]
	if prefix != APIKeyPrefix {
		return false
	}

	// Check if the next character is underscore
	if key[len(APIKeyPrefix)] != '_' {
		return false
	}

	return true
}