api-platform/internal/handler/grpc/interceptor/auth.go

41 lines
952 B
Go
Raw Normal View History

2024-11-21 11:25:32 +00:00
package interceptor
import (
"context"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
2024-11-22 17:55:15 +00:00
"leafdev.top/Leaf/api-platform/internal/schema"
auth2 "leafdev.top/Leaf/api-platform/internal/service/auth"
"leafdev.top/Leaf/api-platform/pkg/consts"
2024-11-21 11:25:32 +00:00
)
type Auth struct {
authService *auth2.Service
}
func NewAuth(authService *auth2.Service) *Auth {
return &Auth{
authService: authService,
}
}
func (a *Auth) JwtAuth(ctx context.Context) (context.Context, error) {
tokenString, err := auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, err
}
token, err := a.authService.AuthFromToken(schema.JWTIDToken, tokenString)
if err != nil {
return nil, err
}
if !token.Valid {
return nil, consts.ErrNotValidToken
}
ctx = logging.InjectFields(ctx, logging.Fields{"auth.sub", token.Token.Sub})
return a.authService.SetUser(ctx, token), nil
}