forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
104 lines (89 loc) · 2.04 KB
/
auth.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
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
package middleware
import (
"chat/auth"
"chat/utils"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"net/http"
"strings"
)
func ProcessToken(c *gin.Context, token string) *auth.User {
if user := auth.ParseToken(c, token); user != nil {
c.Set("auth", true)
c.Set("user", user.Username)
c.Set("agent", "token")
return user
}
c.Set("auth", false)
c.Set("user", "")
c.Set("agent", "")
return nil
}
func ProcessKey(c *gin.Context, key string) *auth.User {
addr := c.ClientIP()
cache := utils.GetCacheFromContext(c)
if utils.IsInBlackList(cache, addr) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 403,
"message": "ip in black list",
})
return nil
}
if user := auth.ParseApiKey(c, key); user != nil {
c.Set("auth", true)
c.Set("user", user.Username)
c.Set("agent", "api")
return user
}
utils.IncrIP(cache, addr)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "Access denied. Please provide correct api key.",
})
return nil
}
func ProcessAuthorization(c *gin.Context) *auth.User {
k := strings.TrimSpace(c.GetHeader("Authorization"))
if k != "" {
if strings.HasPrefix(k, "Bearer ") {
k = strings.TrimPrefix(k, "Bearer ")
}
if strings.HasPrefix(k, "sk-") {
// api agent
return ProcessKey(c, k)
} else {
// token agent
return ProcessToken(c, k)
}
}
c.Set("auth", false)
c.Set("user", "")
c.Set("agent", "")
return nil
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
instance := ProcessAuthorization(c)
if viper.GetBool("serve_static") {
if !strings.HasPrefix(path, "/api") {
return
} else {
path = strings.TrimPrefix(path, "/api")
}
}
db := utils.GetDBFromContext(c)
admin := instance != nil && instance.IsAdmin(db)
c.Set("admin", admin)
if strings.HasPrefix(path, "/admin") {
if !admin {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "Access denied.",
})
return
}
}
c.Next()
}
}