123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293 |
- 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 {
- 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)
- }
|