user.go 9.6 KB

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