修改gorm

This commit is contained in:
JACKYMYPERSON
2025-09-13 20:00:49 +08:00
parent 0a526d0561
commit 0a94f9c443

View File

@@ -4,151 +4,147 @@ import (
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"encoding/base64" "encoding/base64"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"math/rand" "math/rand"
"net/http"
"net/url"
"strconv" "strconv"
"time" "time"
"toutoukan/config"
"toutoukan/init/databaseInit"
"toutoukan/model/usermodel"
"toutoukan/utill"
) )
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
} }
if wxResp.ErrCode != 0 { //func UserLogin(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{ // fmt.Println("Request Body:", c.Request.Body)
"error": fmt.Sprintf("微信登录失败: %s (错误码: %d)", wxResp.ErrCode, wxResp.ErrMsg), // var req usermodel.WxLoginM
"code": "10027", // if err := c.ShouldBindJSON(&req); err != nil {
}) // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return // }
} // fmt.Println("req:123")
// fmt.Println(req.EncryptedData)
phoneData, err := decryptWxData(wxResp.SessionKey, req.EncryptedData, req.Iv) // fmt.Println(req.Code)
if err != nil { // fmt.Println(req.Iv)
c.JSON(http.StatusInternalServerError, gin.H{"error": "解密失败: " + err.Error()}) // fmt.Println("使用的appid:", config.Conf.WxID)
return // fmt.Println("使用的secret:", config.Conf.Wxsecret)
} // //----------------发送验证请求
// params := url.Values{}
var phoneInfo usermodel.WxPhoneInfo // params.Add("appid", config.Conf.WxID)
if err := json.Unmarshal(phoneData, &phoneInfo); err != nil { // params.Add("secret", config.Conf.Wxsecret)
c.JSON(http.StatusInternalServerError, gin.H{"error": "解析手机号失败"}) // params.Add("js_code", req.Code)
return // params.Add("grant_type", "authorization_code")
} // requestURL := fmt.Sprintf("%s?%s", wxLoginURL, params.Encode())
// fmt.Println("微信接口请求URL:", requestURL)
if phoneInfo.Watermark.AppID != config.Conf.WxID { //
c.JSON(http.StatusForbidden, gin.H{"error": "数据水印验证失败"}) // resp, err := http.Get(fmt.Sprintf("%s?%s", wxLoginURL, params.Encode()))
return // if err != nil {
} // c.JSON(http.StatusInternalServerError, gin.H{"error": "调用微信登录接口失败: " + err.Error()})
// return
fmt.Println("用户手机号为:", phoneInfo.PhoneNumber) // }
// fmt.Println("微信登录返回结果:", resp.Body)
openid := wxResp.OpenID // defer resp.Body.Close()
ctx := c.Request.Context() //
// var wxResp usermodel.WxLoginResponse
var username string // if err := json.NewDecoder(resp.Body).Decode(&wxResp); err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "解析微信登录响应失败: " + err.Error(), "code": "10026"})
var exists bool // return
query := "SELECT EXISTS(SELECT 1 FROM user_info WHERE uid = ? LIMIT 1)" // }
err = databaseInit.UserDB.QueryRowContext(ctx, query, openid).Scan(&exists) //
if err != nil { // if wxResp.ErrCode != 0 {
c.JSON(http.StatusInternalServerError, gin.H{ // c.JSON(http.StatusBadRequest, gin.H{
"error": "查询用户存在性失败: " + err.Error(), // "error": fmt.Sprintf("微信登录失败: %s (错误码: %d)", wxResp.ErrCode, wxResp.ErrMsg),
"code": "10029", // "code": "10027",
}) // })
return // return
} // }
//
if !exists { // phoneData, err := decryptWxData(wxResp.SessionKey, req.EncryptedData, req.Iv)
username = generateUsername() // if err != nil {
now := time.Now() // c.JSON(http.StatusInternalServerError, gin.H{"error": "解密失败: " + err.Error()})
insertSQL := ` // return
INSERT INTO user_info ( // }
uid, gender,createdtime, updatedtime,username,telephone //
) VALUES (?, ?, ?,?,?,?) // var phoneInfo usermodel.WxPhoneInfo
` // if err := json.Unmarshal(phoneData, &phoneInfo); err != nil {
_, err := databaseInit.UserDB.ExecContext( // c.JSON(http.StatusInternalServerError, gin.H{"error": "解析手机号失败"})
ctx, // return
insertSQL, // }
openid, // uid使用微信 openid //
2, // if phoneInfo.Watermark.AppID != config.Conf.WxID {
now, // c.JSON(http.StatusForbidden, gin.H{"error": "数据水印验证失败"})
now, // return
username, // }
phoneInfo.PhoneNumber, //
) // fmt.Println("用户手机号为:", phoneInfo.PhoneNumber)
if err != nil { //
c.JSON(http.StatusInternalServerError, gin.H{ // openid := wxResp.OpenID
"error": "插入新用户失败: " + err.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)"
queryUser := "SELECT username FROM user_info WHERE uid = ? LIMIT 1" // err = databaseInit.UserDB.QueryRowContext(ctx, query, openid).Scan(&exists)
err = databaseInit.UserDB.QueryRowContext(ctx, queryUser, openid).Scan(&username) // if err != nil {
if err != nil { // c.JSON(http.StatusInternalServerError, gin.H{
c.JSON(http.StatusInternalServerError, gin.H{ // "error": "查询用户存在性失败: " + err.Error(),
"error": "查询用户信息失败: " + err.Error(), // "code": "10029",
"code": "10030", // })
}) // return
return // }
} //
} // if !exists {
// username = generateUsername()
token, err := utill.GenerateJWTAndStore(openid) // now := time.Now()
if err != nil { // insertSQL := `
c.JSON(500, gin.H{"error": "生成令牌失败", "code": "10036"}) // INSERT INTO user_info (
return // uid, gender,createdtime, updatedtime,username,telephone
} // ) VALUES (?, ?, ?,?,?,?)
// `
c.JSON(http.StatusOK, gin.H{"result": "success", "error": nil, "code": "20001", "token": token, // _, err := databaseInit.UserDB.ExecContext(
"userinfo": map[string]string{ // ctx,
"username": username, // insertSQL,
"uid": openid, // openid, // uid使用微信 openid
"telephone": phoneInfo.PhoneNumber, // 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())