user.go 8.6 KB

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