Web 服务

This commit is contained in:
奶爸
2019-12-08 16:59:58 +08:00
parent 5a21ce6ca6
commit d8c4364653
33 changed files with 1112 additions and 21 deletions

60
service/rpc/auth.go Normal file
View File

@@ -0,0 +1,60 @@
package rpc
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// AuthHandler ..
type AuthHandler struct {
AppKey string
AppSecret string
}
// GetRequestMetadata ..
func (a *AuthHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"app_key": a.AppKey, "app_secret": a.AppSecret}, nil
}
// RequireTransportSecurity ..
func (a *AuthHandler) RequireTransportSecurity() bool {
return false
}
// Check ..
func (a *AuthHandler) 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 *AuthHandler) GetAppKey() string {
return a.AppKey
}
// GetAppSecret ..
func (a *AuthHandler) GetAppSecret() string {
return a.AppSecret
}

40
service/rpc/nezha.go Normal file
View File

@@ -0,0 +1,40 @@
package rpc
import (
"context"
"fmt"
pb "github.com/p14yground/nezha/proto"
)
// NezhaHandler ..
type NezhaHandler struct {
Auth *AuthHandler
}
// ReportState ..
func (s *NezhaHandler) ReportState(c context.Context, r *pb.State) (*pb.Receipt, error) {
if err := s.Auth.Check(c); err != nil {
return nil, err
}
fmt.Printf("ReportState receive: %s\n", r)
return &pb.Receipt{Proced: true}, nil
}
// Heartbeat ..
func (s *NezhaHandler) Heartbeat(r *pb.Beat, stream pb.NezhaService_HeartbeatServer) error {
if err := s.Auth.Check(stream.Context()); err != nil {
return err
}
fmt.Printf("ReportState receive: %s\n", r)
return nil
}
// Register ..
func (s *NezhaHandler) Register(c context.Context, r *pb.Host) (*pb.Receipt, error) {
if err := s.Auth.Check(c); err != nil {
return nil, err
}
fmt.Printf("Register receive: %s\n", r)
return &pb.Receipt{Proced: true}, nil
}