nezha/cmd/dashboard/main.go

82 lines
1.4 KiB
Go
Raw Normal View History

2019-12-05 09:36:58 -05:00
package main
import (
"context"
2019-12-05 10:42:20 -05:00
"fmt"
2019-12-05 09:36:58 -05:00
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
2019-12-05 10:42:20 -05:00
pb "github.com/p14yground/nezha/proto"
2019-12-05 09:36:58 -05:00
)
2019-12-05 10:42:20 -05:00
// NezhaService ..
type NezhaService struct {
2019-12-05 09:36:58 -05:00
auth *Auth
}
2019-12-05 10:42:20 -05:00
// ReportState ..
func (s *NezhaService) ReportState(ctx context.Context, r *pb.State) (*pb.Receipt, error) {
2019-12-05 09:36:58 -05:00
if err := s.auth.Check(ctx); err != nil {
return nil, err
}
2019-12-05 10:42:20 -05:00
fmt.Printf("receive: %s\n", r)
return &pb.Receipt{}, nil
2019-12-05 09:36:58 -05:00
}
func main() {
server := grpc.NewServer()
2019-12-05 10:42:20 -05:00
pb.RegisterNezhaServiceServer(server, &NezhaService{})
2019-12-05 09:36:58 -05:00
lis, err := net.Listen("tcp", ":5555")
if err != nil {
panic(err)
}
server.Serve(lis)
}
// Auth ..
type Auth struct {
appKey string
appSecret string
}
// Check ..
func (a *Auth) Check(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Errorf(codes.Unauthenticated, "metadata.FromIncomingContext err")
}
var (
appKey string
appSecret string
)
if value, ok := md["app_key"]; ok {
appKey = value[0]
}
if value, ok := md["app_secret"]; ok {
appSecret = value[0]
}
if appKey != a.GetAppKey() || appSecret != a.GetAppSecret() {
return status.Errorf(codes.Unauthenticated, "invalid token")
}
return nil
}
// GetAppKey ..
func (a *Auth) GetAppKey() string {
return "naiba"
}
// GetAppSecret ..
func (a *Auth) GetAppSecret() string {
return "nbsecret"
}