token.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package token
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "mtp2_if/config"
  9. "mtp2_if/global/e"
  10. "mtp2_if/logger"
  11. "mtp2_if/rediscli"
  12. "net/http"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/gin-gonic/gin"
  18. )
  19. // TouristToken 游客Token
  20. var TouristToken string = "c886a057f3d820d4dbc41473686c7c2d"
  21. // CheckToken Token校验
  22. func CheckToken(loginid string, token string, group string) (string, error) {
  23. key := ""
  24. if len(group) == 0 {
  25. key = fmt.Sprintf("monitor:online_loginid::%s", loginid)
  26. } else {
  27. key = fmt.Sprintf("monitor:online_loginid:%s:%s", loginid, group)
  28. }
  29. field := "Token"
  30. realToken, err := rediscli.GetRedisClient().HGet(key, field).Result()
  31. if err != nil {
  32. return "", err
  33. }
  34. if realToken != token {
  35. return "", errors.New("token is invalid")
  36. }
  37. // 获取UserID
  38. userID, err := rediscli.GetRedisClient().HGet(key, "UserID").Result()
  39. return userID, err
  40. }
  41. // Auth Token校验中间件
  42. func Auth() gin.HandlerFunc {
  43. return func(c *gin.Context) {
  44. // if config.SerCfg.GetDebugMode() {
  45. // c.Next()
  46. // return
  47. // }
  48. // windows下方便开发调试, 不做token校验
  49. if config.SerCfg.GetDebugMode() &&
  50. runtime.GOOS == "windows" {
  51. c.Next()
  52. return
  53. }
  54. var code int
  55. var data interface{}
  56. userID := ""
  57. code = e.SUCCESS
  58. token := c.GetHeader("Authorization")
  59. if token == "" {
  60. // Token缺失
  61. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  62. } else {
  63. // 获取loginid
  64. s := strings.Split(token, "_")
  65. loginid := s[0]
  66. // 支持分组功能
  67. group := ""
  68. if len(s) == 3 {
  69. group = s[2]
  70. }
  71. var err error
  72. userID, err = CheckToken(loginid, token, group)
  73. if err != nil {
  74. // Token错误
  75. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  76. }
  77. }
  78. // Token检验失败
  79. if code != e.SUCCESS {
  80. c.JSON(http.StatusUnauthorized, gin.H{
  81. "code": code,
  82. "msg": e.GetMsg(code),
  83. "data": data,
  84. })
  85. c.Abort()
  86. return
  87. }
  88. // FIXME: - 针对POST接口,应判断传入TOKEN对应的用户是否正确(比如判断UserID或AccountID是否对得上等),后期处理
  89. if c.Request.Method == "POST" {
  90. c.Set("requserid", userID)
  91. }
  92. if config.SerCfg.GetApiKeyMode() {
  93. timestamp := c.GetHeader("Timestamp")
  94. verification := c.GetHeader("Verification")
  95. if timestamp == "" || token == "" || verification == "" {
  96. c.JSON(http.StatusUnauthorized, gin.H{
  97. "code": e.ERROR,
  98. "msg": "apikey1",
  99. "data": struct{}{},
  100. })
  101. c.Abort()
  102. return
  103. }
  104. // 判断时间,10S之内有效
  105. t, err := strconv.Atoi(timestamp)
  106. if err != nil {
  107. c.JSON(http.StatusUnauthorized, gin.H{
  108. "code": e.ERROR,
  109. "msg": "apikey2",
  110. "data": struct{}{},
  111. })
  112. c.Abort()
  113. return
  114. }
  115. now := time.Now().UnixMilli()
  116. ts := int64(t) - now
  117. logger.GetLogger().Debugf("t:%v now:%v ts: %v", t, now, ts)
  118. if ts < -10*1000 && ts > 10*1000 {
  119. c.JSON(http.StatusUnauthorized, gin.H{
  120. "code": e.ERROR,
  121. "msg": "apikey3",
  122. "data": struct{}{},
  123. })
  124. c.Abort()
  125. return
  126. }
  127. s := fmt.Sprintf("%s%s", token, timestamp)
  128. hashed := hmac.New(sha256.New, []byte(config.SerCfg.WebCfg.ApiKey))
  129. hashed.Write([]byte(s))
  130. h := hex.EncodeToString(hashed.Sum(nil))
  131. if h == "" {
  132. c.JSON(http.StatusUnauthorized, gin.H{
  133. "code": e.ERROR,
  134. "msg": "apikey4",
  135. "data": struct{}{},
  136. })
  137. c.Abort()
  138. return
  139. }
  140. if h != verification {
  141. c.JSON(http.StatusUnauthorized, gin.H{
  142. "code": e.ERROR,
  143. "msg": "apikey5",
  144. "data": struct{}{},
  145. })
  146. c.Abort()
  147. return
  148. }
  149. }
  150. // Token检验成功
  151. c.Next()
  152. }
  153. }
  154. // AuthByHsby 游客鉴权
  155. func AuthByHsby() gin.HandlerFunc {
  156. return func(c *gin.Context) {
  157. // 包含accountID、accountIDs、userID和userIDs等参数需要走正常鉴权
  158. accountID := c.Query("accountID")
  159. accountIDs := c.Query("accountIDs")
  160. userID := c.Query("userID")
  161. userIDs := c.Query("userIDs")
  162. loginID := c.Query("loginID")
  163. if len(accountID) != 0 || len(accountIDs) != 0 || len(userID) != 0 || len(userIDs) != 0 || len(loginID) != 0 {
  164. realToken(c)
  165. return
  166. }
  167. var code int
  168. var data interface{}
  169. code = e.SUCCESS
  170. token := c.GetHeader("Authorization")
  171. if token == "" {
  172. // Token缺失
  173. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  174. } else {
  175. // Token带下划线的走正常鉴权
  176. if strings.Contains(token, "_") {
  177. realToken(c)
  178. return
  179. }
  180. if token != TouristToken {
  181. // Token错误
  182. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  183. }
  184. }
  185. // Token检验失败
  186. if code != e.SUCCESS {
  187. c.JSON(http.StatusUnauthorized, gin.H{
  188. "code": code,
  189. "msg": e.GetMsg(code),
  190. "data": data,
  191. })
  192. c.Abort()
  193. return
  194. }
  195. // Token检验成功
  196. c.Next()
  197. }
  198. }
  199. func realToken(c *gin.Context) {
  200. // if config.SerCfg.GetDebugMode() {
  201. // c.Next()
  202. // return
  203. // }
  204. var code int
  205. var data interface{}
  206. code = e.SUCCESS
  207. token := c.GetHeader("Authorization")
  208. if token == "" {
  209. // Token缺失
  210. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  211. } else {
  212. // 获取loginid
  213. s := strings.Split(token, "_")
  214. loginid := s[0]
  215. // 支持分组功能
  216. group := ""
  217. if len(s) == 3 {
  218. group = s[2]
  219. }
  220. if _, err := CheckToken(loginid, token, group); err != nil {
  221. // Token错误
  222. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  223. }
  224. }
  225. // Token检验失败
  226. if code != e.SUCCESS {
  227. c.JSON(http.StatusUnauthorized, gin.H{
  228. "code": code,
  229. "msg": e.GetMsg(code),
  230. "data": data,
  231. })
  232. c.Abort()
  233. return
  234. }
  235. // FIXME: - 针对POST接口,应判断传入TOKEN对应的用户是否正确(比如判断UserID或AccountID是否对得上等),后期处理
  236. // Token检验成功
  237. c.Next()
  238. return
  239. }