Files
ai_wht_wechat/go_backend/controller/auth_controller.go
2025-12-19 22:36:48 +08:00

101 lines
2.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package controller
import (
"ai_xhs/common"
"ai_xhs/service"
"github.com/gin-gonic/gin"
)
type AuthController struct {
authService *service.AuthService
}
func NewAuthController() *AuthController {
return &AuthController{
authService: service.NewAuthService(),
}
}
// WechatLogin 微信小程序登录
func (ctrl *AuthController) WechatLogin(c *gin.Context) {
var req struct {
Code string `json:"code" binding:"required"`
Phone string `json:"phone"` // 可选,员工手机号(直接传明文)
PhoneCode string `json:"phone_code"` // 可选微信手机号加密code
}
if err := c.ShouldBindJSON(&req); err != nil {
common.Error(c, common.CodeInvalidParams, "参数错误: "+err.Error())
return
}
// 调用登录服务
token, employee, err := ctrl.authService.WechatLogin(req.Code, req.Phone, req.PhoneCode)
if err != nil {
common.Error(c, common.CodeServerError, err.Error())
return
}
// 获取用户显示名称(优先使用真实姓名,其次用户名)
displayName := employee.RealName
if displayName == "" {
displayName = employee.Username
}
common.SuccessWithMessage(c, "登录成功", gin.H{
"token": token,
"employee": gin.H{
"id": employee.ID,
"name": displayName,
"username": employee.Username,
"real_name": employee.RealName,
"phone": employee.Phone,
"role": employee.Role,
"enterprise_id": employee.EnterpriseID,
"enterprise_name": employee.EnterpriseName,
"is_bound_xhs": employee.IsBoundXHS,
},
})
}
// PhoneLogin 手机号登录(用于测试)
func (ctrl *AuthController) PhoneLogin(c *gin.Context) {
var req struct {
Phone string `json:"phone" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
common.Error(c, common.CodeInvalidParams, "参数错误: "+err.Error())
return
}
// 调用手机号登录服务
token, employee, err := ctrl.authService.PhoneLogin(req.Phone)
if err != nil {
common.Error(c, common.CodeServerError, err.Error())
return
}
// 获取用户显示名称(优先使用真实姓名,其次用户名)
displayName := employee.RealName
if displayName == "" {
displayName = employee.Username
}
common.SuccessWithMessage(c, "登录成功", gin.H{
"token": token,
"employee": gin.H{
"id": employee.ID,
"name": displayName,
"username": employee.Username,
"real_name": employee.RealName,
"phone": employee.Phone,
"role": employee.Role,
"enterprise_id": employee.EnterpriseID,
"enterprise_name": employee.EnterpriseName,
"is_bound_xhs": employee.IsBoundXHS,
},
})
}