user.go 8.5 KB

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