package api import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "tmr-watch/http/handle/restful" "tmr-watch/pkg/app" "tmr-watch/pkg/e" "tmr-watch/pkg/util" "tmr-watch/service/user_service" "github.com/Anderson-Lu/gofasion/gofasion" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/validation" "github.com/gin-gonic/gin" ) type auth struct { Id int `json:"id"` Username string `json:"username"` Password string `json:"password"` CaptchaKey string `json:"CaptchaKey"` Role int `json:"role_id"` Imei string `json:"imei"` PastureId string `json:"pastureid"` TypeIn int `json:"typein"` } // Auth 获取登录token 信息 func Auth(c *gin.Context) { appG := app.Gin{C: c} var reqInfo auth err := c.BindJSON(&reqInfo) valid := validation.Validation{} valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符") valid.MaxSize(reqInfo.Password, 100, "password").Message("最长为100字符") valid.MinSize(reqInfo.Password, 1, "password").Message("不能为空") valid.MinSize(reqInfo.Password, 1, "password").Message("不能为空") if valid.HasErrors() { app.MarkErrors(valid.Errors) appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors) return } authService := user_service.User{Username: reqInfo.Username, Password: reqInfo.Password} isExist, err := authService.Check() if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err) return } if !isExist { isExist, err = authService.MD5Check() if !isExist { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH, "") return } } token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err) return } appG.Response(http.StatusOK, e.SUCCESS, map[string]string{ "token": token, }) } // @Summary 获取登录token 信息 // @Tags auth // @Accept json // @Produce json // @Param username formData string true "admin" // @Param password formData string true "123456" // @Success 200 {string} json "{ "code": 200e, "data": { "token": "xxx" }, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /auth [POST] func AuthLogin(c *gin.Context) { appG := app.Gin{C: c} var reqInfo auth err := c.BindJSON(&reqInfo) fmt.Println("++++++++++++++++", reqInfo) valid := validation.Validation{} valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符") if valid.HasErrors() { app.MarkErrors(valid.Errors) appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors) return } err = restful.CheckUserFace(reqInfo.Username, reqInfo.Imei, reqInfo.TypeIn) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err.Error()) return } token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err.Error()) return } appG.Response(http.StatusOK, e.SUCCESS, map[string]string{ "token": token, }) } // @Summary 获取单个用户信息 // @Tags users // @Accept json // @Produce json // @Param id body int true "id" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Router /authdata/userinfo [GET] func UserLogout(c *gin.Context) { appG := app.Gin{C: c} data := make(map[string]interface{}) data["name"] = "" data["avatar"] = "" data["introduction"] = "" appG.Response(http.StatusOK, e.SUCCESS, data) } // GetUserinfo 获取单个用户信息 // @Tags users // @Accept json // @Produce json // @Param id path int true "iddd" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Router /authdata/userinfo [GET] func GetUserinfo(c *gin.Context) { appG := app.Gin{C: c} data := restful.GetUserInfo(appG.Get("jwt_username")) appG.Response(http.StatusOK, e.SUCCESS, data) } func GetOpenID(c *gin.Context) { code := c.Param("code") appG := app.Gin{C: c} openid, err := util.SendWxAuthAPI(code) if err != nil { appG.Response(http.StatusOK, e.SUCCESS, map[string]string{ "err": "openid 获取失败 :" + err.Error(), }) return } appG.Response(http.StatusOK, e.SUCCESS, map[string]string{ "openid": openid, }) } func UserWXOpenIDBinding(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) openid := fsion.Get("openid").ValueStr() // pastureid := fsion.Get("pastureid").ValueStr() userinfo := fsion.Get("userinfo").ValueStr() tx := restful.Engine.NewSession() defer tx.Close() userlist := strings.Split(userinfo, ".") fmt.Println(len(userlist), userlist) if len(userlist) < 3 { logs.Error("UserWXOpenIDBinding-error1:", nil) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } _, err := tx.SQL(` replace into user_wx(userid,pastureid,openid,name) VALUES (?,?,?,?)`, userlist[2], userlist[1], openid, userlist[3]).Execute() if err != nil { logs.Error("UserWXOpenIDBinding-error2:", err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } appG.Response(http.StatusOK, e.SUCCESS, true) } func AuthImei(c *gin.Context) { appG := app.Gin{C: c} var reqInfo auth err := c.BindJSON(&reqInfo) //c.Request.ParseForm() //reqInfo.Username = c.PostForm("username") //reqInfo.Password = c.PostForm("pwd") valid := validation.Validation{} valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符") valid.MaxSize(reqInfo.Imei, 100, "imei").Message("最长为100字符") if valid.HasErrors() { app.MarkErrors(valid.Errors) appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors) return } tx := restful.Engine.NewSession() defer tx.Close() isExist, err := tx.SQL(" select id from driver where drivername = ? ", reqInfo.Imei).Exist() if err != nil { logs.Error("AuthImei-error1:", err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } isTmrExist, err := tx.SQL(" select id from tmr where imei = ? ", reqInfo.Imei).Exist() if err != nil { logs.Error("AuthImei-error1:", err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } if !isExist && !isTmrExist { //appG.Response(http.StatusUnauthorized, e.ERROR_AUTH, nil) appG.Response(http.StatusOK, e.ERROR_AUTH, "未注册!!!") return } token, err := util.GenerateToken(reqInfo.Username, reqInfo.Imei) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err) return } appG.Response(http.StatusOK, e.SUCCESS, map[string]string{ "token": token, }) } func GetWxCode(c *gin.Context) { appG := app.Gin{C: c} code := c.Query("code") url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s" var appid, secret, jsCode, grantType string jsCode = code tx := restful.Engine.NewSession() defer tx.Close() wxConfigList, err := tx.SQL(" select * from wx_config where system = ? ", "tmrwatch").Query().List() if err != nil { logs.Error("GetWxCode-error1:", err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } for _, wx := range wxConfigList { grantType = wx["grantType"].(string) appid = wx["appid"].(string) secret = wx["secret"].(string) } url = fmt.Sprintf(url, appid, secret, jsCode, grantType) client := &http.Client{Timeout: 5 * time.Second} payload := strings.NewReader(``) req, err := http.NewRequest(http.MethodGet, url, payload) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err) return } res, err := client.Do(req) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err) return } var data interface{} json.Unmarshal(body, &data) dataMap := data.(map[string]interface{}) if _, ok := dataMap["code"]; !ok { dataMap["code"] = "" } appG.Response(http.StatusOK, e.SUCCESS, dataMap) }