api_base_controller.go 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "sws_xcx/enums"
  7. "sws_xcx/models"
  8. "sws_xcx/service"
  9. "sws_xcx/utils"
  10. "net/http"
  11. "time"
  12. "github.com/astaxie/beego"
  13. "github.com/dgrijalva/jwt-go"
  14. "github.com/google/uuid"
  15. )
  16. func ApiControllersRegisterRouters() {
  17. //接收MQTT消息
  18. beego.Router("/xcx/api/device/emqmsg", &MessageApiControllor{}, "Post:PutEmqxMessage")
  19. beego.Router("/xcx/api/user/login", &LoginApiController{}, "Post:WxXcxLogin")
  20. beego.Router("/xcx/api/user/updatephonebycode", &UserApiController{}, "Post:UpdatePhoneByCode")
  21. beego.Router("/xcx/api/user/getuserinfo", &UserApiController{}, "Get:GetUserInfo")
  22. beego.Router("/xcx/api/user/savehealthprofile", &UserApiController{}, "Post:SaveHealthProfile")
  23. beego.Router("/xcx/api/user/saveuserinfo", &UserApiController{}, "Post:SaveUserInfo")
  24. beego.Router("/xcx/api/user/gethealthprofile", &UserApiController{}, "Get:GetHealthProfile")
  25. beego.Router("/xcx/api/sysdic/getillness", &SysDicApiController{}, "Get:GetIllness")
  26. beego.Router("/xcx/api/sysdic/getrenalstatus", &SysDicApiController{}, "Get:GetRenalStatus")
  27. beego.Router("/xcx/api/sysdic/getcheckitems", &SysDicApiController{}, "Get:GetCheckItems")
  28. beego.Router("/xcx/api/sysdic/getdevicetypes", &SysDicApiController{}, "Get:GetDeviceTypes")
  29. }
  30. type BaseApiController struct {
  31. beego.Controller
  32. }
  33. func (c *BaseApiController) Prepare() {
  34. }
  35. type BaseApiAuthController struct {
  36. BaseApiController
  37. CurrentUser models.XcxUser
  38. sessionKey string
  39. }
  40. func (c *BaseApiAuthController) Prepare() {
  41. c.BaseApiController.Prepare()
  42. // JWT Token通常放在请求头中,例如Authorization: Bearer <token>
  43. authHeader := c.Ctx.Input.Header("Authorization")
  44. if authHeader == "" {
  45. c.ServeFailJsonSendAndStop(http.StatusUnauthorized, enums.ErrorCodeNotLogin, "缺少认证信息")
  46. return
  47. }
  48. tokenString := authHeader
  49. if strings.Contains(authHeader, "Bearer") {
  50. tokenString = authHeader[len("Bearer "):]
  51. }
  52. token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  53. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  54. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  55. }
  56. //从配置文件中获取secret
  57. secret := beego.AppConfig.String("xsrfkey")
  58. return []byte(secret), nil
  59. })
  60. if err != nil || !token.Valid {
  61. utils.ErrorLog("Token验证失败: %v", err)
  62. c.ServeFailJsonSendAndStop(http.StatusUnauthorized, enums.ErrorCodeNotLogin, "无效的Token")
  63. return
  64. }
  65. // 假设JWT中包含了用户ID
  66. claims, ok := token.Claims.(*CustomClaims)
  67. if !ok {
  68. c.ServeFailJsonSendAndStop(http.StatusUnauthorized, enums.ErrorCodeNotLogin, "无法解析Token中的信息")
  69. return
  70. }
  71. key := claims.UserID
  72. c.sessionKey = key
  73. redisCli := service.RedisClient()
  74. defer redisCli.Close()
  75. uJson, err := redisCli.Get(fmt.Sprintf("session:%v", key)).Bytes()
  76. if err != nil {
  77. c.ServeFailJsonSendAndStop(http.StatusUnauthorized, enums.ErrorCodeNotLogin, fmt.Sprintf("redis err:%v", err))
  78. return
  79. }
  80. user := &models.XcxUser{}
  81. err = json.Unmarshal(uJson, user)
  82. if err != nil {
  83. c.ServeFailJsonSendAndStop(http.StatusUnauthorized, enums.ErrorCodeNotLogin, fmt.Sprintf("json err:%v", err))
  84. return
  85. }
  86. //c.Ctx.Input.SetData("user", user)
  87. c.CurrentUser = *user
  88. //c.SetSession("user", user)
  89. }
  90. type CustomClaims struct {
  91. UserID string `json:"sessionkey"`
  92. jwt.StandardClaims
  93. }
  94. // 输出数据格式化
  95. /*
  96. success json:
  97. {
  98. "state": 1,
  99. "code": 0,
  100. "data": json,
  101. }
  102. fail json:
  103. {
  104. "state": 0,
  105. "code": int,
  106. "msg": string,
  107. }
  108. */
  109. func (c *BaseApiController) ServeSuccessJSON(data interface{}) {
  110. c.Data["json"] = enums.MakeSuccessResponseJSON(data)
  111. c.ServeJSON()
  112. }
  113. func (c *BaseApiController) ServeFailJSONWithSGJErrorCode(code int) {
  114. c.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
  115. c.ServeJSON()
  116. }
  117. func (c *BaseApiController) ServeFailJSONWithSGJError(err *enums.SGJError) {
  118. c.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
  119. c.ServeJSON()
  120. }
  121. func (c *BaseApiController) ServeFailJsonSend(code int, msg string) {
  122. c.Data["json"] = enums.MakeFailResponseJSON(msg, code)
  123. c.ServeJSON()
  124. }
  125. func (c *BaseApiController) ServeDynamicFailJsonSend(msg string) {
  126. c.Data["json"] = enums.MakeDynamicFailResponseJSON(msg)
  127. c.ServeJSON()
  128. }
  129. func (c *BaseApiController) ServeFailJsonSendAndStop(httpStatus int, errCode int, msg string) {
  130. c.Ctx.Output.SetStatus(httpStatus)
  131. c.ServeFailJsonSend(errCode, msg)
  132. c.StopRun()
  133. }
  134. func (c *BaseApiController) login(u models.XcxUser) (string, error) {
  135. key := uuid.New().String()
  136. expire, _ := beego.AppConfig.Int("xsrfexpire")
  137. if expire == 0 {
  138. expire = 7200
  139. }
  140. uJson, _ := json.Marshal(u)
  141. redisCli := service.RedisClient()
  142. defer redisCli.Close()
  143. redisCli.Set(fmt.Sprintf("session:%v", key), uJson, time.Second*time.Duration(expire))
  144. // 创建一个我们自己的声明
  145. claims := CustomClaims{
  146. UserID: key,
  147. StandardClaims: jwt.StandardClaims{
  148. ExpiresAt: time.Now().Add(time.Second * time.Duration(expire)).Unix(), // Token有效期(默认为7200秒)
  149. Issuer: "sws_xcx", // 签发者
  150. },
  151. }
  152. // 使用指定的签名方法创建签名
  153. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  154. // 使用密钥签名并获得完整的编码后的字符串形式的Token
  155. return token.SignedString([]byte(beego.AppConfig.String("xsrfkey")))
  156. }
  157. func (c *BaseApiAuthController) updateCurrentUser(updateAction func(*models.XcxUser)) error {
  158. u := &c.CurrentUser
  159. updateAction(u)
  160. err := service.NewXcxUserService().UpdateUser(u)
  161. if err != nil {
  162. //c.ServeFailJsonSendAndStop(http.StatusOK, enums.ErrorCodeDBUpdate, "更新用户信息失败")
  163. return err
  164. }
  165. redisCli := service.RedisClient()
  166. defer redisCli.Close()
  167. uJson, _ := json.Marshal(u)
  168. expire, _ := beego.AppConfig.Int("xsrfexpire")
  169. if expire == 0 {
  170. expire = 7200
  171. }
  172. err = redisCli.Set(fmt.Sprintf("session:%v", c.sessionKey), uJson, time.Second*time.Duration(expire)).Err()
  173. if err != nil {
  174. return err
  175. }
  176. c.CurrentUser = *u
  177. return nil
  178. }