lijian 1 год назад
Родитель
Сommit
17ac689299
1 измененных файлов с 54 добавлено и 9 удалено
  1. 54 9
      services/httpaccess/actions.go

+ 54 - 9
services/httpaccess/actions.go

@@ -11,12 +11,9 @@ import (
 	"sparrow/pkg/rpcs"
 	"sparrow/pkg/server"
 	"sparrow/pkg/token"
+	"strconv"
 	"strings"
 
-	"github.com/opentracing/opentracing-go/ext"
-
-	"github.com/opentracing/opentracing-go"
-
 	"github.com/martini-contrib/render"
 )
 
@@ -94,20 +91,59 @@ func RegisterDevice(args DeviceRegisterArgs, r render.Render) {
 func DeviceAccessAuth(args AccessAuthArgs, r render.Render) {
 	server.Log.Printf("ACTION DeviceAccessAuth, args:: %v", args)
 	result := AccessAuthResp{}
+	deviceId, err := ClientIDToDeviceID(args.UserName)
+	if err != nil {
+		server.Log.Errorf("invalid Identify: %s", args.UserName)
+		result.Result = "deny"
+		r.JSON(http.StatusOK, result)
+		return
+	}
+	device := &models.Device{}
+	err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.FindDeviceById", deviceId, device)
+	if err != nil {
+		server.Log.Errorf("device not found %d", deviceId)
+		result.Result = "deny"
+		r.JSON(http.StatusOK, result)
+		return
+	}
+	// parse token
+	token, err := hex.DecodeString(args.Password)
+	if err != nil {
+		server.Log.Errorf("token format error : %v", err)
+		result.Result = "deny"
+		r.JSON(http.StatusOK, result)
+		return
+	}
+	// validate token
+	if err := validateToken(device.RecordId, token); err != nil {
+		server.Log.Errorf("validate token error : %v", err)
+		result.Result = "deny"
+		r.JSON(http.StatusOK, result)
+		return
+	}
 	result.Result = "allow"
 	r.JSON(http.StatusOK, result)
 }
 
+func validateToken(deviceRecordId string, token []byte) error {
+	args := rpcs.ArgsValidateDeviceAccessToken{
+		Id:          deviceRecordId,
+		AccessToken: token,
+	}
+	reply := rpcs.ReplyValidateDeviceAccessToken{}
+	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.ValidateDeviceAccessToken", args, &reply)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
 // AuthDevice device auth
 func AuthDevice(args DeviceAuthArgs, r render.Render) {
 	device := &models.Device{}
 
-	span, ctx := opentracing.StartSpanFromContext(context.Background(), "AuthDevice")
-	defer span.Finish()
-
-	ext.SpanKindRPCClient.Set(span)
 	arg := uint64(args.DeviceId)
-	err := server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.FindDeviceById", &arg, device)
+	err := server.RPCCallByName(context.Background(), rpcs.RegistryServerName, "Registry.FindDeviceById", &arg, device)
 	if err != nil {
 		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
 		return
@@ -160,3 +196,12 @@ func AuthDevice(args DeviceAuthArgs, r render.Render) {
 	r.JSON(http.StatusOK, result)
 	return
 }
+
+func ClientIDToDeviceID(identify string) (uint64, error) {
+	deviceId, err := strconv.ParseUint(identify, 16, 64)
+	if err != nil {
+		return uint64(0), err
+	}
+
+	return deviceId, nil
+}