nezha/service/rpc/auth.go

53 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"
2020-11-10 21:07:45 -05:00
"github.com/naiba/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 05:14:31 -05:00
return map[string]string{"client_id": a.ClientID, "client_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 ..
2019-12-09 05:14:31 -05:00
func (a *AuthHandler) Check(ctx context.Context) (clientID string, err error) {
2019-12-07 05:14:40 -05:00
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
2019-12-09 05:14:31 -05:00
err = status.Errorf(codes.Unauthenticated, "获取 metaData 失败")
return
2019-12-07 05:14:40 -05:00
}
var (
2019-12-09 05:14:31 -05:00
clientSecret string
2019-12-07 05:14:40 -05:00
)
2019-12-09 05:14:31 -05:00
if value, ok := md["client_id"]; ok {
clientID = value[0]
2019-12-07 05:14:40 -05:00
}
2019-12-09 05:14:31 -05:00
if value, ok := md["client_secret"]; ok {
clientSecret = value[0]
2019-12-07 05:14:40 -05:00
}
2019-12-09 05:14:31 -05:00
dao.ServerLock.RLock()
defer dao.ServerLock.RUnlock()
if server, has := dao.ServerList[clientID]; !has || server.Secret != clientSecret {
err = status.Errorf(codes.Unauthenticated, "客户端认证失败")
2019-12-07 05:14:40 -05:00
}
2019-12-09 05:14:31 -05:00
return
2019-12-07 05:14:40 -05:00
}