-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
116 lines (97 loc) · 2.25 KB
/
auth.go
File metadata and controls
116 lines (97 loc) · 2.25 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"os"
"strings"
"github.com/gin-gonic/gin"
)
func authenticateWithKey(key string) *User {
usersMutex.RLock()
defer usersMutex.RUnlock()
for _, user := range users {
if user.GetKey() == key {
return &user
}
}
return nil
}
func doesUserOwnKey(userId UserId, key string) bool {
keyOwnershipCacheMutex.Lock()
defer keyOwnershipCacheMutex.Unlock()
keysMutex.RLock()
defer keysMutex.RUnlock()
for _, userKey := range keys {
if userKey.Key == key {
if _, exists := userKey.Users[userId]; exists {
return true
}
break
}
}
return false
}
func getKeyNextBilling(userId UserId, key string) int64 {
keyOwnershipCacheMutex.Lock()
defer keyOwnershipCacheMutex.Unlock()
var success bool = keysMutex.TryRLock()
if success {
defer keysMutex.RUnlock()
}
for _, userKey := range keys {
if userKey.Key == key {
if _, exists := userKey.Users[userId]; exists {
nextBilling := userKey.Users[userId].NextBilling
if nextBilling == nil {
return 0
}
switch v := nextBilling.(type) {
case float64:
return int64(v)
case int64:
return v
case int:
return int64(v)
default:
return 0
}
}
break
}
}
// If the key doesn't exist, return 0 to indicate that the user doesn't have a subscription
return 0
}
func isAdmin(c *gin.Context) bool {
envOnce.Do(loadEnvFile)
ADMIN_TOKEN := os.Getenv("ADMIN_TOKEN")
if ADMIN_TOKEN == "" {
return false
}
authHeader := c.GetHeader("Authorization")
var adminToken string
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
adminToken = authHeader[7:]
} else if authHeader != "" {
adminToken = authHeader
}
return adminToken == ADMIN_TOKEN
}
func authenticateAdmin(c *gin.Context) bool {
envOnce.Do(loadEnvFile)
ADMIN_TOKEN := os.Getenv("ADMIN_TOKEN")
if ADMIN_TOKEN == "" {
c.JSON(500, gin.H{"error": "ADMIN_TOKEN environment variable not set"})
return false
}
authHeader := c.GetHeader("Authorization")
var adminToken string
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
adminToken = authHeader[7:]
} else if authHeader != "" {
adminToken = authHeader
}
if adminToken != ADMIN_TOKEN {
c.JSON(403, gin.H{"error": "Invalid admin authentication"})
return false
}
return true
}