Browse Source

添加用户手机号登录的author权限校验

xingzai 2 years ago
parent
commit
ba3aad58d0

+ 5 - 1
controllers/article.go

@@ -33,6 +33,10 @@ type ArticleCommonController struct {
 	BaseCommonController
 }
 
+type ArticleControllerMobile struct {
+	BaseAuthMobileController
+}
+
 // @Title 获取报告详情
 // @Description 获取报告详情接口
 // @Param   ArticleId   query   int  true       "报告ID"
@@ -536,7 +540,7 @@ func (this *ArticleController) InterviewApply() {
 // @Param   ArticleIdMd5   query   int  true       "报告ID"
 // @Success 200 {object} models.ArticleDetailResp
 // @router /look/detail [get]
-func (this *ArticleController) DetailMd5() {
+func (this *ArticleControllerMobile) DetailMd5() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br

+ 137 - 0
controllers/base_auth_mobile.go

@@ -0,0 +1,137 @@
+package controllers
+
+import (
+	"encoding/json"
+	"fmt"
+	beego "github.com/beego/beego/v2/adapter"
+	"hongze/hongze_cygx/services"
+	"net/http"
+	"net/url"
+	"strconv"
+
+	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/utils"
+
+	"github.com/rdlucklib/rdluck_tools/log"
+)
+
+func init() {
+	if utils.RunMode == "release" {
+		logDir := `/data/rdlucklog/hongze_cygx`
+		apiLog = log.Init("20060102.api", logDir)
+	} else {
+		apiLog = log.Init("20060102.api")
+	}
+}
+
+type BaseAuthMobileController struct {
+	beego.Controller
+	User  *models.WxUserItem
+	Token string
+}
+
+func (this *BaseAuthMobileController) Prepare() {
+	fmt.Println("enter prepare")
+	method := this.Ctx.Input.Method()
+	uri := this.Ctx.Input.URI()
+	fmt.Println("Url:", uri)
+	if method != "HEAD" {
+		if method == "POST" || method == "GET" {
+			authorization := this.Ctx.Input.Header("Authorization")
+			if authorization == "" {
+				authorization = this.GetString("Authorization")
+			}
+			this.Token = authorization
+			if authorization == "" {
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
+				this.StopRun()
+				return
+			}
+			session, err := models.GetCygxSessionMobile(authorization)
+			if err != nil {
+				if err.Error() == utils.ErrNoRow() {
+					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + authorization}, false, false)
+					this.StopRun()
+					return
+				}
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
+				this.StopRun()
+				return
+			}
+			if session == nil {
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
+				this.StopRun()
+				return
+			}
+			//wxUser, err := models.GetWxUserItemByUserId(session.UserId)
+			wxUser, err := models.GetWxUserItemByMobile(session.Mobile)
+			if err != nil && err != services.ERR_USER_NOT_BIND {
+				if err.Error() == utils.ErrNoRow() {
+					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取信息失败 " + strconv.Itoa(session.UserId)}, false, false)
+					this.StopRun()
+					return
+				}
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取wx_user信息异常,Eerr:" + err.Error()}, false, false)
+				this.StopRun()
+				return
+			}
+			if wxUser == nil {
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
+				this.StopRun()
+				return
+			}
+			this.User = wxUser
+		} else {
+			this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
+			this.StopRun()
+			return
+		}
+	}
+}
+
+func (c *BaseAuthMobileController) ServeJSON(encoding ...bool) {
+	var (
+		hasIndent   = false
+		hasEncoding = false
+	)
+	if beego.BConfig.RunMode == beego.PROD {
+		hasIndent = false
+	}
+	if len(encoding) > 0 && encoding[0] == true {
+		hasEncoding = true
+	}
+	if c.Data["json"] == nil {
+		go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
+		return
+	}
+	baseRes := c.Data["json"].(*models.BaseResponse)
+	if baseRes != nil && baseRes.Ret != 200 && baseRes.Ret != 408 && baseRes.IsSendEmail {
+		body, _ := json.Marshal(baseRes)
+		msgBody := "URI:" + c.Ctx.Input.URI() + "<br/> ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + ";<br/>" + c.Token
+		go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+" 失败提醒", msgBody, utils.EmailSendToUsers)
+	}
+
+	c.JSON(c.Data["json"], hasIndent, hasEncoding)
+}
+
+func (c *BaseAuthMobileController) JSON(data interface{}, hasIndent bool, coding bool) error {
+	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
+	var content []byte
+	var err error
+	if hasIndent {
+		content, err = json.MarshalIndent(data, "", "  ")
+	} else {
+		content, err = json.Marshal(data)
+	}
+	if err != nil {
+		http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
+		return err
+	}
+	ip := c.Ctx.Input.IP()
+	requestBody, _ := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
+	apiLog.Println("请求地址:", c.Ctx.Input.URI(), "Authorization:", c.Ctx.Input.Header("Authorization"), "RequestBody:", requestBody, "ResponseBody", string(content), "IP:", ip)
+	if coding {
+		content = []byte(utils.StringsToJSON(string(content)))
+	}
+	return c.Ctx.Output.Body(content)
+}

+ 20 - 105
controllers/user.go

@@ -1297,102 +1297,36 @@ func (this *UserCommonController) LoginPublic() {
 		br.ErrMsg = "参数解析失败,Err:" + err.Error()
 		return
 	}
-	user, err := models.GetWxUserItemByMobile(req.Mobile)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "登录失败!"
-		br.ErrMsg = "获取手机号用户信息失败,Err:" + err.Error()
-		return
-	}
-	if user == nil {
-		br.Msg = "用户不存在"
-		br.Ret = 408
-		return
-	}
 
-	userRecord, err := models.GetUserRecordByUserId(user.UserId, utils.WxPlatform)
-	if err != nil {
-		br.Msg = "用户不存在!"
-		br.ErrMsg = "用户OPID不存在,Err:" + err.Error()
-		return
-	}
-
-	unionId := userRecord.UnionId
-	openId := userRecord.OpenId
-	if unionId == "" {
+	mobile := strings.Trim(req.Mobile, " ")
+	if req.Mobile == "" {
 		br.Msg = "参数错误"
-		br.ErrMsg = "参数错误,unionId 为空"
+		br.ErrMsg = "参数错误,手机号为空 为空"
 		return
 	}
-	if req.LoginType == 1 || req.LoginType == 3 {
-		if req.Mobile == "" {
-			br.Msg = "参数错误"
-			br.ErrMsg = "参数错误,手机号为空 为空"
-			return
-		}
-		if req.LoginType == 3 {
-			item, err := models.GetMsgCode(req.Mobile, req.VCode)
-			if err != nil {
-				if err.Error() == utils.ErrNoRow() {
-					br.Msg = "验证码错误,请重新输入"
-					br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-					return
-				} else {
-					br.Msg = "验证码错误,请重新输入"
-					br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-					return
-				}
-			}
-			if item == nil {
-				br.Msg = "验证码错误,请重新输入"
-				return
-			}
-		}
-		req.Mobile = strings.Trim(req.Mobile, " ")
-	} else if req.LoginType == 2 {
-		if req.Email == "" {
-			br.ErrMsg = "邮箱不能为空,请输入邮箱"
-			br.Msg = "邮箱不能为空,请输入邮箱"
-			return
-		}
-		if !utils.ValidateEmailFormatat(req.Email) {
-			br.ErrMsg = "邮箱格式错误,请重新输入"
-			br.Msg = "邮箱格式错误,请重新输入"
+
+	item, err := models.GetMsgCode(req.Mobile, req.VCode)
+	if err != nil {
+		if err.Error() == utils.ErrNoRow() {
+			br.Msg = "验证码错误,请重新输入"
+			br.ErrMsg = "校验验证码失败,Err:" + err.Error()
 			return
-		}
-		item, err := models.GetMsgCode(req.Email, req.VCode)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			} else {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			}
-		}
-		if item == nil {
+		} else {
 			br.Msg = "验证码错误,请重新输入"
+			br.ErrMsg = "校验验证码失败,Err:" + err.Error()
 			return
 		}
-	} else {
-		br.Msg = "无效的登录方式"
-		br.ErrMsg = "无效的登录方式,Err:" + err.Error()
+	}
+	if item == nil {
+		br.Msg = "验证码错误,请重新输入"
 		return
 	}
+
 	if len(req.Mobile) >= 11 && req.CountryCode == "" {
 		req.CountryCode = "86"
 	}
-
-	user, err = services.BindWxUser(openId, req.Mobile, req.Email, req.CountryCode)
-	if err != nil {
-		br.Msg = "登录失败"
-		br.ErrMsg = "绑定手机号失败:" + err.Error()
-		return
-	}
-	userId := user.UserId
 	var token string
-	tokenItem, err := models.GetTokenByOpenId(openId)
+	tokenItem, err := models.GetSessionMobileTokenByOpenId(mobile)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		br.Msg = "登录失败"
 		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
@@ -1401,18 +1335,16 @@ func (this *UserCommonController) LoginPublic() {
 	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
 		timeUnix := time.Now().Unix()
 		timeUnixStr := strconv.FormatInt(timeUnix, 10)
-		token = utils.MD5(openId) + utils.MD5(timeUnixStr)
+		token = utils.MD5(mobile) + utils.MD5(timeUnixStr)
 		//新增session
 		{
-			session := new(models.CygxSession)
-			session.OpenId = unionId
-			session.UnionId = unionId
-			session.UserId = userId
+			session := new(models.CygxSessionMobile)
+			session.Mobile = mobile
 			session.CreatedTime = time.Now()
 			session.LastUpdatedTime = time.Now()
 			session.ExpireTime = time.Now().AddDate(0, 1, 0)
 			session.AccessToken = token
-			err = models.AddSession(session)
+			err = models.AddCygxSessionMobile(session)
 			if err != nil {
 				br.Msg = "登录失败"
 				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
@@ -1422,25 +1354,8 @@ func (this *UserCommonController) LoginPublic() {
 	} else {
 		token = tokenItem.AccessToken
 	}
-
-	//新增登录日志
-	{
-		loginLog := new(models.WxUserLog)
-		loginLog.UserId = userId
-		loginLog.OpenId = unionId
-		loginLog.Mobile = req.Mobile
-		loginLog.Email = req.Email
-		loginLog.CreateTime = time.Now()
-		loginLog.Handle = "wechat_user_login"
-		loginLog.Remark = token
-		go models.AddWxUserLog(loginLog)
-	}
 	resp := new(models.LoginResp)
-	resp.UserId = userId
 	resp.Authorization = token
-	if user.CompanyId == 1 {
-		resp.IsPotential = true
-	}
 	br.Ret = 200
 	br.Success = true
 	br.Data = resp

+ 1 - 0
models/db.go

@@ -109,6 +109,7 @@ func init() {
 		new(CygxUserInteractionNum),
 		new(CygxChartCollectByCygx),
 		new(CygxCompanyInteractionNum),
+		new(CygxSessionMobile),
 	)
 	// 记录ORM查询日志
 	orm.Debug = true

+ 45 - 0
models/session_mobile.go

@@ -0,0 +1,45 @@
+package models
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+type CygxSessionMobile struct {
+	SessionId       int `orm:"column(session_id);pk"`
+	Mobile          string
+	UserId          int
+	AccessToken     string
+	ExpireTime      time.Time
+	CreatedTime     time.Time
+	LastUpdatedTime time.Time
+}
+
+func GetCygxSessionMobile(token string) (item *CygxSessionMobile, err error) {
+	sql := `SELECT * FROM cygx_session_mobile WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	err = o.Raw(sql, token).QueryRow(&item)
+	return
+}
+
+func GetSessionMobileCountByToken(token string) (count int, err error) {
+	sql := `SELECT COUNT(1) AS count FROM cygx_session_mobile WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	err = o.Raw(sql, token).QueryRow(&count)
+	return
+}
+
+//添加用户session信息
+func AddCygxSessionMobile(item *CygxSessionMobile) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Insert(item)
+	return
+}
+
+//根据用户id获取token
+func GetSessionMobileTokenByOpenId(openId string) (item *CygxSession, err error) {
+	sql := `SELECT * FROM cygx_session_mobile WHERE mobile=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	err = o.Raw(sql, openId).QueryRow(&item)
+	return
+}

+ 5 - 5
routers/commentsRouter_controllers.go

@@ -315,17 +315,17 @@ func init() {
 
     beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleController"] = append(beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleController"],
         beego.ControllerComments{
-            Method: "DetailMd5",
-            Router: "/look/detail",
+            Method: "Pdfwatermark",
+            Router: "/pdfwatermark",
             AllowHTTPMethods: []string{"get"},
             MethodParams: param.Make(),
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleController"] = append(beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleController"],
+    beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleControllerMobile"] = append(beego.GlobalControllerRouter["hongze/hongze_cygx/controllers:ArticleControllerMobile"],
         beego.ControllerComments{
-            Method: "Pdfwatermark",
-            Router: "/pdfwatermark",
+            Method: "DetailMd5",
+            Router: "/look/detail",
             AllowHTTPMethods: []string{"get"},
             MethodParams: param.Make(),
             Filters: nil,

+ 1 - 0
routers/router.go

@@ -53,6 +53,7 @@ func init() {
 			web.NSInclude(
 				&controllers.ArticleController{},
 				&controllers.ArticleCommonController{},
+				&controllers.ArticleControllerMobile{},
 			),
 		),
 		web.NSNamespace("/config",