loginbyweixinlogic.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package logic
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "git.i2edu.net/i2/go-zero/core/logx"
  7. "git.i2edu.net/i2/go-zero/core/stores/sqlc"
  8. "git.i2edu.net/i2/go-zero/core/stores/sqlx"
  9. "git.i2edu.net/i2/i2-bill-api/internal/svc"
  10. "git.i2edu.net/i2/i2-bill-api/internal/types"
  11. "git.i2edu.net/i2/i2-bill-api/internal/utils"
  12. "git.i2edu.net/i2/i2-bill-api/model"
  13. "github.com/dgrijalva/jwt-go"
  14. )
  15. type LoginByWeixinLogic struct {
  16. logx.Logger
  17. ctx context.Context
  18. svcCtx *svc.ServiceContext
  19. }
  20. func NewLoginByWeixinLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginByWeixinLogic {
  21. return LoginByWeixinLogic{
  22. Logger: logx.WithContext(ctx),
  23. ctx: ctx,
  24. svcCtx: svcCtx,
  25. }
  26. }
  27. func (l *LoginByWeixinLogic) LoginByWeixin(req types.AuthLoginBody) (*types.AuthResponse, error) {
  28. alb, rtnInfo := req, types.AuthResponse{}
  29. userInfo, err := l.Login(alb.Code)
  30. if err != nil {
  31. logx.Error(err)
  32. return nil, err
  33. }
  34. err = l.svcCtx.SqlConn.Transact(func(session sqlx.Session) error {
  35. var user model.User
  36. err := session.QueryRow(&user, fmt.Sprintf("select %s from user where `weixin_openid` = ? limit 1", model.UserRows), userInfo.OpenID)
  37. if err == sqlc.ErrNotFound {
  38. user.Username = utils.GetUUID()
  39. user.Password = ""
  40. user.RegisterTime = utils.GetTimestamp()
  41. user.RegisterIp = ""
  42. user.Mobile = ""
  43. user.WeixinOpenid = userInfo.OpenID
  44. user.Avatar = userInfo.AvatarUrl
  45. user.Gender = userInfo.Gender
  46. user.Nickname = userInfo.NickName
  47. _, err = session.Exec(`insert into user (%s) values (
  48. mobile, avatar, weixin_openid, password, birthday, register_time, last_login_time, nickname, erp_id, username, gender, user_level_id, register_ip, last_login_ip
  49. )`,
  50. user.Mobile, user.Avatar, user.WeixinOpenid, user.Password, user.Birthday, user.RegisterTime, user.LastLoginTime, user.Nickname, user.ErpId, user.Username, user.Gender, user.UserLevelId, user.RegisterIp, user.LastLoginIp)
  51. if err != nil {
  52. logx.Error(err)
  53. return err
  54. }
  55. err = session.QueryRow(&user, fmt.Sprintf("select %s from user where `weixin_openid` = ? limit 1", model.UserRows), userInfo.OpenID)
  56. if err != nil {
  57. logx.Error(err)
  58. return err
  59. }
  60. }
  61. rtnInfo.UserInfo.ID = user.Id
  62. rtnInfo.UserInfo.UserName = user.Username
  63. rtnInfo.UserInfo.NickName = user.Nickname
  64. rtnInfo.UserInfo.Mobile = user.Mobile
  65. rtnInfo.UserInfo.Gender = user.Gender
  66. rtnInfo.UserInfo.Avatar = user.Avatar
  67. rtnInfo.UserInfo.Birthday = user.Birthday
  68. user.LastLoginIp = ""
  69. user.LastLoginTime = utils.GetTimestamp()
  70. _, err = session.Exec(`update user set
  71. mobile = ?, avatar = ?, weixin_openid = ?, password = ?, birthday = ?, register_time = ?, last_login_time = ?, nickname = ?, erp_id = ?, username = ?, gender = ?, user_level_id = ?, register_ip = ?, last_login_ip = ? where id = ?`, user.Mobile, user.Avatar, user.WeixinOpenid, user.Password, user.Birthday, user.RegisterTime, user.LastLoginTime, user.Nickname, user.ErpId, user.Username, user.Gender, user.UserLevelId, user.RegisterIp, user.LastLoginIp, user.Id)
  72. if err != nil {
  73. logx.Error(err)
  74. return err
  75. }
  76. return nil
  77. })
  78. if err != nil {
  79. return nil, err
  80. }
  81. var accessExpire = l.svcCtx.Config.JwtAuth.AccessExpire
  82. now := time.Now().Unix()
  83. payloads := map[string]interface{}{
  84. "userId": rtnInfo.UserInfo.ID,
  85. }
  86. accessToken, err := l.CreateJWT(now, l.svcCtx.Config.JwtAuth.AccessSecret, payloads, accessExpire)
  87. if err != nil {
  88. logx.Error(err)
  89. return nil, err
  90. }
  91. rtnInfo.Token = accessToken
  92. return &rtnInfo, nil
  93. }
  94. func (l *LoginByWeixinLogic) CreateJWT(iat int64, secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {
  95. claims := make(jwt.MapClaims)
  96. claims["exp"] = iat + seconds
  97. claims["iat"] = iat
  98. for k, v := range payloads {
  99. claims[k] = v
  100. }
  101. token := jwt.New(jwt.SigningMethodHS256)
  102. token.Claims = claims
  103. return token.SignedString([]byte(secretKey))
  104. }
  105. func (l *LoginByWeixinLogic) Login(code string) (*types.WXUserInfo, error) {
  106. secret := l.svcCtx.Config.Weixin.Secret
  107. appid := l.svcCtx.Config.Weixin.Appid
  108. req := utils.Get("https://api.weixin.qq.com/sns/jscode2session")
  109. req.Param("grant_type", "authorization_code")
  110. req.Param("js_code", code)
  111. req.Param("secret", secret)
  112. req.Param("appid", appid)
  113. var res types.WXLoginResponse
  114. req.ToJSON(&res)
  115. userinfo, err := l.DecryptUserInfoData(res.SessionKey)
  116. userinfo.OpenID = res.OpenID
  117. return userinfo, err
  118. }
  119. func (l *LoginByWeixinLogic) DecryptUserInfoData(sessionKey string) (*types.WXUserInfo, error) {
  120. var wxuserinfo types.WXUserInfo
  121. return &wxuserinfo, nil
  122. }