nezha/service/rpc/auth.go

54 lines
1.2 KiB
Go
Raw Normal View History

2019-12-08 03:59:58 -05:00
package rpc
2019-12-07 05:14:40 -05:00
import (
"context"
2019-12-09 03:02:49 -05:00
"fmt"
2019-12-07 05:14:40 -05:00
2019-12-09 03:02:49 -05:00
"github.com/p14yground/nezha/model"
"github.com/p14yground/nezha/service/dao"
2019-12-07 05:14:40 -05:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// AuthHandler ..
type AuthHandler struct {
2019-12-09 03:02:49 -05:00
ClientID string
ClientSecret string
2019-12-07 05:14:40 -05:00
}
// GetRequestMetadata ..
func (a *AuthHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
2019-12-09 03:02:49 -05:00
return map[string]string{"app_key": a.ClientID, "app_secret": a.ClientSecret}, nil
2019-12-07 05:14:40 -05:00
}
// RequireTransportSecurity ..
func (a *AuthHandler) RequireTransportSecurity() bool {
2019-12-09 03:02:49 -05:00
return !dao.Conf.Debug
2019-12-07 05:14:40 -05:00
}
// Check ..
func (a *AuthHandler) Check(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
2019-12-09 03:02:49 -05:00
return status.Errorf(codes.Unauthenticated, "获取 metaData 失败")
2019-12-07 05:14:40 -05:00
}
var (
2019-12-09 03:02:49 -05:00
ClientID string
ClientSecret string
2019-12-07 05:14:40 -05:00
)
if value, ok := md["app_key"]; ok {
2019-12-09 03:02:49 -05:00
ClientID = value[0]
2019-12-07 05:14:40 -05:00
}
if value, ok := md["app_secret"]; ok {
2019-12-09 03:02:49 -05:00
ClientSecret = value[0]
2019-12-07 05:14:40 -05:00
}
2019-12-09 03:02:49 -05:00
if _, ok := dao.Cache.Get(fmt.Sprintf("%s%s%s", model.CtxKeyServer, ClientID, ClientSecret)); !ok {
return status.Errorf(codes.Unauthenticated, "客户端认证失败")
2019-12-07 05:14:40 -05:00
}
return nil
}