gohttp/server/middleware.go

235 lines
5.6 KiB
Go
Raw Normal View History

2023-12-11 18:15:29 +08:00
package server
import (
2023-12-12 21:44:35 +08:00
"container/list"
2025-02-19 23:17:43 +08:00
"context"
2023-12-11 23:46:40 +08:00
"encoding/json"
2025-02-19 23:17:43 +08:00
"fmt"
2023-12-11 18:15:29 +08:00
"net/http"
2025-02-19 23:17:43 +08:00
"path"
2023-12-12 22:58:30 +08:00
"reflect"
2023-12-11 23:46:40 +08:00
"strings"
2023-12-11 18:15:29 +08:00
"git.pyer.club/kingecg/gohttpd/model"
2025-02-19 23:17:43 +08:00
"git.pyer.club/kingecg/gologger"
"github.com/golang-jwt/jwt/v5"
2023-12-11 18:15:29 +08:00
)
2025-02-18 00:54:50 +08:00
type Middleware func(w http.ResponseWriter, r *http.Request, next http.Handler)
2023-12-11 18:15:29 +08:00
2023-12-12 21:44:35 +08:00
type MiddlewareLink struct {
*list.List
}
2023-12-12 22:58:30 +08:00
func IsEqualMiddleware(a, b Middleware) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return reflect.ValueOf(a).Pointer() == reflect.ValueOf(b).Pointer()
}
2023-12-12 21:44:35 +08:00
func (ml *MiddlewareLink) Add(m Middleware) {
2023-12-12 22:58:30 +08:00
if m == nil {
return
}
2023-12-12 21:44:35 +08:00
if ml.List.Len() == 0 {
ml.PushBack(m)
} else {
2023-12-12 22:58:30 +08:00
if IsEqualMiddleware(m, Done) {
return
}
2023-12-12 21:44:35 +08:00
el := ml.Back()
ml.InsertBefore(m, el)
}
}
func (ml *MiddlewareLink) wrap(m Middleware, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m(w, r, next)
})
}
2025-02-18 00:54:50 +08:00
func (ml *MiddlewareLink) WrapHandler(next http.Handler) http.Handler {
if ml.Back() == nil {
return next
}
var handler http.Handler = next
2025-02-18 00:54:50 +08:00
for e := ml.Back(); e != nil; e = e.Prev() {
middleware, ok := e.Value.(Middleware)
if !ok {
break
}
handler = ml.wrap(middleware, handler)
2023-12-12 21:44:35 +08:00
}
return handler
2023-12-12 21:44:35 +08:00
}
2025-05-30 18:42:53 +08:00
func (ml *MiddlewareLink) Clone() *MiddlewareLink {
ret := NewMiddlewareLink()
for e := ml.Back(); e != nil; e = e.Prev() {
middleware, ok := e.Value.(Middleware)
if !ok {
break
}
ret.Add(middleware)
}
return ret
}
2023-12-12 21:44:35 +08:00
func NewMiddlewareLink() *MiddlewareLink {
ml := &MiddlewareLink{list.New()}
ml.Add(Done)
return ml
}
2025-02-18 00:54:50 +08:00
func BasicAuth(w http.ResponseWriter, r *http.Request, next http.Handler) {
2023-12-11 18:15:29 +08:00
config := model.GetConfig()
if config.Admin.Username == "" || config.Admin.Password == "" {
2025-02-18 00:54:50 +08:00
next.ServeHTTP(w, r)
2023-12-11 18:15:29 +08:00
return
}
user, pass, ok := r.BasicAuth()
if ok && user == config.Admin.Username && pass == config.Admin.Password {
2025-02-18 00:54:50 +08:00
next.ServeHTTP(w, r)
2023-12-11 18:15:29 +08:00
} else {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
}
}
2025-02-19 23:17:43 +08:00
func JwtAuth(w http.ResponseWriter, r *http.Request, next http.Handler) {
l := gologger.GetLogger("JwtAuth")
2025-05-30 18:42:53 +08:00
config := getServerConfig(r)
if config == nil || config.Jwt == nil {
http.Error(w, "Jwt config error", http.StatusInternalServerError)
return
}
jwtConfig := config.Jwt
2025-02-19 23:17:43 +08:00
if jwtConfig.Secret == "" || path.Base(r.URL.Path) == "login" {
next.ServeHTTP(w, r)
return
}
// 从cookie中获取token
tokenCookie, err := r.Cookie("auth_token")
if err != nil {
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
tokenString := tokenCookie.Value
token, err := jwt.ParseWithClaims(tokenString, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
// 确保签名方法是正确的
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(jwtConfig.Secret), nil
})
if err != nil {
l.Error("Failed to parse JWT: %v", err)
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
if claims, ok := token.Claims.(*jwt.RegisteredClaims); ok && token.Valid {
// 验证通过,将用户信息存储在请求上下文中
ctx := context.WithValue(r.Context(), "user", claims)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
}
2023-12-11 18:15:29 +08:00
2025-02-18 00:54:50 +08:00
func RecordAccess(w http.ResponseWriter, r *http.Request, next http.Handler) {
model.Incr(r.Host)
next.ServeHTTP(w, r)
}
func Parse[T any](w http.ResponseWriter, r *http.Request, next http.Handler) {
2023-12-11 23:46:40 +08:00
2023-12-11 18:15:29 +08:00
if r.Method == "POST" || r.Method == "PUT" {
2023-12-11 23:46:40 +08:00
//判断r的content-type是否是application/x-www-form-urlencoded
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
r.ParseForm()
2025-02-18 00:54:50 +08:00
} else if r.Header.Get("Content-Type") == "multipart/form-data" {
2023-12-11 23:46:40 +08:00
r.ParseMultipartForm(r.ContentLength)
2025-02-18 00:54:50 +08:00
} else {
// 判断r的content-type是否是application/json
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") {
var t T
// 读取json数据
if err := json.NewDecoder(r.Body).Decode(&t); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx := r.Context()
m := ctx.Value(RequestCtxKey("data")).(map[string]interface{})
if m != nil {
m["data"] = t
}
2023-12-11 23:46:40 +08:00
}
}
2025-02-18 00:54:50 +08:00
2023-12-11 18:15:29 +08:00
}
2025-02-18 00:54:50 +08:00
next.ServeHTTP(w, r)
2023-12-11 18:15:29 +08:00
}
2023-12-12 21:44:35 +08:00
2025-05-30 18:42:53 +08:00
func getServerConfig(r *http.Request) *model.HttpServerConfig {
2025-05-29 17:39:08 +08:00
ctx := r.Context()
serverName, ok := ctx.Value(RequestCtxKey("serverName")).(string)
if !ok {
serverName = ""
2025-05-30 18:42:53 +08:00
return nil
2025-05-29 17:39:08 +08:00
}
config := model.GetServerConfig(serverName)
2025-05-30 18:42:53 +08:00
return config
}
// IPAccessControl 中间件实现IP访问控制
func IPAccessControl(w http.ResponseWriter, r *http.Request, next http.Handler) {
// get serverName from request context
config := getServerConfig(r)
2025-05-29 17:39:08 +08:00
if config != nil {
allowedIPs := config.AllowIPs
deniedIPs := config.DenyIPs
clientIP := strings.Split(r.RemoteAddr, ":")[0] // 获取客户端IP
// 首先检查是否被禁止Deny规则优先级高于Allow
for _, ip := range deniedIPs {
if ip == clientIP {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
}
// 然后检查是否被允许
if len(allowedIPs) > 0 {
allowed := false
for _, ip := range allowedIPs {
if ip == clientIP {
allowed = true
break
}
}
if !allowed {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
}
2025-05-30 18:42:53 +08:00
} else {
http.Error(w, "Server Config Error", http.StatusInternalServerError)
2025-05-29 17:39:08 +08:00
}
next.ServeHTTP(w, r)
}
2025-02-18 00:54:50 +08:00
func Done(w http.ResponseWriter, r *http.Request, next http.Handler) {
next.ServeHTTP(w, r)
2023-12-12 21:44:35 +08:00
}