forked from BlueSkyXN/Go-GPT-Gateway
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.go
58 lines (51 loc) · 1.12 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
package main
import (
"bufio"
"os"
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")] {
c.String(401, "Unauthorized")
c.Abort()
return
}
c.Next()
}