user.go 9.8 KB

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