2019-12-08 16:59:58 +08:00
|
|
|
package rpc
|
2019-12-07 18:14:40 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-10-20 23:23:04 +08:00
|
|
|
"sync"
|
2019-12-07 18:14:40 +08:00
|
|
|
|
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
"google.golang.org/grpc/status"
|
2022-01-09 11:54:14 +08:00
|
|
|
|
2024-10-20 23:23:04 +08:00
|
|
|
"github.com/naiba/nezha/model"
|
2022-01-09 11:54:14 +08:00
|
|
|
"github.com/naiba/nezha/service/singleton"
|
2019-12-07 18:14:40 +08:00
|
|
|
)
|
|
|
|
|
2024-07-14 12:47:36 +08:00
|
|
|
type authHandler struct {
|
2019-12-09 16:02:49 +08:00
|
|
|
ClientSecret string
|
2024-10-20 23:23:04 +08:00
|
|
|
ClientUUID string
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|
|
|
|
|
2024-07-14 12:47:36 +08:00
|
|
|
func (a *authHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
|
2024-10-20 23:23:04 +08:00
|
|
|
return map[string]string{"client_secret": a.ClientSecret, "client_uuid": a.ClientUUID}, nil
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|
|
|
|
|
2024-07-14 12:47:36 +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
|
|
|
}
|
|
|
|
|
2024-07-14 12:47:36 +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
|
|
|
}
|
|
|
|
|
2024-10-20 23:23:04 +08:00
|
|
|
if clientSecret != singleton.Conf.AgentSecretKey {
|
|
|
|
return 0, status.Errorf(codes.Unauthenticated, "客户端认证失败")
|
|
|
|
}
|
|
|
|
|
|
|
|
var clientUUID string
|
|
|
|
if value, ok := md["client_uuid"]; ok {
|
|
|
|
clientUUID = value[0]
|
|
|
|
}
|
|
|
|
|
2022-01-09 11:54:14 +08:00
|
|
|
singleton.ServerLock.RLock()
|
|
|
|
defer singleton.ServerLock.RUnlock()
|
2024-10-20 23:23:04 +08:00
|
|
|
clientID, hasID := singleton.ServerUUIDToID[clientUUID]
|
2021-07-25 23:50:08 +08:00
|
|
|
if !hasID {
|
2024-10-20 23:23:04 +08:00
|
|
|
s := model.Server{UUID: clientUUID}
|
|
|
|
if err := singleton.DB.Create(&s).Error; err != nil {
|
|
|
|
return 0, status.Errorf(codes.Unauthenticated, err.Error())
|
|
|
|
}
|
|
|
|
s.Host = &model.Host{}
|
|
|
|
s.State = &model.HostState{}
|
|
|
|
s.TaskCloseLock = new(sync.Mutex)
|
|
|
|
singleton.ServerList[s.ID] = &s
|
|
|
|
singleton.ServerUUIDToID[clientUUID] = s.ID
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|
2024-10-20 23:23:04 +08:00
|
|
|
|
2021-01-30 17:10:51 +08:00
|
|
|
return clientID, nil
|
2019-12-07 18:14:40 +08:00
|
|
|
}
|