Parcourir la source

feat(用户信息调整):第三方用户与系统用户的关系逻辑调整

Roc il y a 4 ans
Parent
commit
2b39706099

+ 2 - 0
.gitignore

@@ -12,3 +12,5 @@
 /swagger
 /binlog
 /rdlucklog
+.DS_Store
+/rdlucklog/*

+ 11 - 1
controllers/base_auth.go

@@ -3,6 +3,7 @@ package controllers
 import (
 	"encoding/json"
 	"fmt"
+	"hongze/hongze_api/services"
 	"net/http"
 	"net/url"
 	"strconv"
@@ -61,8 +62,17 @@ func (this *BaseAuthController) Prepare() {
 				this.StopRun()
 				return
 			}
-			wxUser, err := models.GetWxUserItemByUserId(session.UserId)
+			//wxUser, err := models.GetWxUserItemByUserId(session.UserId)
+			wxUser, err := services.GetWxUserItemByOpenId(session.OpenId)
 			if err != nil {
+				//用户openid查询出来发现没有绑定用户
+				if err == services.ERR_USER_NOT_BIND{
+					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.UserId)}, false, false)
+					//this.StopRun()
+					this.User = wxUser
+					return
+				}
+				//没有找到记录
 				if err.Error() == utils.ErrNoRow() {
 					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.UserId)}, false, false)
 					this.StopRun()

+ 10 - 1
controllers/base_common.go

@@ -2,6 +2,7 @@ package controllers
 
 import (
 	"encoding/json"
+	"hongze/hongze_api/services"
 	"net/http"
 	"net/url"
 	"strconv"
@@ -58,8 +59,16 @@ func (this *BaseCommonController) Prepare() {
 			this.StopRun()
 			return
 		}
-		wxUser, err := models.GetWxUserItemByUserId(session.UserId)
+		//wxUser, err := models.GetWxUserItemByUserId(session.UserId)
+		wxUser, err := services.GetWxUserItemByOpenId(session.OpenId)
 		if err != nil {
+			//用户openid没有绑定用户
+			if err == services.ERR_USER_NOT_BIND{
+				this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.UserId)}, false, false)
+				this.StopRun()
+				return
+			}
+			//没有找到记录
 			if err.Error() == utils.ErrNoRow() {
 				this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.UserId)}, false, false)
 				this.StopRun()

+ 1 - 1
controllers/bill.go

@@ -32,7 +32,7 @@ func (this *BillController) Detail() {
 		return
 	}
 	uid := user.UserId
-	userInfo, err := models.GetWxUserItemByUserId(uid)
+	userInfo, err := services.GetWxUserItemByUserId(uid,utils.WxPlatform)
 	if err != nil {
 		br.Ret = 600
 		br.Msg = "登录失败"

+ 186 - 9
controllers/user.go

@@ -2,6 +2,7 @@ package controllers
 
 import (
 	"encoding/json"
+	"fmt"
 	"hongze/hongze_api/models"
 	"hongze/hongze_api/services"
 	"hongze/hongze_api/utils"
@@ -297,13 +298,16 @@ func (this *UserController) Login() {
 		br.ErrMsg = "参数错误,openid 为空"
 		return
 	}
-	userId := user.UserId
-	newUserId := 0
 	if req.LoginType == 1 {
-		//BindMobile(openId, mobile string, userId, loginType int) (err error) {
+		//手机登录
+		if req.Mobile == "" {
+			br.ErrMsg = "手机号不能为空,请输入手机号"
+			br.Msg = "手机号不能为空,请输入手机号"
+			return
+		}
 		req.Mobile = strings.Trim(req.Mobile, " ")
-		newUserId, err = models.BindMobile(openId, req.Mobile, userId, req.LoginType)
 	} else if req.LoginType == 2 {
+		//邮箱登录
 		if req.Email == "" {
 			br.ErrMsg = "邮箱不能为空,请输入邮箱"
 			br.Msg = "邮箱不能为空,请输入邮箱"
@@ -314,14 +318,17 @@ func (this *UserController) Login() {
 			br.Msg = "邮箱格式错误,请重新输入"
 			return
 		}
-		newUserId, err = models.BindMobile(openId, req.Email, userId, req.LoginType)
 	} else {
 		br.Msg = "无效的登录方式"
 		br.ErrMsg = "无效的登录方式,Err:" + err.Error()
 		return
 	}
+	user,err = services.BindWxUser(openId,req.Mobile,req.Email)
+	userId := user.UserId
+
+
 	var token string
-	tokenItem, err := models.GetTokenByUid(newUserId)
+	tokenItem, err := models.GetTokenByOpenId(openId)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		br.Msg = "登录失败"
 		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
@@ -331,7 +338,7 @@ func (this *UserController) Login() {
 	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
 		timeUnix := time.Now().Unix()
 		timeUnixStr := strconv.FormatInt(timeUnix, 10)
-		token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		token := utils.MD5(openId) + utils.MD5(timeUnixStr)
 		//新增session
 		{
 			session := new(models.Session)
@@ -351,7 +358,7 @@ func (this *UserController) Login() {
 	} else {
 		token = tokenItem.AccessToken
 	}
-	userPermission, err := services.CheckUserPermission(newUserId)
+	userPermission, err := services.CheckUserPermission(userId)
 	if err != nil {
 		br.Msg = "登录失败"
 		br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
@@ -378,7 +385,7 @@ func (this *UserController) Login() {
 	}
 
 	resp := new(models.LoginResp)
-	resp.UserId = newUserId
+	resp.UserId = userId
 	resp.UserPermission = userPermission
 	resp.Authorization = token
 	br.Ret = 200
@@ -386,6 +393,122 @@ func (this *UserController) Login() {
 	br.Data = resp
 	br.Msg = "登录成功"
 }
+//func (this *UserController) Login() {
+//	br := new(models.BaseResponse).Init()
+//	defer func() {
+//		this.Data["json"] = br
+//		this.ServeJSON()
+//	}()
+//	var req models.LoginReq
+//	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+//	if err != nil {
+//		br.Msg = "参数解析异常!"
+//		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+//		return
+//	}
+//	user := this.User
+//	if user == nil {
+//		br.Msg = "请登录"
+//		br.ErrMsg = "请登录"
+//		br.Ret = 408
+//		return
+//	}
+//
+//	openId := user.OpenId
+//	if openId == "" {
+//		br.Msg = "参数错误"
+//		br.ErrMsg = "参数错误,openid 为空"
+//		return
+//	}
+//	userId := user.UserId
+//	newUserId := 0
+//	if req.LoginType == 1 {
+//		//BindMobile(openId, mobile string, userId, loginType int) (err error) {
+//		req.Mobile = strings.Trim(req.Mobile, " ")
+//		newUserId, err = models.BindMobile(openId, req.Mobile, userId, req.LoginType)
+//	} else if req.LoginType == 2 {
+//		if req.Email == "" {
+//			br.ErrMsg = "邮箱不能为空,请输入邮箱"
+//			br.Msg = "邮箱不能为空,请输入邮箱"
+//			return
+//		}
+//		if !utils.ValidateEmailFormatat(req.Email) {
+//			br.ErrMsg = "邮箱格式错误,请重新输入"
+//			br.Msg = "邮箱格式错误,请重新输入"
+//			return
+//		}
+//		newUserId, err = models.BindMobile(openId, req.Email, userId, req.LoginType)
+//	} else {
+//		br.Msg = "无效的登录方式"
+//		br.ErrMsg = "无效的登录方式,Err:" + err.Error()
+//		return
+//	}
+//	var token string
+//	tokenItem, err := models.GetTokenByUid(newUserId)
+//	if err != nil && err.Error() != utils.ErrNoRow() {
+//		br.Msg = "登录失败"
+//		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+//		return
+//	}
+//
+//	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+//		timeUnix := time.Now().Unix()
+//		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+//		token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+//		//新增session
+//		{
+//			session := new(models.Session)
+//			session.OpenId = openId
+//			session.UserId = userId
+//			session.CreatedTime = time.Now()
+//			session.LastUpdatedTime = time.Now()
+//			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+//			session.AccessToken = token
+//			err = models.AddSession(session)
+//			if err != nil {
+//				br.Msg = "登录失败"
+//				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+//				return
+//			}
+//		}
+//	} else {
+//		token = tokenItem.AccessToken
+//	}
+//	userPermission, err := services.CheckUserPermission(newUserId)
+//	if err != nil {
+//		br.Msg = "登录失败"
+//		br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
+//		return
+//	}
+//	err = models.ModifyFirstLogin(user.UserId)
+//	if err != nil {
+//		br.Msg = "登录失败"
+//		br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
+//		return
+//	}
+//
+//	//新增登录日志
+//	{
+//		loginLog := new(models.WxUserLog)
+//		loginLog.UserId = userId
+//		loginLog.OpenId = openId
+//		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 = newUserId
+//	resp.UserPermission = userPermission
+//	resp.Authorization = token
+//	br.Ret = 200
+//	br.Success = true
+//	br.Data = resp
+//	br.Msg = "登录成功"
+//}
 
 // @Title 申请试用
 // @Description 申请试用接口
@@ -479,4 +602,58 @@ func (this *UserController) SmallLimit() {
 	br.Ret = 200
 	br.Success = true
 	br.Data = resp
+}
+
+// @Title test
+// @Description test接口
+// @Param	request	body models.CheckEmailCodeReq true "type json string"
+// @Success Ret=200 校验成功
+// @router /test [get]
+func (this *UserCommonController) Test() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	openid := "oN0jD1S3P-FVosLhq-YiVOXldtRo"
+	wxUser,err := services.GetWxUserItemByOpenId(openid)
+	fmt.Println(err)
+	fmt.Println(wxUser)
+	fmt.Println("-----------")
+
+	//wxUser,err = models.GetWxUserItemByOpenId(openid)
+	//fmt.Println(err)
+	//fmt.Println(wxUser)
+	//fmt.Println("-----------")
+
+	userId := 12274
+	userId = 12018
+	platform := 2
+	wxUser,err = services.GetWxUserItemByUserId(userId,platform)
+	fmt.Println(err)
+	fmt.Println(wxUser)
+	fmt.Println("根据用户id获取结束-----------")
+
+	mobile := "18170239278"
+	wxUser,err = services.GetWxUserItemByMobile(mobile,platform)
+	fmt.Println(err)
+	fmt.Println(wxUser)
+	fmt.Println("根据手机号获取结束-----------")
+
+	email := "984198890@qq.com"
+	wxUser,err = services.GetWxUserItemByEmail(email,platform)
+	fmt.Println(err)
+	fmt.Println(wxUser)
+	fmt.Println("根据邮箱获取结束-----------")
+
+	unionId := "o1q5cwOzXXA9Hy9PTEIwxP81Casg"
+	wxUser,err = services.GetWxUserItemByUnionId(unionId,platform)
+	fmt.Println(err)
+	fmt.Println(wxUser)
+	fmt.Println("根据unionid获取结束-----------")
+
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "验证码正确"
 }

+ 212 - 123
controllers/wechat.go

@@ -7,7 +7,6 @@ import (
 	"hongze/hongze_api/services"
 	"hongze/hongze_api/utils"
 	"strconv"
-	"time"
 )
 
 type WechatController struct {
@@ -61,6 +60,11 @@ func (this *WechatCommonController) WechatLogin() {
 		return
 	}
 	openId := item.Openid
+	if openId == "" {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取openid失败,openid:" + item.Openid
+		return
+	}
 	accessToken, err := services.WxGetAccessToken()
 	if err != nil {
 		br.Msg = "获取用户信息失败"
@@ -69,6 +73,7 @@ func (this *WechatCommonController) WechatLogin() {
 	}
 	//获取用户信息
 	wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
+
 	if err != nil {
 		br.Msg = "获取用户信息失败"
 		br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
@@ -81,131 +86,13 @@ func (this *WechatCommonController) WechatLogin() {
 		return
 	}
 
-	unionid := item.Unionid
-	if unionid == "" {
-		unionid = wxUserInfo.Unionid
-	}
-	firstLogin := 1
-	userId := 0
-	utils.FileLog.Info("openId:%s", openId)
-	utils.FileLog.Info("unionid:%s", unionid)
-	//获取成功
-	if openId != "" {
-		wxUser, err := models.GetWxUserItemByOpenId(openId)
-		if err != nil && err.Error() != utils.ErrNoRow() {
-			br.Msg = "获取用户信息失败"
-			br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
-			return
-		}
-		if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
-			user := new(models.WxUser)
-			user.OpenId = openId
-			user.CompanyId = 1
-			user.CreatedTime = time.Now()
-			user.UnionId = unionid
-			user.Unionid = unionid
-			user.NickName = wxUserInfo.Nickname
-			user.Sex = wxUserInfo.Sex
-			user.City = wxUserInfo.City
-			user.Province = wxUserInfo.Province
-			user.Country = wxUserInfo.Country
-			user.Headimgurl = wxUserInfo.Headimgurl
-			user.FirstLogin = 1
-			user.Enabled = 1
-			user.RegisterPlatform = 1
-			user.RegisterTime = time.Now()
-			_, err = models.AddWxUser(user)
-			wxUser, err = models.GetWxUserItemByOpenId(openId)
-			if err != nil {
-				br.Msg = "获取用户信息失败"
-				br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
-				return
-			}
-			userId = wxUser.UserId
-		} else {
-			firstLogin = wxUser.FirstLogin
-			userId = wxUser.UserId
-		}
-	} else {
-		br.Msg = "获取用户信息失败"
-		br.ErrMsg = "获取openid失败,openid:" + item.Openid
-		return
-	}
-	permission, err := services.CheckUserPermission(userId)
-	if err != nil {
-		utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
-	}
-	//if err != nil {
-	//	br.Msg = "登录失败"
-	//	br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
-	//	return
-	//}
-	var token string
-	tokenItem, err := models.GetTokenByUid(userId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "登录失败"
-		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+	token,userId,firstLogin,permission,err := services.WxLogin(code,item,wxUserInfo)
+	if err != nil{
+		br.Msg = "微信登录失败"
+		br.ErrMsg = "微信登录失败,err:" + err.Error()
 		return
 	}
 
-	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
-		timeUnix := time.Now().Unix()
-		timeUnixStr := strconv.FormatInt(timeUnix, 10)
-		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-		//新增session
-		{
-			session := new(models.Session)
-			session.OpenId = openId
-			session.UserId = userId
-			session.CreatedTime = time.Now()
-			session.LastUpdatedTime = time.Now()
-			session.ExpireTime = time.Now().AddDate(0, 3, 0)
-			session.AccessToken = token
-			err = models.AddSession(session)
-			if err != nil {
-				br.Msg = "登录失败"
-				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
-				return
-			}
-		}
-	} else {
-		token = tokenItem.AccessToken
-	}
-
-	if wxUserInfo != nil {
-		go models.ModifyWxUserInfo(wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
-	}
-	//firstLogin==1,强制绑定手机号或者邮箱
-	{
-		newItem, _ := models.GetWxUserItemByUserId(userId)
-		if newItem.Mobile == "" && newItem.Email == "" {
-			firstLogin = 1
-		}
-	}
-	//新增登录日志
-	{
-		loginLog := new(models.WxUserLog)
-		loginLog.UserId = userId
-		loginLog.OpenId = openId
-		loginLog.UnionId = unionid
-		loginLog.CreateTime = time.Now()
-		loginLog.Handle = "wechat_login"
-		loginLog.Remark = token
-		go models.AddWxUserLog(loginLog)
-	}
-
-	{
-		codeLog := new(models.WxUserCode)
-		codeLog.WxCode = code
-		codeLog.UserId = userId
-		codeLog.Code = 0
-		codeLog.FirstLogin = firstLogin
-		codeLog.Authorization = token
-		codeLog.UserPermission = permission
-		codeLog.CreateTime=time.Now()
-		models.AddWxUserCode(codeLog)
-	}
-
 	resp.UserId = userId
 	resp.Code = 0
 	resp.FirstLogin = firstLogin
@@ -224,6 +111,208 @@ func (this *WechatCommonController) WechatLogin() {
 		utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
 	}
 }
+//作废于2021-03-29 10:14:54
+//func (this *WechatCommonController) WechatLoginV1() {
+//	br := new(models.BaseResponse).Init()
+//	defer func() {
+//		this.Data["json"] = br
+//		this.ServeJSON()
+//	}()
+//	resp := new(models.WxLoginResp)
+//
+//	code := this.GetString("Code")
+//	fmt.Println("code:", code)
+//	utils.FileLog.Info("WechatLogin code:%s", code)
+//	wxCodeInfo, err := models.GetWxUserCode(code)
+//	if err == nil && wxCodeInfo != nil && wxCodeInfo.Id > 0 {
+//		utils.FileLog.Info("WechatLogin code exist:%s", code)
+//		resp.UserId = wxCodeInfo.UserId
+//		resp.Code = 0
+//		resp.FirstLogin = wxCodeInfo.FirstLogin
+//		resp.Authorization = wxCodeInfo.Authorization
+//		resp.UserPermission = wxCodeInfo.UserPermission
+//		br.Ret = 200
+//		br.Success = true
+//		br.Msg = "登录成功"
+//		br.Data = resp
+//		return
+//	}
+//
+//	item, err := services.WxGetUserOpenIdByCode(code)
+//	if err != nil {
+//		br.Msg = "获取用户信息失败"
+//		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
+//		return
+//	}
+//	if item.Errcode != 0 {
+//		br.Msg = "获取用户信息失败"
+//		br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
+//		return
+//	}
+//	openId := item.Openid
+//	accessToken, err := services.WxGetAccessToken()
+//	if err != nil {
+//		br.Msg = "获取用户信息失败"
+//		br.ErrMsg = "获取access_token失败,err:" + err.Error()
+//		return
+//	}
+//	//获取用户信息
+//	wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
+//	if err != nil {
+//		br.Msg = "获取用户信息失败"
+//		br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
+//		return
+//	}
+//	if wxUserInfo.Errcode != 0 {
+//		userInfoJson, _ := json.Marshal(wxUserInfo)
+//		br.Msg = "登录失败"
+//		br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
+//		return
+//	}
+//
+//	unionid := item.Unionid
+//	if unionid == "" {
+//		unionid = wxUserInfo.Unionid
+//	}
+//	firstLogin := 1
+//	userId := 0
+//	utils.FileLog.Info("openId:%s", openId)
+//	utils.FileLog.Info("unionid:%s", unionid)
+//	//获取成功
+//	if openId != "" {
+//		wxUser, err := models.GetWxUserItemByOpenId(openId)
+//		if err != nil && err.Error() != utils.ErrNoRow() {
+//			br.Msg = "获取用户信息失败"
+//			br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
+//			return
+//		}
+//		if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+//			user := new(models.WxUser)
+//			user.OpenId = openId
+//			user.CompanyId = 1
+//			user.CreatedTime = time.Now()
+//			user.UnionId = unionid
+//			user.Unionid = unionid
+//			user.NickName = wxUserInfo.Nickname
+//			user.Sex = wxUserInfo.Sex
+//			user.City = wxUserInfo.City
+//			user.Province = wxUserInfo.Province
+//			user.Country = wxUserInfo.Country
+//			user.Headimgurl = wxUserInfo.Headimgurl
+//			user.FirstLogin = 1
+//			user.Enabled = 1
+//			user.RegisterPlatform = 1
+//			user.RegisterTime = time.Now()
+//			_, err = models.AddWxUser(user)
+//			wxUser, err = models.GetWxUserItemByOpenId(openId)
+//			if err != nil {
+//				br.Msg = "获取用户信息失败"
+//				br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
+//				return
+//			}
+//			userId = wxUser.UserId
+//		} else {
+//			firstLogin = wxUser.FirstLogin
+//			userId = wxUser.UserId
+//		}
+//	} else {
+//		br.Msg = "获取用户信息失败"
+//		br.ErrMsg = "获取openid失败,openid:" + item.Openid
+//		return
+//	}
+//	permission, err := services.CheckUserPermission(userId)
+//	if err != nil {
+//		utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
+//	}
+//	//if err != nil {
+//	//	br.Msg = "登录失败"
+//	//	br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
+//	//	return
+//	//}
+//	var token string
+//	tokenItem, err := models.GetTokenByUid(userId)
+//	if err != nil && err.Error() != utils.ErrNoRow() {
+//		br.Msg = "登录失败"
+//		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+//		return
+//	}
+//
+//	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+//		timeUnix := time.Now().Unix()
+//		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+//		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+//		//新增session
+//		{
+//			session := new(models.Session)
+//			session.OpenId = openId
+//			session.UserId = userId
+//			session.CreatedTime = time.Now()
+//			session.LastUpdatedTime = time.Now()
+//			session.ExpireTime = time.Now().AddDate(0, 3, 0)
+//			session.AccessToken = token
+//			err = models.AddSession(session)
+//			if err != nil {
+//				br.Msg = "登录失败"
+//				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+//				return
+//			}
+//		}
+//	} else {
+//		token = tokenItem.AccessToken
+//	}
+//
+//	if wxUserInfo != nil {
+//		go models.ModifyWxUserInfo(wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
+//	}
+//	//firstLogin==1,强制绑定手机号或者邮箱
+//	{
+//		newItem, _ := models.GetWxUserItemByUserId(userId)
+//		if newItem.Mobile == "" && newItem.Email == "" {
+//			firstLogin = 1
+//		}
+//	}
+//	//新增登录日志
+//	{
+//		loginLog := new(models.WxUserLog)
+//		loginLog.UserId = userId
+//		loginLog.OpenId = openId
+//		loginLog.UnionId = unionid
+//		loginLog.CreateTime = time.Now()
+//		loginLog.Handle = "wechat_login"
+//		loginLog.Remark = token
+//		go models.AddWxUserLog(loginLog)
+//	}
+//
+//	{
+//		codeLog := new(models.WxUserCode)
+//		codeLog.WxCode = code
+//		codeLog.UserId = userId
+//		codeLog.Code = 0
+//		codeLog.FirstLogin = firstLogin
+//		codeLog.Authorization = token
+//		codeLog.UserPermission = permission
+//		codeLog.CreateTime=time.Now()
+//		models.AddWxUserCode(codeLog)
+//	}
+//
+//	resp.UserId = userId
+//	resp.Code = 0
+//	resp.FirstLogin = firstLogin
+//	resp.Authorization = token
+//	resp.UserPermission = permission
+//	br.Ret = 200
+//	br.Success = true
+//	br.Msg = "登录成功"
+//	br.Data = resp
+//	//登录日志
+//	{
+//		returnResult, err := json.Marshal(br)
+//		if err != nil {
+//			utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
+//		}
+//		utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
+//	}
+//}
 
 // @Title 微信获取签名接口
 // @Description 微信获取签名接口

+ 18 - 0
models/session.go

@@ -46,3 +46,21 @@ func GetTokenByUid(uid int) (item *Session, err error) {
 	err = o.Raw(sql, uid).QueryRow(&item)
 	return
 }
+
+//根据用户id获取token
+func GetTokenByOpenId(openId string) (item *Session, err error) {
+	sql := `SELECT * FROM session WHERE open_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, openId).QueryRow(&item)
+	return
+}
+
+//更新session
+func UpdateSession(sessionId,userId int) (err error) {
+	sql := `update session WHERE set user_id=? where session_id = ? `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	_,err = o.Raw(sql, userId,sessionId).Exec()
+	return
+}

+ 62 - 0
models/user_record.go

@@ -0,0 +1,62 @@
+package models
+
+import (
+	"rdluck_tools/orm"
+	"time"
+)
+
+type UserRecord struct {
+	UserRecordId int `orm:"column(user_record_id);pk"`
+	OpenId string `description:"用户openid,最大长度:32"`
+	UnionId string `description:"用户unionid,最大长度:64"`
+	Subscribe int `description:"是否关注"`
+	NickName string `descritpion:"用户昵称,最大长度:32"`
+	RealName string `descritpion:"用户实际名称,最大长度:32"`
+	BindAccount string `descritpion:"绑定时的账号,最大长度:128"`
+	Sex int `descritpion:"普通用户性别,1为男性,2为女性"`
+	Province string `description:"普通用户个人资料填写的省份,最大长度:30"`
+	City string `description:"普通用户个人资料填写的城市,最大长度:30"`
+	Country string `description:"国家,如中国为CN,最大长度:30"`
+	Headimgurl string `description:"用户第三方(微信)头像,最大长度:512"`
+	CreateTime time.Time `description:"创建时间,关系添加时间、用户授权时间"`
+	CreatePlatform int `description:"注册平台,1:日度点评公众号,2:管理后台,3:pc端网站,4:查研观向小程序;默认:1"`
+	SessionKey string `description:"微信小程序会话密钥,最大长度:255"`
+	UserId int `description:"用户id"`
+}
+
+//根据openid获取用户关系
+func GetUserRecordByOpenId(openId string) (item *UserRecord, err error) {
+	sql := `SELECT * FROM user_record WHERE open_id=? `
+	err = orm.NewOrm().Raw(sql, openId).QueryRow(&item)
+	return
+}
+
+//根据用户id和平台id获取用户关系
+func GetUserRecordByUserId(userId,platform int) (item *UserRecord, err error) {
+	sql := `SELECT * FROM user_record WHERE user_id=? AND create_platform = ?`
+	err = orm.NewOrm().Raw(sql, userId,platform).QueryRow(&item)
+	return
+}
+
+//添加用户关系
+func AddUserRecord(record *UserRecord) (recordId int64,err error) {
+	o := orm.NewOrm()
+	recordId,err = o.Insert(record)
+	return
+}
+
+//根据openid绑定用户关系
+func BindUserRecordByOpenid(userId int,openId,bindAccount string)(err error)  {
+	o := orm.NewOrm()
+	msql := " UPDATE user_record SET user_id = ?,bind_account=? WHERE open_id = ? "
+	_, err = o.Raw(msql, userId,bindAccount, openId).Exec()
+	return
+}
+
+//修改用户微信信息
+func ModifyUserRecordInfo(openId,nickName, headimgUrl, city, province, country string, sex, userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE user_record SET nick_name=?,headimgurl=?,sex=?,city=?,province=?,country=? WHERE user_id=? and openid=? `
+	_, err = o.Raw(sql, nickName, headimgUrl, sex, city, province, country, userId,openId).Exec()
+	return
+}

+ 24 - 0
rdlucklog/hongze_api.log

@@ -1,2 +1,26 @@
 2021/02/22 09:32:28.728 [I]  authorization:,cookie:
 2021/02/25 16:51:47.040 [I]  report.detail 16,1
+2021/03/25 17:15:06.228 [I]  authorization:,cookie:
+2021/03/25 17:15:06.228 [I]  URI:/api/user/test
+2021/03/25 17:16:44.332 [I]  authorization:,cookie:
+2021/03/25 17:16:44.332 [I]  URI:/api/user/test
+2021/03/25 17:18:04.257 [I]  authorization:,cookie:
+2021/03/25 17:18:04.257 [I]  URI:/api/user/test
+2021/03/25 17:19:16.405 [I]  authorization:,cookie:
+2021/03/25 17:19:16.405 [I]  URI:/api/user/test
+2021/03/25 17:24:51.937 [I]  authorization:,cookie:
+2021/03/25 17:24:51.937 [I]  URI:/api/user/test
+2021/03/25 17:25:37.290 [I]  authorization:,cookie:
+2021/03/25 17:25:37.290 [I]  URI:/api/user/test
+2021/03/25 17:25:47.062 [I]  authorization:,cookie:
+2021/03/25 17:25:47.062 [I]  URI:/api/user/test
+2021/03/25 17:26:45.469 [I]  authorization:,cookie:
+2021/03/25 17:26:45.469 [I]  URI:/api/user/test
+2021/03/25 17:27:30.891 [I]  authorization:,cookie:
+2021/03/25 17:27:30.891 [I]  URI:/api/user/test
+2021/03/25 17:28:01.679 [I]  authorization:,cookie:
+2021/03/25 17:28:01.679 [I]  URI:/api/user/test
+2021/03/25 17:39:07.585 [I]  authorization:,cookie:
+2021/03/25 17:39:07.585 [I]  URI:/api/user/test
+2021/03/25 18:13:44.363 [I]  authorization:,cookie:
+2021/03/25 18:13:44.363 [I]  URI:/api/user/test

+ 1 - 1
services/annual_report.go

@@ -15,7 +15,7 @@ func CreateAnnualReport() {
 	startDate := "2020-01-01 00:00:00"
 	endDate := time.Now().Format(utils.FormatDate)
 	uid := 123
-	user,err:=models.GetWxUserItemByUserId(uid)
+	user,err:=GetWxUserItemByUserId(uid,utils.WxPlatform)
 	if err!=nil {
 
 	}

+ 342 - 0
services/user.go

@@ -0,0 +1,342 @@
+package services
+
+import (
+	"errors"
+	"hongze/hongze_api/models"
+	"hongze/hongze_api/utils"
+	"strconv"
+	"time"
+)
+
+var ERR_NO_USER_RECORD = errors.New("用户关系没有入库")
+var ERR_USER_NOT_BIND = errors.New("用户没有绑定")
+
+//通过openid获取用户信息
+func GetWxUserItemByOpenId(openid string)  (item *models.WxUserItem,err error){
+	//通过openid获取用户关联信息
+	userRecord,userRecordErr := models.GetUserRecordByOpenId(openid)
+	if userRecordErr != nil{
+		if userRecordErr.Error() == utils.ErrNoRow(){
+			err = ERR_NO_USER_RECORD
+			return
+		}else{
+			err = userRecordErr
+			return
+		}
+	}
+
+	//该openid在系统中没有关联关系
+	if userRecord == nil {
+		err = ERR_NO_USER_RECORD
+		return
+	}
+
+	//该openid没有绑定用户
+	if userRecord.UserId <= 0{
+		err = ERR_USER_NOT_BIND
+		return
+	}
+
+	//获取用户信息
+	item,wxUserErr := models.GetWxUserItemByUserId(userRecord.UserId)
+	if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+	//格式化返回用户数据
+	formatWxUserAndUserRecord(item,userRecord)
+	return
+}
+
+//根据用户id和平台id获取用户信息
+func GetWxUserItemByUserId(userId,platform int)  (wxUserItem *models.WxUserItem,err error){
+	//获取用户信息
+	wxUserItem,wxUserErr := models.GetWxUserItemByUserId(userId)
+	if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+	//格式化返回用户数据
+	formatWxUser(wxUserItem,platform)
+	return
+}
+
+//根据用户邮箱和平台id获取用户信息
+func GetWxUserItemByEmail(email string,platform int) (wxUserItem *models.WxUserItem,err error) {
+	//获取用户信息
+	wxUserItem,wxUserErr := models.GetWxUserItemByEmail(email)
+	if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+
+	//格式化返回用户数据
+	formatWxUser(wxUserItem,platform)
+	return
+}
+
+//根据用户手机号和平台id获取用户信息
+func GetWxUserItemByMobile(mobile string,platform int) (wxUserItem *models.WxUserItem,err error) {
+	//获取用户信息
+	wxUserItem,wxUserErr := models.GetWxUserItemByMobile(mobile)
+	if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+	//格式化返回用户数据
+	formatWxUser(wxUserItem,platform)
+	return
+}
+
+//根据用户unionid和平台id获取用户信息
+func GetWxUserItemByUnionId(unionId string,platform int) (wxUserItem *models.WxUserItem,err error) {
+	//获取用户信息
+	wxUserItem,wxUserErr := models.GetWxUserItemByUnionid(unionId)
+	if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+	//格式化返回用户数据
+	formatWxUser(wxUserItem,platform)
+	return
+}
+
+//通过用户 关系表记录  和  用户记录  格式化返回 用户数据
+func formatWxUserAndUserRecord(wxUser *models.WxUserItem,userRecord *models.UserRecord)  {
+	wxUser.OpenId = userRecord.OpenId
+	wxUser.UnionId = userRecord.UnionId
+	wxUser.NickName = userRecord.NickName
+	//wxUser.RealName = userRecord.RealName
+	//wxUser.BindAccount = userRecord.BindAccount
+	wxUser.Headimgurl = userRecord.Headimgurl
+}
+
+//通过用户 用户记录  和  来源平台  格式化返回 用户数据
+func formatWxUser(wxUser *models.WxUserItem,platform int)  {
+	//根据用户id和平台id获取用户关系
+	userRecord,userRecordErr := models.GetUserRecordByUserId(wxUser.UserId,platform)
+	if userRecordErr != nil{
+		if userRecordErr.Error() != utils.ErrNoRow(){
+			return
+		}
+		if userRecordErr.Error() == utils.ErrNoRow(){
+			return
+		}
+	}
+
+	//该openid在系统中没有关联关系
+	if userRecord == nil {
+		return
+	}
+
+	wxUser.OpenId = userRecord.OpenId
+	wxUser.UnionId = userRecord.UnionId
+	wxUser.NickName = userRecord.NickName
+	//wxUser.RealName = userRecord.RealName
+	//wxUser.BindAccount = userRecord.BindAccount
+	wxUser.Headimgurl = userRecord.Headimgurl
+	return
+}
+
+//用户绑定
+func BindWxUser(openid,mobile,email string) (wxUser *models.WxUserItem,err error)  {
+	if mobile == "" && email == ""{
+		err = errors.New("手机号或邮箱必填一个")
+		return
+	}
+	var bindAccount string
+	//根据手机号获取用户信息
+	if mobile != ""{
+		tmpWxUser,wxUserErr := models.GetWxUserItemByMobile(mobile)
+		if wxUserErr != nil && wxUserErr.Error() != utils.ErrNoRow(){
+			err = wxUserErr
+			return
+		}
+		wxUser = tmpWxUser
+		bindAccount = mobile
+	}
+	//根据邮箱获取用户信息
+	if wxUser == nil && email != ""{
+		tmpWxUser,wxUserErr := models.GetWxUserItemByEmail(email)
+		if wxUserErr != nil && wxUserErr.Error() != utils.ErrNoRow(){
+			err = wxUserErr
+			return
+		}
+		wxUser = tmpWxUser
+		bindAccount = email
+	}
+
+	//查询openid的第三方(微信)信息
+	userRecord,err := models.GetUserRecordByOpenId(openid)
+	if err != nil{
+		return
+	}
+
+
+	var userId int
+	//如果查询出来的用户是nil,那么需要新增用户
+	if wxUser == nil{
+		user := &models.WxUser{
+			CompanyId:1,
+			CreatedTime:time.Now(),
+			FirstLogin:1,
+			Enabled:1,
+			RegisterPlatform:1,
+			RegisterTime:time.Now(),
+			Mobile: mobile,
+			Email: email,
+		}
+		tmpUserId, addUserErr := models.AddWxUser(user)
+		if err != nil{
+			err = addUserErr
+			return
+		}
+		user.UserId = int(tmpUserId)
+		userId = int(tmpUserId)
+	}else{
+		userId = wxUser.UserId
+	}
+	//如果存在该手机号/邮箱,那么需要校验
+	if userRecord.UserId > 0 && userRecord.UserId != userId{
+		err = errors.New("用户已绑定,不允许重复绑定")
+		return
+	}
+
+	err = models.BindUserRecordByOpenid(userId,openid,bindAccount)
+	if err != nil{
+		return
+	}
+	userRecord.UserId = userId
+	//格式化用户数据
+	formatWxUserAndUserRecord(wxUser,userRecord)
+	return
+}
+
+//微信登录
+func WxLogin(code string,wxAccessToken *WxAccessToken,wxUserInfo *WxUserInfo)(token string,userId,firstLogin,permission int,err error){
+	openId := wxAccessToken.Openid
+	unionId := wxAccessToken.Unionid
+	if unionId == ""{
+		unionId = wxUserInfo.Unionid
+	}
+
+	//firstLogin==1,强制绑定手机号或者邮箱
+	firstLogin = 1
+	wxUser, wxUserErr := GetWxUserItemByOpenId(openId)
+	if wxUserErr == ERR_NO_USER_RECORD{	//没有用户openid记录
+		_,recordErr := AddUserRecord(openId,unionId,wxUserInfo.Nickname,"",wxUserInfo.Province,wxUserInfo.City,wxUserInfo.Country,wxUserInfo.Headimgurl,"",utils.WxPlatform,wxUserInfo.Sex,0)
+		err = recordErr
+		return
+	}else if wxUserErr == ERR_USER_NOT_BIND{
+		//没有用户信息
+		wxUser.FirstLogin = 1
+	}else if wxUserErr != nil{
+		err = wxUserErr
+		return
+	}
+
+	//如果已经登录注册绑定的情况下
+	if wxUser != nil && wxUserErr == nil{
+		//获取用户权限
+		firstLogin = wxUser.FirstLogin
+		userId = wxUser.UserId
+
+		permission, permissionErr := CheckUserPermission(userId)
+		if permissionErr != nil {
+			//记录日志
+			utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
+		}
+
+		if wxUserInfo != nil {
+			go models.ModifyUserRecordInfo(openId,wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
+		}
+
+		{
+			codeLog := new(models.WxUserCode)
+			codeLog.WxCode = code
+			codeLog.UserId = userId
+			codeLog.Code = 0
+			codeLog.FirstLogin = firstLogin
+			codeLog.Authorization = token
+			codeLog.UserPermission = permission
+			codeLog.CreateTime=time.Now()
+			models.AddWxUserCode(codeLog)
+		}
+		if wxUser.Mobile == "" && wxUser.Email == "" {
+			firstLogin = 1
+		}
+	}
+
+
+	//获取登录token
+	tokenItem, tokenErr := models.GetTokenByOpenId(openId)
+	if tokenErr != nil && tokenErr.Error() != utils.ErrNoRow() {
+		err  = errors.New("登录失败,获取token失败:" + tokenErr.Error())
+		return
+	}
+
+	if tokenItem == nil || (tokenErr != nil && tokenErr.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(openId) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.OpenId = openId
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 3, 0)
+			session.AccessToken = token
+			sessionErr := models.AddSession(session)
+			if err != nil {
+				err  = errors.New("登录失败,新增用户session信息失败:" + sessionErr.Error())
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
+
+	//新增登录日志
+	{
+		loginLog := new(models.WxUserLog)
+		loginLog.UserId = userId
+		loginLog.OpenId = openId
+		loginLog.UnionId = unionId
+		loginLog.CreateTime = time.Now()
+		loginLog.Handle = "wechat_login"
+		loginLog.Remark = token
+		go models.AddWxUserLog(loginLog)
+	}
+	return
+}
+
+func UserLogin()  {
+	
+}
+
+//添加第三方用户(微信)记录
+func AddUserRecord(openId,unionId,nickName,realName,province,city,country,headimgurl,sessionKey string,platform,sex,subscribe int) (userRecord *models.UserRecord,err error) {
+	userRecord = &models.UserRecord{
+		OpenId :openId,	//用户open_id
+		UnionId :unionId,//用户union_id
+		Subscribe :subscribe,
+		NickName :nickName,	//用户昵称,最大长度:32
+		RealName :realName,	//用户实际名称,最大长度:32
+		Sex :sex,	//普通用户性别,1为男性,2为女性
+		Province :province,//普通用户个人资料填写的省份,最大长度:30
+		City :city,	//普通用户个人资料填写的城市,最大长度:30
+		Country :country,	//国家,如中国为CN,最大长度:30
+		Headimgurl :headimgurl,	//用户第三方(微信)头像,最大长度:512
+		CreateTime :time.Now(),	//创建时间,关系添加时间、用户授权时间
+		CreatePlatform :platform,	//注册平台,1:日度点评公众号,2:管理后台,3:pc端网站,4:查研观向小程序;默认:1
+		SessionKey :sessionKey,	//微信小程序会话密钥,最大长度:255
+	}
+	recordId, err := models.AddUserRecord(userRecord)
+	if err !=nil{
+		return
+	}
+	userRecord.UserRecordId = int(recordId)
+	return
+}

+ 2 - 1
services/user_permission.go

@@ -10,7 +10,8 @@ import (
 
 func CheckUserPermission(userId int) (status int, err error) {
 	if userId > 0 {
-		wxUser, err := models.GetWxUserItemByUserId(userId)
+		//wxUser, err := models.GetWxUserItemByUserId(userId)
+		wxUser,err := GetWxUserItemByUserId(userId,utils.WxPlatform)
 		if err != nil {
 			if err.Error() == utils.ErrNoRow() {
 				status = 40001

+ 3 - 0
utils/config.go

@@ -22,6 +22,7 @@ var (
 	WxAppSecret         string
 	TemplateIdByProduct string //产品运行报告通知-模板ID
 	TemplateRedirectUrl string //模板消息跳转地址
+	WxPlatform int	//用户来源,需要入库,用来保存该用户来自哪个平台,默认是:1
 )
 
 //pc端微信配置信息
@@ -50,6 +51,7 @@ func init() {
 		WxId = "gh_b67e0049fb8c"
 		TemplateIdByProduct = "Cp2wF8gvBtxyWV4DeYuI172oqwyYXVRSm3AyJO42d84"
 		TemplateRedirectUrl = "https://ficc.hzinsights.com/reportdtl?id="
+		WxPlatform = 1
 
 		PcWxAppId = "wx615472d6874eeb7f"
 		PcWxAppSecret="97fe374fb0cc90ef58c4b49d431366f1"
@@ -60,6 +62,7 @@ func init() {
 		WxId = "gh_5dc508325c6f"
 		TemplateIdByProduct = "-YjuPOB7Fqd-S3ilabYa6wvjDY9aXmeEfPN6DCiy-EY"
 		TemplateRedirectUrl = "http://rddpweb.brilliantstart.cn/reportdtl?id="
+		WxPlatform = 1
 
 		PcWxAppId = "wx7c8084f6e5b1d85a"
 		PcWxAppSecret="9e4210cd5a363aa1f316b7c4b8898418"