370 lines
9.6 KiB
Go
370 lines
9.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"strings"
|
|
|
|
"server/models"
|
|
authsvc "server/services/auth"
|
|
"server/services/wechatmini"
|
|
|
|
"github.com/beego/beego/v2/client/orm"
|
|
"github.com/beego/beego/v2/core/logs"
|
|
beego "github.com/beego/beego/v2/server/web"
|
|
)
|
|
|
|
const (
|
|
MiniReasonNotConfigured = "not_configured"
|
|
MiniReasonIdentityNotFound = "identity_not_found"
|
|
MiniReasonNoTenant = "no_tenant"
|
|
MiniReasonWechatAPI = "wechat_api_error"
|
|
)
|
|
|
|
const idPWechatMini = "wechat_mini"
|
|
|
|
type AuthWechatMiniController struct {
|
|
beego.Controller
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) serveJSON(data map[string]interface{}) {
|
|
c.Data["json"] = data
|
|
_ = c.ServeJSON()
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) fail(reason string, bizCode int, msg string) {
|
|
c.Ctx.Output.SetStatus(400)
|
|
c.serveJSON(map[string]interface{}{"code": bizCode, "msg": msg, "reason": reason})
|
|
}
|
|
|
|
func loadMiniConfig(appID string) (*wechatmini.Config, error) {
|
|
if appID = strings.TrimSpace(appID); appID != "" {
|
|
return wechatmini.LoadEnabledAppByAppID(appID)
|
|
}
|
|
return wechatmini.LoadEnabledConfig()
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) Config() {
|
|
cfg, err := loadMiniConfig(c.GetString("appid"))
|
|
if err != nil {
|
|
c.serveJSON(map[string]interface{}{
|
|
"code": 200,
|
|
"data": map[string]interface{}{"enabled": false, "auto_bind": false},
|
|
})
|
|
return
|
|
}
|
|
c.serveJSON(map[string]interface{}{
|
|
"code": 200,
|
|
"data": map[string]interface{}{"enabled": true, "auto_bind": cfg.AutoBind},
|
|
})
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) Login() {
|
|
var req struct {
|
|
Code string `json:"code"`
|
|
PhoneCode string `json:"phone_code"`
|
|
ClientID string `json:"client_id"`
|
|
AppID string `json:"appid"`
|
|
}
|
|
body := c.Ctx.Input.RequestBody
|
|
if len(body) == 0 {
|
|
body, _ = io.ReadAll(c.Ctx.Request.Body)
|
|
}
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
c.fail("", 400, "参数错误")
|
|
return
|
|
}
|
|
req.Code = strings.TrimSpace(req.Code)
|
|
req.PhoneCode = strings.TrimSpace(req.PhoneCode)
|
|
req.ClientID = strings.TrimSpace(req.ClientID)
|
|
if req.ClientID == "" {
|
|
req.ClientID = "yz-miniapp"
|
|
}
|
|
if req.Code == "" {
|
|
c.fail("", 400, "缺少登录凭证,请重新进入小程序")
|
|
return
|
|
}
|
|
|
|
cfg, err := loadMiniConfig(req.AppID)
|
|
if err != nil {
|
|
c.fail(MiniReasonNotConfigured, 400, "小程序登录未开通,请使用账号密码登录")
|
|
return
|
|
}
|
|
|
|
session, err := wechatmini.Code2Session(cfg, req.Code)
|
|
if err != nil {
|
|
msg := err.Error()
|
|
if hint, ok := wechatmini.ExplainError(err); ok {
|
|
msg = hint
|
|
}
|
|
logs.Warn("[wechat-mini] code 换取 openid 失败: %v", err)
|
|
c.fail(MiniReasonWechatAPI, 400, msg)
|
|
return
|
|
}
|
|
|
|
var mobile string
|
|
if req.PhoneCode != "" {
|
|
phone, perr := wechatmini.GetPhoneNumber(cfg, req.PhoneCode)
|
|
if perr != nil {
|
|
logs.Warn("[wechat-mini] 获取手机号失败: %v", perr)
|
|
} else {
|
|
mobile = strings.TrimSpace(phone.PurePhoneNumber)
|
|
if mobile == "" {
|
|
mobile = strings.TrimSpace(phone.PhoneNumber)
|
|
}
|
|
}
|
|
}
|
|
|
|
identity, err := c.resolveIdentity(cfg, mobile, session)
|
|
if err != nil {
|
|
c.fail(MiniReasonIdentityNotFound, 404, "该微信未绑定温新云账号,请使用手机号一键登录或先注册")
|
|
return
|
|
}
|
|
if identity.Status != models.AuthIdentityStatusEnabled {
|
|
c.fail("", 403, "账号已被禁用或锁定,无法登录")
|
|
return
|
|
}
|
|
|
|
tenants, lerr := authsvc.ListTenantOptions(identity.ID)
|
|
if lerr != nil {
|
|
c.fail("", 400, "获取企业列表失败,请重试")
|
|
return
|
|
}
|
|
noTenant := len(tenants) == 0
|
|
tid := uint64(0)
|
|
needChoose := false
|
|
if len(tenants) == 1 {
|
|
tid = tenants[0].Tid
|
|
} else if len(tenants) > 1 {
|
|
tid = authsvc.PendingTenantID
|
|
needChoose = true
|
|
}
|
|
|
|
username := "微信用户"
|
|
if identity.Nickname != nil && strings.TrimSpace(*identity.Nickname) != "" {
|
|
username = strings.TrimSpace(*identity.Nickname)
|
|
} else if identity.Mobile != nil && *identity.Mobile != "" {
|
|
username = *identity.Mobile
|
|
}
|
|
|
|
tokens, terr := c.issueTokens(identity.ID, tid, req.ClientID, username, needChoose)
|
|
if terr != nil {
|
|
c.fail("", 400, terr.Error())
|
|
return
|
|
}
|
|
|
|
resp := map[string]interface{}{
|
|
"code": 200,
|
|
"msg": "登录成功",
|
|
"tokens": tokens,
|
|
"tenants": tenants,
|
|
"identity": map[string]interface{}{"id": identity.ID, "nickname": username, "mobile": mobileOr(identity)},
|
|
"need_tenant": noTenant,
|
|
}
|
|
if needChoose {
|
|
resp["need_choose_tenant"] = true
|
|
resp["sid"] = tokens.Sid
|
|
}
|
|
c.serveJSON(resp)
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) RegisterConfirm() {
|
|
var req struct {
|
|
Scene string `json:"scene"`
|
|
Code string `json:"code"`
|
|
PhoneCode string `json:"phone_code"`
|
|
AppID string `json:"appid"`
|
|
}
|
|
body := c.Ctx.Input.RequestBody
|
|
if len(body) == 0 {
|
|
body, _ = io.ReadAll(c.Ctx.Request.Body)
|
|
}
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
c.fail("", 400, "参数错误")
|
|
return
|
|
}
|
|
req.Scene = strings.TrimSpace(req.Scene)
|
|
if req.Scene == "" {
|
|
c.fail("", 400, "缺少会话标识,请重新扫码")
|
|
return
|
|
}
|
|
if err := wechatmini.ConfirmRegister(req.Scene, req.Code, req.PhoneCode, req.AppID); err != nil {
|
|
msg := err.Error()
|
|
if hint, ok := wechatmini.ExplainError(err); ok {
|
|
msg = hint
|
|
}
|
|
logs.Warn("[wechat-mini] 注册确认失败 scene=%s: %v", req.Scene, err)
|
|
c.fail(MiniReasonWechatAPI, 400, msg)
|
|
return
|
|
}
|
|
c.serveJSON(map[string]interface{}{"code": 200, "msg": "确认成功,请回到电脑继续完成注册"})
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) Bind() {
|
|
claims := claimsFromCtxThird(c.Ctx)
|
|
if claims == nil || claims.UserID <= 0 {
|
|
c.Ctx.Output.SetStatus(401)
|
|
c.serveJSON(map[string]interface{}{"code": 401, "msg": "未登录"})
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Code string `json:"code"`
|
|
AppID string `json:"appid"`
|
|
}
|
|
body := c.Ctx.Input.RequestBody
|
|
if len(body) == 0 {
|
|
body, _ = io.ReadAll(c.Ctx.Request.Body)
|
|
}
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
c.fail("", 400, "参数错误")
|
|
return
|
|
}
|
|
req.Code = strings.TrimSpace(req.Code)
|
|
if req.Code == "" {
|
|
c.fail("", 400, "缺少登录凭证,请重新进入小程序")
|
|
return
|
|
}
|
|
|
|
cfg, err := loadMiniConfig(req.AppID)
|
|
if err != nil {
|
|
c.fail(MiniReasonNotConfigured, 400, "小程序登录未开通")
|
|
return
|
|
}
|
|
|
|
session, err := wechatmini.Code2Session(cfg, req.Code)
|
|
if err != nil {
|
|
msg := err.Error()
|
|
if hint, ok := wechatmini.ExplainError(err); ok {
|
|
msg = hint
|
|
}
|
|
logs.Warn("[wechat-mini] 绑定 code 换取 openid 失败: %v", err)
|
|
c.fail(MiniReasonWechatAPI, 400, msg)
|
|
return
|
|
}
|
|
|
|
c.syncBinding(cfg, uint64(claims.UserID), session, true)
|
|
c.serveJSON(map[string]interface{}{"code": 200, "msg": "绑定成功"})
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) resolveIdentity(cfg *wechatmini.Config, mobile string, session *wechatmini.Session) (*models.AuthIdentity, error) {
|
|
if mobile != "" {
|
|
if identity, err := authsvc.FindIdentityByAccount(mobile); err == nil {
|
|
c.syncBinding(cfg, identity.ID, session, true)
|
|
return identity, nil
|
|
}
|
|
}
|
|
|
|
bind := findMiniBinding(session.OpenID, session.UnionID)
|
|
if bind == nil {
|
|
return nil, orm.ErrNoRows
|
|
}
|
|
var identity models.AuthIdentity
|
|
if err := models.Orm.QueryTable(new(models.AuthIdentity)).
|
|
Filter("id", bind.IdentityID).
|
|
Filter("delete_time__isnull", true).
|
|
One(&identity); err != nil {
|
|
return nil, err
|
|
}
|
|
return &identity, nil
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) syncBinding(cfg *wechatmini.Config, identityID uint64, session *wechatmini.Session, verified bool) {
|
|
bind := findMiniBinding(session.OpenID, session.UnionID)
|
|
if bind != nil && bind.IdentityID == identityID {
|
|
return
|
|
}
|
|
if bind != nil {
|
|
if !verified {
|
|
return
|
|
}
|
|
_, _ = models.Orm.QueryTable(new(models.AuthIdentityThird)).Filter("id", bind.ID).Delete()
|
|
}
|
|
if !verified && !cfg.AutoBind {
|
|
return
|
|
}
|
|
item := &models.AuthIdentityThird{
|
|
IdentityID: identityID,
|
|
Provider: idPWechatMini,
|
|
OpenID: session.OpenID,
|
|
}
|
|
if session.UnionID != "" {
|
|
uid := session.UnionID
|
|
item.UnionID = &uid
|
|
}
|
|
_, _ = models.Orm.Insert(item)
|
|
}
|
|
|
|
func findMiniBinding(openID, unionID string) *models.AuthIdentityThird {
|
|
qs := models.Orm.QueryTable(new(models.AuthIdentityThird)).Filter("provider", idPWechatMini)
|
|
if openID != "" {
|
|
var bind models.AuthIdentityThird
|
|
if err := qs.Filter("open_id", openID).One(&bind); err == nil {
|
|
return &bind
|
|
}
|
|
}
|
|
if unionID != "" {
|
|
var bind models.AuthIdentityThird
|
|
if err := qs.Filter("union_id", unionID).One(&bind); err == nil {
|
|
return &bind
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *AuthWechatMiniController) issueTokens(identityID, tid uint64, clientID, username string, needChoose bool) (*authsvc.TokenPair, error) {
|
|
accessTTL := 0
|
|
if needChoose {
|
|
accessTTL = 600
|
|
}
|
|
sess, serr := authsvc.CreateSession(authsvc.SessionInfo{
|
|
IdentityID: identityID,
|
|
Tid: tid,
|
|
ClientID: clientID,
|
|
IP: c.Ctx.Input.IP(),
|
|
UserAgent: c.Ctx.Request.UserAgent(),
|
|
LoginType: "wechat_mini",
|
|
Amr: "wechat_mini",
|
|
})
|
|
if serr != nil {
|
|
return nil, serr
|
|
}
|
|
tokens, terr := authsvc.IssueTokens(authsvc.TokenIssue{
|
|
IdentityID: identityID,
|
|
Tid: tid,
|
|
ClientID: clientID,
|
|
Sid: sess.Sid,
|
|
Username: username,
|
|
UserType: "app",
|
|
Amr: "wechat_mini",
|
|
AccessTTL: accessTTL,
|
|
})
|
|
if terr != nil {
|
|
return nil, terr
|
|
}
|
|
|
|
identityIDCopy := identityID
|
|
tidCopy := tid
|
|
amr := "wechat_mini"
|
|
_, _ = models.Orm.Insert(&models.AuthLoginLog{
|
|
Tid: &tidCopy,
|
|
IdentityID: &identityIDCopy,
|
|
UserName: username,
|
|
ClientID: clientID,
|
|
LoginType: "wechat_mini",
|
|
Amr: &amr,
|
|
Status: 1,
|
|
Message: "微信小程序一键登录成功",
|
|
IP: c.Ctx.Input.IP(),
|
|
UserAgent: c.Ctx.Request.UserAgent(),
|
|
})
|
|
return tokens, nil
|
|
}
|
|
|
|
func mobileOr(identity *models.AuthIdentity) string {
|
|
if identity != nil && identity.Mobile != nil {
|
|
return *identity.Mobile
|
|
}
|
|
return ""
|
|
}
|