2019-12-08 16:59:58 +08:00
|
|
|
package rpc
|
2019-12-07 18:14:40 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
"google.golang.org/grpc/status"
|
2022-01-09 11:54:14 +08:00
|
|
|
|
|
|
|
"github.com/naiba/nezha/service/singleton"
|
2019-12-07 18:14:40 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
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) {
|
2021-01-30 17:10:51 +08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-01-30 17:10:51 +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 {
|
2021-01-30 17:10:51 +08:00
|
|
|
return 0, status.Errorf(codes.Unauthenticated, "获取 metaData 失败")
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|
2021-01-30 17:10:51 +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
|
|
|
}
|
|
|
|
|
2022-01-09 11:54:14 +08:00
|
|
|
singleton.ServerLock.RLock()
|
|
|
|
defer singleton.ServerLock.RUnlock()
|
|
|
|
clientID, hasID := singleton.SecretToID[clientSecret]
|
2021-07-25 23:50:08 +08:00
|
|
|
if !hasID {
|
|
|
|
return 0, status.Errorf(codes.Unauthenticated, "客户端认证失败")
|
|
|
|
}
|
2022-01-09 11:54:14 +08:00
|
|
|
_, hasServer := singleton.ServerList[clientID]
|
2021-07-25 23:50:08 +08:00
|
|
|
if !hasServer {
|
2021-01-30 17:10:51 +08:00
|
|
|
return 0, status.Errorf(codes.Unauthenticated, "客户端认证失败")
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|
2021-01-30 17:10:51 +08:00
|
|
|
return clientID, nil
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|