2019-12-08 03:59:58 -05:00
|
|
|
package rpc
|
2019-12-07 05:14:40 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-01-08 08:04:50 -05:00
|
|
|
"strconv"
|
2019-12-07 05:14:40 -05:00
|
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AuthHandler struct {
|
2019-12-09 03:02:49 -05:00
|
|
|
ClientID string
|
|
|
|
ClientSecret string
|
2019-12-07 05:14:40 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-01-08 08:04:50 -05:00
|
|
|
func (a *AuthHandler) Check(ctx context.Context) (clientID uint64, 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
|
|
|
}
|
2021-01-08 08:04:50 -05:00
|
|
|
var clientSecret string
|
2019-12-09 05:14:31 -05:00
|
|
|
if value, ok := md["client_id"]; ok {
|
2021-01-08 08:04:50 -05:00
|
|
|
clientID, _ = strconv.ParseUint(value[0], 10, 64)
|
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
|
|
|
}
|