Skip to content

Commit

Permalink
正向http鉴权 (#341)
Browse files Browse the repository at this point in the history
* 正向http鉴权

* 正向http鉴权

* 正向http鉴权

---------

Co-authored-by: Alex <[email protected]>
  • Loading branch information
alexskim and Alex authored Mar 4, 2024
1 parent 3996ffe commit 344e33b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ type Settings struct {
WhiteBypass []int64 `yaml:"white_bypass"`
TransferUrl bool `yaml:"transfer_url"`
HttpAddress string `yaml:"http_address"`
AccessToken string `yaml:"http_access_token"`
HttpVersion int `yaml:"http_version"`
HttpTimeOut int `yaml:"http_timeout"`
PostUrl []string `yaml:"post_url"`
Expand Down Expand Up @@ -1217,6 +1218,18 @@ func GetHttpAddress() string {
return instance.Settings.HttpAddress
}

// 获取 HTTP 访问令牌
func GetHTTPAccessToken() string {
mu.Lock()
defer mu.Unlock()

if instance == nil {
mylog.Println("Warning: instance is nil when trying to get HTTP access token.")
return ""
}
return instance.Settings.AccessToken
}

// 获取 HTTP 版本
func GetHttpVersion() int {
mu.Lock()
Expand Down
11 changes: 11 additions & 0 deletions httpapi/httpapi.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package httpapi

import (
"github.com/hoshinonyaruko/gensokyo/config"
"net/http"
"strconv"
"strings"

"github.com/gin-gonic/gin"
"github.com/hoshinonyaruko/gensokyo/callapi"
Expand All @@ -13,6 +15,15 @@ import (
// CombinedMiddleware 创建并返回一个带有依赖的中间件闭包
func CombinedMiddleware(api openapi.OpenAPI, apiV2 openapi.OpenAPI) gin.HandlerFunc {
return func(c *gin.Context) {
accessToken := config.GetHTTPAccessToken()
if accessToken != "" {
tokenHeader := strings.Replace(c.GetHeader("Authorization"), "Bearer ", "", 1)
tokenQuery, _ := c.GetQuery("access_token")
if (tokenHeader == "" || tokenHeader != accessToken) && (tokenQuery == "" || tokenQuery != accessToken) {
c.JSON(http.StatusForbidden, gin.H{"error": "鉴权失败"})
return
}
}
// 检查路径和处理对应的请求
if c.Request.URL.Path == "/send_group_msg" {
handleSendGroupMessage(c, api, apiV2)
Expand Down
1 change: 1 addition & 0 deletions template/config_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ settings:
#正向http
http_address: "" #http监听地址 与websocket独立 示例:0.0.0.0:5700 为空代表不开启
http_access_token: "" #http访问令牌
http_version : 11 #暂时只支持11
http_timeout: 5 #反向 HTTP 超时时间, 单位秒,<5 时将被忽略
Expand Down

0 comments on commit 344e33b

Please sign in to comment.