nezha/service/rpc/auth.go

75 lines
1.9 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"
"strings"
2019-12-07 18:14:40 +08:00
petname "github.com/dustinkirkland/golang-petname"
"github.com/hashicorp/go-uuid"
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-11-28 19:38:54 +08:00
"github.com/nezhahq/nezha/model"
"github.com/nezhahq/nezha/service/singleton"
2019-12-07 18:14:40 +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
}
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 = strings.TrimSpace(value[0])
2019-12-07 18:14:40 +08:00
}
if clientSecret == "" {
return 0, status.Error(codes.Unauthenticated, "客户端认证失败")
}
ip, _ := ctx.Value(model.CtxKeyRealIP{}).(string)
2024-10-20 23:23:04 +08:00
if clientSecret != singleton.Conf.AgentSecretKey {
model.BlockIP(singleton.DB, ip, model.WAFBlockReasonTypeAgentAuthFail)
return 0, status.Error(codes.Unauthenticated, "客户端认证失败")
2024-10-20 23:23:04 +08:00
}
model.ClearIP(singleton.DB, ip)
2024-10-20 23:23:04 +08:00
var clientUUID string
if value, ok := md["client_uuid"]; ok {
clientUUID = value[0]
}
2024-10-22 23:44:50 +08:00
if _, err := uuid.ParseUUID(clientUUID); err != nil {
return 0, status.Error(codes.Unauthenticated, "客户端 UUID 不合法")
2024-10-22 23:44:50 +08:00
}
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]
if !hasID {
s := model.Server{UUID: clientUUID, Name: petname.Generate(2, "-")}
2024-10-20 23:23:04 +08:00
if err := singleton.DB.Create(&s).Error; err != nil {
return 0, status.Error(codes.Unauthenticated, err.Error())
2024-10-20 23:23:04 +08:00
}
s.Host = &model.Host{}
s.State = &model.HostState{}
// generate a random silly server name
2024-10-20 23:23:04 +08:00
singleton.ServerList[s.ID] = &s
singleton.ServerUUIDToID[clientUUID] = s.ID
singleton.ReSortServer()
2024-10-22 23:44:50 +08:00
clientID = s.ID
2019-12-07 18:14:40 +08:00
}
2024-10-20 23:23:04 +08:00
return clientID, nil
2019-12-07 18:14:40 +08:00
}