From cbaa5d0862c9d55c21e94075f6c714be999b77c6 Mon Sep 17 00:00:00 2001
From: jano3 <jano@uafrica.com>
Date: Tue, 22 Nov 2022 14:53:18 +0200
Subject: [PATCH] Add new auth package for bob API keys, and move oauth package
 to oauth folder

---
 auth/api_key.go          | 30 ++++++++++++++++++++++++++++++
 {auth => oauth}/oauth.go |  0
 2 files changed, 30 insertions(+)
 create mode 100644 auth/api_key.go
 rename {auth => oauth}/oauth.go (100%)

diff --git a/auth/api_key.go b/auth/api_key.go
new file mode 100644
index 0000000..2f4fabb
--- /dev/null
+++ b/auth/api_key.go
@@ -0,0 +1,30 @@
+package auth
+
+import (
+	"github.com/google/uuid"
+	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/utils"
+	"strings"
+)
+
+// GenerateNewApiKey generates a 32 character API key. If the build environment is dev or stage the key will start with
+// "dev_" or "stage_" respectively.
+func GenerateNewApiKey() string {
+	uniqueKey := uuid.New().String()
+	uniqueKey = strings.ReplaceAll(uniqueKey, "-", "")
+
+	env := utils.GetEnv("ENVIRONMENT", "")
+	if env == "dev" || env == "stage" {
+		uniqueKey = env + "_" + uniqueKey
+	}
+
+	return uniqueKey
+}
+
+// GetApiKeyFromHeaders checks if a bearer token is passed as part of the Authorization header and returns that key
+func GetApiKeyFromHeaders(headers map[string]string) string {
+	key := headers["Authorization"]
+	if strings.HasPrefix(strings.ToLower(key), "bearer ") {
+		return strings.TrimPrefix(strings.ToLower(key), "bearer")
+	}
+	return ""
+}
diff --git a/auth/oauth.go b/oauth/oauth.go
similarity index 100%
rename from auth/oauth.go
rename to oauth/oauth.go
-- 
GitLab