42 lines
904 B
Go
42 lines
904 B
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"giter.top/smart/internal/auth/oauth2"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Context keys for auth principal
|
|
const (
|
|
CtxUserID = "auth_user_id"
|
|
CtxTenantID = "auth_tenant_id"
|
|
CtxScope = "auth_scope"
|
|
)
|
|
|
|
// NewBearer 解析 opaque Bearer access_token,写入上下文;无 Bearer 或无效时继续放行(兼容未迁移接口)。
|
|
func NewBearer(store *oauth2.Store) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
h := c.GetHeader("Authorization")
|
|
const prefix = "Bearer "
|
|
if !strings.HasPrefix(h, prefix) {
|
|
c.Next()
|
|
return
|
|
}
|
|
raw := strings.TrimSpace(strings.TrimPrefix(h, prefix))
|
|
if raw == "" {
|
|
c.Next()
|
|
return
|
|
}
|
|
p, err := store.LookupAccessToken(c.Request.Context(), raw)
|
|
if err != nil {
|
|
c.Next()
|
|
return
|
|
}
|
|
c.Set(CtxUserID, p.UserID)
|
|
c.Set(CtxTenantID, p.TenantID)
|
|
c.Set(CtxScope, p.Scope)
|
|
c.Next()
|
|
}
|
|
}
|