更新用户登录

This commit is contained in:
2025-09-23 18:39:01 +08:00
parent 0729f6e5cf
commit e8302dd3d7
2 changed files with 150 additions and 132 deletions

View File

@@ -7,7 +7,7 @@ database:
params: "charset=utf8mb4&parseTime=True&loc=Local" params: "charset=utf8mb4&parseTime=True&loc=Local"
redis: redis:
host: "localhost" host: "localhost"
port: 30079 port: 6379
username: "default" username: "default"
password: "" password: ""
jwtsecret: "clka1af83af15vhyt8s652avre" jwtsecret: "clka1af83af15vhyt8s652avre"

View File

@@ -4,147 +4,146 @@ import (
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"encoding/base64" "encoding/base64"
"github.com/gin-gonic/gin" "encoding/json"
"errors"
"fmt"
"math/rand" "math/rand"
"net/http"
"net/url"
"strconv" "strconv"
"time" "time"
"toutoukan/init/config"
"toutoukan/init/databaseInit"
"toutoukan/model/usermodel"
"toutoukan/utill/jwt"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
) )
const wxLoginURL = "https://api.weixin.qq.com/sns/jscode2session" const wxLoginURL = "https://api.weixin.qq.com/sns/jscode2session"
func UserLogin(c *gin.Context) { func UserLogin(c *gin.Context) {
fmt.Println("Request Body:", c.Request.Body)
var req usermodel.WxLoginM
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
fmt.Println("req:123")
fmt.Println(req.EncryptedData)
fmt.Println(req.Code)
fmt.Println(req.Iv)
fmt.Println("使用的appid:", config.Conf.WxID)
fmt.Println("使用的secret:", config.Conf.Wxsecret)
//----------------发送验证请求
params := url.Values{}
params.Add("appid", config.Conf.WxID)
params.Add("secret", config.Conf.Wxsecret)
params.Add("js_code", req.Code)
params.Add("grant_type", "authorization_code")
requestURL := fmt.Sprintf("%s?%s", wxLoginURL, params.Encode())
fmt.Println("微信接口请求URL:", requestURL)
resp, err := http.Get(fmt.Sprintf("%s?%s", wxLoginURL, params.Encode()))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "调用微信登录接口失败: " + err.Error()})
return
}
fmt.Println("微信登录返回结果:", resp.Body)
defer resp.Body.Close()
var wxResp usermodel.WxLoginResponse
if err := json.NewDecoder(resp.Body).Decode(&wxResp); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "解析微信登录响应失败: " + err.Error(), "code": "10026"})
return
} }
//func UserLogin(c *gin.Context) { if wxResp.ErrCode != 0 {
// fmt.Println("Request Body:", c.Request.Body) c.JSON(http.StatusBadRequest, gin.H{
// var req usermodel.WxLoginM "error": fmt.Sprintf("微信登录失败: %s (错误码: %d)", wxResp.ErrCode, wxResp.ErrMsg),
// if err := c.ShouldBindJSON(&req); err != nil { "code": "10027",
// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) })
// } return
// fmt.Println("req:123") }
// fmt.Println(req.EncryptedData)
// fmt.Println(req.Code) phoneData, err := decryptWxData(wxResp.SessionKey, req.EncryptedData, req.Iv)
// fmt.Println(req.Iv) if err != nil {
// fmt.Println("使用的appid:", config.Conf.WxID) c.JSON(http.StatusInternalServerError, gin.H{"error": "解密失败: " + err.Error()})
// fmt.Println("使用的secret:", config.Conf.Wxsecret) return
// //----------------发送验证请求 }
// params := url.Values{}
// params.Add("appid", config.Conf.WxID) var phoneInfo usermodel.WxPhoneInfo
// params.Add("secret", config.Conf.Wxsecret) if err := json.Unmarshal(phoneData, &phoneInfo); err != nil {
// params.Add("js_code", req.Code) c.JSON(http.StatusInternalServerError, gin.H{"error": "解析手机号失败"})
// params.Add("grant_type", "authorization_code") return
// requestURL := fmt.Sprintf("%s?%s", wxLoginURL, params.Encode()) }
// fmt.Println("微信接口请求URL:", requestURL)
// if phoneInfo.Watermark.AppID != config.Conf.WxID {
// resp, err := http.Get(fmt.Sprintf("%s?%s", wxLoginURL, params.Encode())) c.JSON(http.StatusForbidden, gin.H{"error": "数据水印验证失败"})
// if err != nil { return
// c.JSON(http.StatusInternalServerError, gin.H{"error": "调用微信登录接口失败: " + err.Error()}) }
// return
// } fmt.Println("用户手机号为:", phoneInfo.PhoneNumber)
// fmt.Println("微信登录返回结果:", resp.Body)
// defer resp.Body.Close() openid := wxResp.OpenID
//
// var wxResp usermodel.WxLoginResponse // 业务逻辑实现
// if err := json.NewDecoder(resp.Body).Decode(&wxResp); err != nil { var user UserInfo
// c.JSON(http.StatusInternalServerError, gin.H{"error": "解析微信登录响应失败: " + err.Error(), "code": "10026"}) var username string
// return // 查找用户是否存在
// } result := databaseInit.UserDB.Where("uid = ?", openid).First(&user)
//
// if wxResp.ErrCode != 0 { if result.Error != nil {
// c.JSON(http.StatusBadRequest, gin.H{ if errors.Is(result.Error, gorm.ErrRecordNotFound) {
// "error": fmt.Sprintf("微信登录失败: %s (错误码: %d)", wxResp.ErrCode, wxResp.ErrMsg), // 用户不存在,创建新用户
// "code": "10027", username := generateUsername()
// }) now := time.Now()
// return newUser := UserInfo{
// } Uid: openid,
// Gender: 2, // 这里假设 gender 传 2可根据实际需求修改
// phoneData, err := decryptWxData(wxResp.SessionKey, req.EncryptedData, req.Iv) CreatedTime: now,
// if err != nil { UpdatedTime: now,
// c.JSON(http.StatusInternalServerError, gin.H{"error": "解密失败: " + err.Error()}) Username: username,
// return Telephone: phoneInfo.PhoneNumber,
// } // 若还有 password、avatar_url、birthdate、bio 等字段需要赋值,可在此补充
// // 比如 Password: "默认密码"实际中密码应加密存储AvatarUrl: "默认头像地址" 等
// var phoneInfo usermodel.WxPhoneInfo }
// if err := json.Unmarshal(phoneData, &phoneInfo); err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "解析手机号失败"}) if err := databaseInit.UserDB.Create(&newUser).Error; err != nil {
// return c.JSON(http.StatusInternalServerError, gin.H{
// } "error": "插入新用户失败: " + err.Error(),
// "code": "10029",
// if phoneInfo.Watermark.AppID != config.Conf.WxID { })
// c.JSON(http.StatusForbidden, gin.H{"error": "数据水印验证失败"}) return
// return }
// } username = newUser.Username
// } else {
// fmt.Println("用户手机号为:", phoneInfo.PhoneNumber) // 数据库查询错误
// c.JSON(http.StatusInternalServerError, gin.H{
// openid := wxResp.OpenID "error": "查询用户存在性失败: " + result.Error.Error(),
// ctx := c.Request.Context() "code": "10029",
// })
// var username string return
// }
// var exists bool } else {
// query := "SELECT EXISTS(SELECT 1 FROM user_info WHERE uid = ? LIMIT 1)" // 用户已存在,获取用户名
// err = databaseInit.UserDB.QueryRowContext(ctx, query, openid).Scan(&exists) username = user.Username
// if err != nil { }
// c.JSON(http.StatusInternalServerError, gin.H{
// "error": "查询用户存在性失败: " + err.Error(), token, err := jwt.GenerateJWTAndStore(openid)
// "code": "10029", if err != nil {
// }) c.JSON(500, gin.H{"error": "生成令牌失败", "code": "10036"})
// return return
// } }
//
// if !exists { c.JSON(http.StatusOK, gin.H{"result": "success", "error": nil, "code": "20001", "token": token,
// username = generateUsername() "userinfo": map[string]string{
// now := time.Now() "username": username,
// insertSQL := ` "uid": openid,
// INSERT INTO user_info ( "telephone": phoneInfo.PhoneNumber,
// uid, gender,createdtime, updatedtime,username,telephone },
// ) VALUES (?, ?, ?,?,?,?) })
// ` }
// _, err := databaseInit.UserDB.ExecContext(
// ctx,
// insertSQL,
// openid, // uid使用微信 openid
// 2,
// now,
// now,
// username,
// phoneInfo.PhoneNumber,
// )
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{
// "error": "插入新用户失败: " + err.Error(),
// "code": "10029",
// })
// return
// }
// } else {
// queryUser := "SELECT username FROM user_info WHERE uid = ? LIMIT 1"
// err = databaseInit.UserDB.QueryRowContext(ctx, queryUser, openid).Scan(&username)
// if err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{
// "error": "查询用户信息失败: " + err.Error(),
// "code": "10030",
// })
// return
// }
// }
//
// token, err := utill.GenerateJWTAndStore(openid)
// if err != nil {
// c.JSON(500, gin.H{"error": "生成令牌失败", "code": "10036"})
// return
// }
//
// c.JSON(http.StatusOK, gin.H{"result": "success", "error": nil, "code": "20001", "token": token,
// "userinfo": map[string]string{
// "username": username,
// "uid": openid,
// "telephone": phoneInfo.PhoneNumber,
// },
// })
//}
func generateUsername() string { func generateUsername() string {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
@@ -178,3 +177,22 @@ func pkcs7Unpad(data []byte) []byte {
} }
return data[:len(data)-padding] return data[:len(data)-padding]
} }
// 定义与表结构对应的用户模型
type UserInfo struct {
Uid string `gorm:"column:uid;primaryKey"`
Telephone string `gorm:"column:telephone"`
Password string `gorm:"column:password"`
AvatarUrl string `gorm:"column:avatar_url"`
Gender int `gorm:"column:gender"`
Birthdate time.Time `gorm:"column:birthdate;type:datetime"`
CreatedTime time.Time `gorm:"column:createdtime;type:datetime"`
UpdatedTime time.Time `gorm:"column:updatedtime;type:datetime"`
Bio string `gorm:"column:bio"`
Username string `gorm:"column:username"`
}
// 自定义表名
func (UserInfo) TableName() string {
return "user_info"
}