feat: add unified authorization middleware

This commit is contained in:
2026-08-12 11:46:48 +08:00
parent 2d1deb54f0
commit fa6898aef8
31 changed files with 341 additions and 490 deletions

View File

@@ -21,10 +21,15 @@ type Server struct {
HTTP *gin.Engine
http *http.Server
dynamic *dynamicGateway
auth *authorization
}
func New() *Server {
grpcServer := grpc.NewServer()
func New(key string, expireSeconds int64, anonymous []string) (*Server, error) {
auth, err := newAuthorization(key, expireSeconds, anonymous)
if err != nil {
return nil, err
}
grpcServer := grpc.NewServer(grpc.UnaryInterceptor(auth.unaryInterceptor))
reflection.Register(grpcServer)
engine := gin.New()
engine.Use(gin.Logger(), gin.Recovery())
@@ -32,10 +37,11 @@ func New() *Server {
GRPC: grpcServer,
Gateway: gwRuntime.NewServeMux(),
HTTP: engine,
}
auth: auth,
}, nil
}
func (s *Server) Start(grpcAddr, httpAddr string, allow []string) error {
func (s *Server) Start(grpcAddr, httpAddr string) error {
grpcListener, err := net.Listen("tcp", grpcAddr)
if err != nil {
return fmt.Errorf("listen gRPC on %s: %w", grpcAddr, err)
@@ -46,7 +52,7 @@ func (s *Server) Start(grpcAddr, httpAddr string, allow []string) error {
return fmt.Errorf("listen HTTP on %s: %w", httpAddr, err)
}
s.dynamic, err = newDynamicGateway(grpcAddr, allow)
s.dynamic, err = newDynamicGateway(grpcAddr)
if err != nil {
_ = grpcListener.Close()
_ = httpListener.Close()
@@ -65,7 +71,7 @@ func (s *Server) Start(grpcAddr, httpAddr string, allow []string) error {
})
s.http = &http.Server{
Addr: httpAddr,
Handler: handler,
Handler: s.auth.httpMiddleware(handler),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,