user.go 8.5 KB

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