86 lines
2.4 KiB
Go
86 lines
2.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"backend/internal/types"
|
|
"backend/pkg/library/errs"
|
|
"backend/pkg/permission/domain/entity"
|
|
"backend/pkg/permission/domain/token"
|
|
"context"
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
|
|
|
"backend/pkg/permission/domain/usecase"
|
|
uc "backend/pkg/permission/usecase"
|
|
"net/http"
|
|
)
|
|
|
|
type AuthMiddlewareParam struct {
|
|
TokenSec string
|
|
TokenUseCase usecase.TokenUseCase
|
|
}
|
|
|
|
type AuthMiddleware struct {
|
|
TokenSec string
|
|
TokenUseCase usecase.TokenUseCase
|
|
}
|
|
|
|
func NewAuthMiddleware(param AuthMiddlewareParam) *AuthMiddleware {
|
|
return &AuthMiddleware{
|
|
TokenSec: param.TokenSec,
|
|
TokenUseCase: param.TokenUseCase,
|
|
}
|
|
}
|
|
|
|
func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// 解析 Header
|
|
header := types.Authorization{}
|
|
if err := httpx.ParseHeaders(r, &header); err != nil {
|
|
m.writeErrorResponse(w, r, http.StatusBadRequest, "Failed to parse headers", int64(errs.InvalidFormat("").FullCode()))
|
|
|
|
return
|
|
}
|
|
|
|
// 驗證 Token
|
|
claim, err := uc.ParseClaims(header.Authorization, m.TokenSec, true)
|
|
if err != nil {
|
|
// 是否需要紀錄錯誤,是不是只要紀錄除了驗證失敗或過期之外的真錯誤
|
|
m.writeErrorResponse(w, r,
|
|
http.StatusUnauthorized, "failed to verify toke",
|
|
int64(100400))
|
|
|
|
return
|
|
}
|
|
|
|
// 驗證 Token 是否在黑名單中
|
|
if _, err := m.TokenUseCase.ValidationToken(r.Context(), entity.ValidationTokenReq{Token: header.Authorization}); err != nil {
|
|
m.writeErrorResponse(w, r, http.StatusForbidden,
|
|
"failed to get toke",
|
|
int64(100400))
|
|
|
|
return
|
|
}
|
|
|
|
// 設置 context 並傳遞給下一個處理器
|
|
ctx := SetContext(r, claim)
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
func SetContext(r *http.Request, claim uc.TokenClaims) context.Context {
|
|
ctx := context.WithValue(r.Context(), token.KeyRole, claim.Role())
|
|
ctx = context.WithValue(ctx, token.KeyUID, claim.UID())
|
|
ctx = context.WithValue(ctx, token.KeyDeviceID, claim.DeviceID())
|
|
ctx = context.WithValue(ctx, token.KeyScope, claim.Scope())
|
|
ctx = context.WithValue(ctx, token.KeyLoginID, claim.LoginID())
|
|
|
|
return ctx
|
|
}
|
|
|
|
// writeErrorResponse 用於處理錯誤回應
|
|
func (m *AuthMiddleware) writeErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, message string, code int64) {
|
|
httpx.WriteJsonCtx(r.Context(), w, statusCode, types.ErrorResp{
|
|
Code: int(code),
|
|
Msg: message,
|
|
})
|
|
}
|