actions.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package main
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "math/rand"
  8. "net/http"
  9. "sparrow/pkg/models"
  10. "sparrow/pkg/rpcs"
  11. "sparrow/pkg/server"
  12. "sparrow/pkg/token"
  13. "strings"
  14. "github.com/opentracing/opentracing-go/ext"
  15. "github.com/opentracing/opentracing-go"
  16. "github.com/martini-contrib/render"
  17. )
  18. const (
  19. ErrOK = 0
  20. ErrSystemFault = 10001
  21. ErrDeviceNotFound = 10002
  22. ErrWrongSecret = 10003
  23. ErrProtocolNotSuported = 10004
  24. )
  25. func renderError(code int, err error) Common {
  26. result := Common{}
  27. result.Code = code
  28. result.Message = err.Error()
  29. server.Log.Error(err.Error())
  30. return result
  31. }
  32. // DeviceRegisterArgs device register args
  33. type DeviceRegisterArgs struct {
  34. ProductKey string `json:"product_key" binding:"required"`
  35. DeviceCode string `json:"device_code" binding:"required"`
  36. Version string `json:"version" binding:"required"`
  37. ModuleName string `json:"module" binding:"required"`
  38. }
  39. // DeviceAuthArgs device authentication args
  40. type DeviceAuthArgs struct {
  41. DeviceId int64 `json:"device_id" binding:"required"`
  42. DeviceSecret string `json:"device_secret" binding:"required"`
  43. Protocol string `json:"protocol" binding:"required"`
  44. }
  45. // RegisterDevice 设备激活
  46. func RegisterDevice(args DeviceRegisterArgs, r render.Render) {
  47. server.Log.Printf("ACTION RegisterDevice, args:: %v ", args)
  48. rpcargs := &rpcs.ArgsDeviceRegister{
  49. ProductKey: args.ProductKey,
  50. DeviceCode: args.DeviceCode,
  51. DeviceVersion: args.Version,
  52. ModuleName: args.ModuleName,
  53. }
  54. device := &models.Device{}
  55. err := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.RegisterDevice", rpcargs, device)
  56. if err != nil {
  57. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  58. return
  59. }
  60. server.Log.Infof("register device success: %v", device)
  61. result := DeviceRegisterResponse{}
  62. result.Data = DeviceRegisterData{
  63. DeviceId: int64(device.ID),
  64. DeviceSecret: device.DeviceSecret,
  65. DeviceKey: device.DeviceKey,
  66. DeviceIdentifier: device.DeviceIdentifier,
  67. }
  68. r.JSON(http.StatusOK, result)
  69. return
  70. }
  71. // AuthDevice device auth
  72. func AuthDevice(args DeviceAuthArgs, r render.Render) {
  73. server.Log.Printf("ACTION AuthDevice, args:: %v", args)
  74. device := &models.Device{}
  75. span, ctx := opentracing.StartSpanFromContext(context.Background(), "AuthDevice")
  76. defer span.Finish()
  77. ext.SpanKindRPCClient.Set(span)
  78. arg := uint64(args.DeviceId)
  79. err := server.RPCCallByName(ctx, rpcs.RegistryServerName, "Registry.FindDeviceById", &arg, device)
  80. if err != nil {
  81. r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
  82. return
  83. }
  84. fmt.Printf(fmt.Sprintf("%s, %s", device.DeviceSecret, args.DeviceSecret))
  85. if device.DeviceSecret != args.DeviceSecret {
  86. // device secret is wrong.
  87. r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong device secret.")))
  88. return
  89. }
  90. hepler := token.NewHelper(*confRedisHost, *confRedisPort, *confRedisDb)
  91. token, err := hepler.GenerateToken(device.RecordId)
  92. if err != nil {
  93. r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
  94. return
  95. }
  96. var hosts []string
  97. switch args.Protocol {
  98. case "http":
  99. hosts, err = server.GetServerHosts(strings.ToUpper(args.Protocol)+"Access", "httphost")
  100. case "mqtt":
  101. hosts, err = server.GetServerHosts(strings.ToUpper(args.Protocol)+"Access", "tcphost")
  102. case "coap":
  103. hosts, err = server.GetServerHosts(strings.ToUpper(args.Protocol)+"Access", "udphost")
  104. default:
  105. err = errors.New("unsuported protocol: " + args.Protocol)
  106. }
  107. if err != nil {
  108. r.JSON(http.StatusOK, renderError(ErrProtocolNotSuported, err))
  109. return
  110. }
  111. // just get a random host
  112. host := hosts[rand.Intn(len(hosts))]
  113. result := DeviceAuthResponse{}
  114. result.Data = DeviceAuthData{
  115. AccessToken: hex.EncodeToString(token),
  116. AccessAddr: host,
  117. }
  118. server.Log.Infof("auth device success: %v, token: %x, access: %v", device, token, host)
  119. r.JSON(http.StatusOK, result)
  120. return
  121. }