nezha/service/rpc/auth.go

44 lines
1.0 KiB
Go
Raw Normal View History

2019-12-08 16:59:58 +08:00
package rpc
2019-12-07 18:14:40 +08:00
import (
"context"
2020-11-11 10:07:45 +08:00
"github.com/naiba/nezha/service/dao"
2019-12-07 18:14:40 +08:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type AuthHandler struct {
2019-12-09 16:02:49 +08:00
ClientSecret string
2019-12-07 18:14:40 +08:00
}
func (a *AuthHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"client_secret": a.ClientSecret}, nil
2019-12-07 18:14:40 +08:00
}
func (a *AuthHandler) RequireTransportSecurity() bool {
2021-05-10 18:04:38 +08:00
return false
2019-12-07 18:14:40 +08:00
}
func (a *AuthHandler) Check(ctx context.Context) (uint64, error) {
2019-12-07 18:14:40 +08:00
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return 0, status.Errorf(codes.Unauthenticated, "获取 metaData 失败")
2019-12-07 18:14:40 +08:00
}
2021-01-08 21:04:50 +08:00
var clientSecret string
2019-12-09 18:14:31 +08:00
if value, ok := md["client_secret"]; ok {
clientSecret = value[0]
2019-12-07 18:14:40 +08:00
}
2019-12-09 18:14:31 +08:00
dao.ServerLock.RLock()
defer dao.ServerLock.RUnlock()
clientID, hasID := dao.SecretToID[clientSecret]
_, hasServer := dao.ServerList[clientID]
if !hasID || !hasServer {
return 0, status.Errorf(codes.Unauthenticated, "客户端认证失败")
2019-12-07 18:14:40 +08:00
}
return clientID, nil
2019-12-07 18:14:40 +08:00
}