user.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "tmr-watch/http/handle/restful"
  10. "tmr-watch/pkg/app"
  11. "tmr-watch/pkg/e"
  12. "tmr-watch/pkg/util"
  13. "tmr-watch/service/user_service"
  14. "github.com/Anderson-Lu/gofasion/gofasion"
  15. "github.com/astaxie/beego/logs"
  16. "github.com/astaxie/beego/validation"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type auth struct {
  20. Id int `json:"id"`
  21. Username string `json:"username"`
  22. Password string `json:"password"`
  23. CaptchaKey string `json:"CaptchaKey"`
  24. Role int `json:"role_id"`
  25. Imei string `json:"imei"`
  26. PastureId string `json:"pastureid"`
  27. TypeIn int `json:"typein"`
  28. }
  29. // Auth 获取登录token 信息
  30. func Auth(c *gin.Context) {
  31. appG := app.Gin{C: c}
  32. var reqInfo auth
  33. err := c.BindJSON(&reqInfo)
  34. valid := validation.Validation{}
  35. valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
  36. valid.MaxSize(reqInfo.Password, 100, "password").Message("最长为100字符")
  37. valid.MinSize(reqInfo.Password, 1, "password").Message("不能为空")
  38. valid.MinSize(reqInfo.Password, 1, "password").Message("不能为空")
  39. if valid.HasErrors() {
  40. app.MarkErrors(valid.Errors)
  41. appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors)
  42. return
  43. }
  44. authService := user_service.User{Username: reqInfo.Username, Password: reqInfo.Password}
  45. isExist, err := authService.Check()
  46. if err != nil {
  47. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err)
  48. return
  49. }
  50. if !isExist {
  51. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH, "")
  52. return
  53. }
  54. token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password)
  55. if err != nil {
  56. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
  57. return
  58. }
  59. appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
  60. "token": token,
  61. })
  62. }
  63. // @Summary 获取登录token 信息
  64. // @Tags auth
  65. // @Accept json
  66. // @Produce json
  67. // @Param username formData string true "admin"
  68. // @Param password formData string true "123456"
  69. // @Success 200 {string} json "{ "code": 200e, "data": { "token": "xxx" }, "msg": "ok" }"
  70. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  71. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  72. // @Router /auth [POST]
  73. func AuthLogin(c *gin.Context) {
  74. appG := app.Gin{C: c}
  75. var reqInfo auth
  76. err := c.BindJSON(&reqInfo)
  77. fmt.Println("++++++++++++++++", reqInfo)
  78. valid := validation.Validation{}
  79. valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
  80. if valid.HasErrors() {
  81. app.MarkErrors(valid.Errors)
  82. appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors)
  83. return
  84. }
  85. err = restful.CheckUserFace(reqInfo.Username, reqInfo.Imei, reqInfo.TypeIn)
  86. if err != nil {
  87. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err.Error())
  88. return
  89. }
  90. token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password)
  91. if err != nil {
  92. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err.Error())
  93. return
  94. }
  95. appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
  96. "token": token,
  97. })
  98. }
  99. // @Summary 获取单个用户信息
  100. // @Tags users
  101. // @Accept json
  102. // @Produce json
  103. // @Param id body int true "id"
  104. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  105. // @Router /authdata/userinfo [GET]
  106. func UserLogout(c *gin.Context) {
  107. appG := app.Gin{C: c}
  108. data := make(map[string]interface{})
  109. data["name"] = ""
  110. data["avatar"] = ""
  111. data["introduction"] = ""
  112. appG.Response(http.StatusOK, e.SUCCESS, data)
  113. }
  114. // GetUserinfo 获取单个用户信息
  115. // @Tags users
  116. // @Accept json
  117. // @Produce json
  118. // @Param id path int true "iddd"
  119. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  120. // @Router /authdata/userinfo [GET]
  121. func GetUserinfo(c *gin.Context) {
  122. appG := app.Gin{C: c}
  123. data := restful.GetUserInfo(appG.Get("jwt_username"))
  124. appG.Response(http.StatusOK, e.SUCCESS, data)
  125. }
  126. func GetOpenID(c *gin.Context) {
  127. code := c.Param("code")
  128. appG := app.Gin{C: c}
  129. openid, err := util.SendWxAuthAPI(code)
  130. if err != nil {
  131. appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
  132. "err": "openid 获取失败 :" + err.Error(),
  133. })
  134. return
  135. }
  136. appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
  137. "openid": openid,
  138. })
  139. }
  140. func UserWXOpenIDBinding(c *gin.Context) {
  141. appG := app.Gin{C: c}
  142. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  143. fsion := gofasion.NewFasion(string(dataByte))
  144. openid := fsion.Get("openid").ValueStr()
  145. // pastureid := fsion.Get("pastureid").ValueStr()
  146. userinfo := fsion.Get("userinfo").ValueStr()
  147. tx := restful.Engine.NewSession()
  148. defer tx.Close()
  149. userlist := strings.Split(userinfo, ".")
  150. fmt.Println(len(userlist), userlist)
  151. if len(userlist) < 3 {
  152. logs.Error("UserWXOpenIDBinding-error1:", nil)
  153. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  154. return
  155. }
  156. _, err := tx.SQL(` replace into user_wx(userid,pastureid,openid,name) VALUES (?,?,?,?)`, userlist[2], userlist[1], openid, userlist[3]).Execute()
  157. if err != nil {
  158. logs.Error("UserWXOpenIDBinding-error2:", err)
  159. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  160. return
  161. }
  162. appG.Response(http.StatusOK, e.SUCCESS, true)
  163. }
  164. func AuthImei(c *gin.Context) {
  165. appG := app.Gin{C: c}
  166. var reqInfo auth
  167. err := c.BindJSON(&reqInfo)
  168. //c.Request.ParseForm()
  169. //reqInfo.Username = c.PostForm("username")
  170. //reqInfo.Password = c.PostForm("pwd")
  171. valid := validation.Validation{}
  172. valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
  173. valid.MaxSize(reqInfo.Imei, 100, "imei").Message("最长为100字符")
  174. if valid.HasErrors() {
  175. app.MarkErrors(valid.Errors)
  176. appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors)
  177. return
  178. }
  179. tx := restful.Engine.NewSession()
  180. defer tx.Close()
  181. isExist, err := tx.SQL(" select id from driver where drivername = ? ", reqInfo.Imei).Exist()
  182. if err != nil {
  183. logs.Error("AuthImei-error1:", err)
  184. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  185. return
  186. }
  187. isTmrExist, err := tx.SQL(" select id from tmr where imei = ? ", reqInfo.Imei).Exist()
  188. if err != nil {
  189. logs.Error("AuthImei-error1:", err)
  190. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  191. return
  192. }
  193. if !isExist && !isTmrExist {
  194. //appG.Response(http.StatusUnauthorized, e.ERROR_AUTH, nil)
  195. appG.Response(http.StatusOK, e.ERROR_AUTH, "未注册!!!")
  196. return
  197. }
  198. token, err := util.GenerateToken(reqInfo.Username, reqInfo.Imei)
  199. if err != nil {
  200. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
  201. return
  202. }
  203. appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
  204. "token": token,
  205. })
  206. }
  207. func GetWxCode(c *gin.Context) {
  208. appG := app.Gin{C: c}
  209. code := c.Query("code")
  210. url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s"
  211. var appid, secret, jsCode, grantType string
  212. jsCode = code
  213. tx := restful.Engine.NewSession()
  214. defer tx.Close()
  215. wxConfigList, err := tx.SQL(" select * from wx_config where system = ? ", "tmrwatch").Query().List()
  216. if err != nil {
  217. logs.Error("GetWxCode-error1:", err)
  218. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  219. return
  220. }
  221. for _, wx := range wxConfigList {
  222. grantType = wx["grantType"].(string)
  223. appid = wx["appid"].(string)
  224. secret = wx["secret"].(string)
  225. }
  226. url = fmt.Sprintf(url, appid, secret, jsCode, grantType)
  227. client := &http.Client{Timeout: 5 * time.Second}
  228. payload := strings.NewReader(``)
  229. req, err := http.NewRequest(http.MethodGet, url, payload)
  230. if err != nil {
  231. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
  232. return
  233. }
  234. res, err := client.Do(req)
  235. if err != nil {
  236. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
  237. return
  238. }
  239. defer res.Body.Close()
  240. body, err := ioutil.ReadAll(res.Body)
  241. if err != nil {
  242. appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
  243. return
  244. }
  245. var data interface{}
  246. json.Unmarshal(body, &data)
  247. dataMap := data.(map[string]interface{})
  248. if _, ok := dataMap["code"]; !ok {
  249. dataMap["code"] = ""
  250. }
  251. appG.Response(http.StatusOK, e.SUCCESS, dataMap)
  252. }