forked from acheong08/ChatGPT-to-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
67 lines (60 loc) · 1.59 KB
/
middleware.go
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
66
67
package main
import (
"bufio"
"os"
"strings"
gin "github.com/gin-gonic/gin"
)
var ADMIN_PASSWORD string
var API_KEYS map[string]bool
func init() {
ADMIN_PASSWORD = os.Getenv("ADMIN_PASSWORD")
if ADMIN_PASSWORD == "" {
ADMIN_PASSWORD = "TotallySecurePassword"
}
}
func adminCheck(c *gin.Context) {
password := c.Request.Header.Get("Authorization")
if password != ADMIN_PASSWORD {
c.String(401, "Unauthorized")
c.Abort()
return
}
c.Next()
}
func cors(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "*")
c.Header("Access-Control-Allow-Headers", "*")
c.Next()
}
func Authorization(c *gin.Context) {
if API_KEYS == nil {
API_KEYS = make(map[string]bool)
if _, err := os.Stat("api_keys.txt"); err == nil {
file, _ := os.Open("api_keys.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
key := scanner.Text()
if key != "" {
API_KEYS["Bearer "+key] = true
}
}
}
}
if len(API_KEYS) != 0 && !API_KEYS[c.Request.Header.Get("Authorization")] {
if c.Request.Header.Get("Authorization") == "" {
c.JSON(401, gin.H{"error": "No API key provided. Get one at https://discord.gg/9K2BvbXEHT"})
} else if strings.HasPrefix(c.Request.Header.Get("Authorization"), "Bearer sk-") {
c.JSON(401, gin.H{"error": "You tried to use the official API key which is not supported."})
} else if strings.HasPrefix(c.Request.Header.Get("Authorization"), "Bearer eyJhbGciOiJSUzI1NiI") {
return
} else {
c.JSON(401, gin.H{"error": "Invalid API key."})
}
c.Abort()
return
}
c.Next()
}