user.go 8.4 KB

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