更新密码找回uniapp
This commit is contained in:
1 parent
7f9a66da0f
commit
3fdda89833
1304 files changed
+3503
-26132
No files matched your search
@@ -10,18 +10,6 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 移动端免登录票据
|
||||
//
|
||||
// 背景:移动端用「密码直连」拿到的是 client_id=yz-uniapp、user_type=app 的令牌,
|
||||
// Web 端(管理后台)只认自己 localStorage 里 client_id=yz-backend 的令牌,
|
||||
// 两者登录态不共享,导致移动端打开 webview 时又要走一遍统一认证登录。
|
||||
//
|
||||
// 方案:移动端令牌 → 一次性票据 → Web 端令牌。
|
||||
// 票据本身是一次性的短时效凭证,即使泄露也无法二次使用。
|
||||
// =============================================================
|
||||
|
||||
// AppTicketTTL 票据有效期。移动端拿到后应立即跳转,不需要长时效。
|
||||
const AppTicketTTL = 60 * time.Second
|
||||
|
||||
var (
|
||||
@@ -30,7 +18,6 @@ var (
|
||||
ErrAppTicketExpired = errors.New("登录票据已过期")
|
||||
)
|
||||
|
||||
// CreateAppTicket 签发一次性票据
|
||||
func CreateAppTicket(identityID, tid uint64, clientID string) (string, error) {
|
||||
if identityID == 0 {
|
||||
return "", errors.New("身份无效")
|
||||
@@ -56,7 +43,6 @@ func CreateAppTicket(identityID, tid uint64, clientID string) (string, error) {
|
||||
return ticket, nil
|
||||
}
|
||||
|
||||
// ConsumeAppTicket 核销一次性票据(CAS 防重放),返回票据携带的身份与租户。
|
||||
func ConsumeAppTicket(ticket string) (*models.AuthAppLoginTicket, error) {
|
||||
ticket = strings.TrimSpace(ticket)
|
||||
if ticket == "" {
|
||||
@@ -89,7 +75,6 @@ func ConsumeAppTicket(ticket string) (*models.AuthAppLoginTicket, error) {
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// PurgeExpiredAppTickets 清理过期票据(防止表无限增长,由调用方定期触发)
|
||||
func PurgeExpiredAppTickets() (int64, error) {
|
||||
return models.Orm.QueryTable(new(models.AuthAppLoginTicket)).
|
||||
Filter("expire_at__lt", time.Now().Add(-24*time.Hour)).
|
||||
|
||||
+15
-48
@@ -19,28 +19,24 @@ import (
|
||||
"github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
// 人机验证方式(与平台登录验证配置 login_verify_type 保持一致)
|
||||
const (
|
||||
VerifyTypeCaptcha = "captcha" // 本地图形验证码
|
||||
VerifyTypeSMS = "sms" // 短信验证码
|
||||
VerifyTypeEmail = "email" // 邮箱验证码
|
||||
VerifyTypeGeetest = "geetest" // 极验 4.0
|
||||
VerifyTypeGeetest4 = "geetest4" // 极验 4.0
|
||||
VerifyTypeGeetest3 = "geetest3" // 极验 3.0
|
||||
VerifyTypeCaptcha = "captcha"
|
||||
VerifyTypeSMS = "sms"
|
||||
VerifyTypeEmail = "email"
|
||||
VerifyTypeGeetest = "geetest"
|
||||
VerifyTypeGeetest4 = "geetest4"
|
||||
VerifyTypeGeetest3 = "geetest3"
|
||||
)
|
||||
|
||||
// geetest4ValidateURL 极验 4.0 服务端二次校验地址
|
||||
const geetest4ValidateURL = "https://gcaptcha4.geetest.com/validate"
|
||||
|
||||
// 人机验证失败类别
|
||||
const (
|
||||
captchaFailRequired = "required" // 未完成验证 / 参数缺失
|
||||
captchaFailFailed = "failed" // 极验服务端判定未通过
|
||||
captchaFailService = "service" // 极验校验服务不可用(网络/超时/响应异常)
|
||||
captchaFailNotSet = "notset" // 未配置极验
|
||||
captchaFailRequired = "required"
|
||||
captchaFailFailed = "failed"
|
||||
captchaFailService = "service"
|
||||
captchaFailNotSet = "notset"
|
||||
)
|
||||
|
||||
// captchaError 人机验证失败,msg 可直接展示给用户
|
||||
type captchaError struct {
|
||||
kind string
|
||||
msg string
|
||||
@@ -48,25 +44,21 @@ type captchaError struct {
|
||||
|
||||
func (e *captchaError) Error() string { return e.msg }
|
||||
|
||||
// 人机验证错误
|
||||
var (
|
||||
ErrCaptchaRequired = errors.New("请先完成人机验证")
|
||||
ErrCaptchaFailed = errors.New("人机验证未通过,请重新验证")
|
||||
ErrCaptchaNotSet = errors.New("人机验证未配置,请联系管理员")
|
||||
)
|
||||
|
||||
// LoginVerifyConfig 登录页使用的人机验证配置
|
||||
type LoginVerifyConfig struct {
|
||||
OpenVerify bool `json:"openVerify"` // 是否开启登录验证
|
||||
VerifyType string `json:"verifyType"` // captcha/sms/email/geetest/geetest4/geetest3
|
||||
GeetestVersion string `json:"geetestVersion"` // 极验版本:4 / 3
|
||||
CaptchaID string `json:"captchaId"` // 极验 captcha_id,未配置时为空
|
||||
OpenVerify bool `json:"openVerify"`
|
||||
VerifyType string `json:"verifyType"`
|
||||
GeetestVersion string `json:"geetestVersion"`
|
||||
CaptchaID string `json:"captchaId"`
|
||||
|
||||
geetestKey string // 服务端校验密钥,不下发给前端
|
||||
geetestKey string
|
||||
}
|
||||
|
||||
// NeedGeetest 是否需要弹出极验。
|
||||
// 目前认证中心只接入了极验 4.0(gt4),极验 3.0 待接入后再开启强制校验。
|
||||
func (c LoginVerifyConfig) NeedGeetest() bool {
|
||||
if !c.OpenVerify {
|
||||
return false
|
||||
@@ -79,11 +71,6 @@ func (c LoginVerifyConfig) NeedGeetest() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// GetLoginVerifyConfig 读取登录验证配置。
|
||||
//
|
||||
// 登录发生在选择企业之前,租户未知,因此以平台全局配置为准;
|
||||
// 若传入 tid 且该租户单独配置了验证方式,则用租户配置覆盖开关与类型,
|
||||
// 极验参数(captcha_id / key)始终取全局配置。
|
||||
func GetLoginVerifyConfig(tid uint64) LoginVerifyConfig {
|
||||
cfg := LoginVerifyConfig{VerifyType: VerifyTypeCaptcha}
|
||||
|
||||
@@ -136,7 +123,6 @@ func GetLoginVerifyConfig(tid uint64) LoginVerifyConfig {
|
||||
return cfg
|
||||
}
|
||||
|
||||
// CaptchaResult 前端极验验证通过后提交的校验参数
|
||||
type CaptchaResult struct {
|
||||
CaptchaID string `json:"captcha_id"`
|
||||
LotNumber string `json:"lot_number"`
|
||||
@@ -145,10 +131,6 @@ type CaptchaResult struct {
|
||||
CaptchaOutput string `json:"captcha_output"`
|
||||
}
|
||||
|
||||
// VerifyLoginCaptcha 校验人机验证结果,通过返回 nil。
|
||||
//
|
||||
// 仅在开启极验时拦截:未开启或为图形码/短信/邮箱/极验3 时不做处理,
|
||||
// 避免登录页没有对应 UI 却被服务端拒绝。
|
||||
func VerifyLoginCaptcha(tid uint64, result CaptchaResult) error {
|
||||
cfg := GetLoginVerifyConfig(tid)
|
||||
if !cfg.NeedGeetest() {
|
||||
@@ -162,7 +144,6 @@ func VerifyLoginCaptcha(tid uint64, result CaptchaResult) error {
|
||||
cfg.CaptchaID, result.LotNumber, result.PassToken != "", result.GenTime, result.CaptchaOutput != "")
|
||||
return &captchaError{kind: captchaFailRequired, msg: ErrCaptchaRequired.Error()}
|
||||
}
|
||||
// 未配置极验 KEY 时无法做服务端二次校验,仅保证参数完整
|
||||
if cfg.geetestKey == "" {
|
||||
logs.Warn("[auth] 未配置极验 captcha_key,跳过服务端二次校验(仅校验参数完整性)")
|
||||
return nil
|
||||
@@ -172,7 +153,6 @@ func VerifyLoginCaptcha(tid uint64, result CaptchaResult) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 逃生开关:极验服务端不可用时避免整站无法登录
|
||||
if geetestFailOpen() {
|
||||
logs.Warn("[auth] 极验服务端校验失败但已开启 fail_open,按配置放行: %v", err)
|
||||
return nil
|
||||
@@ -180,16 +160,11 @@ func VerifyLoginCaptcha(tid uint64, result CaptchaResult) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// geetestFailOpen 极验二次校验失败时是否放行。
|
||||
// 平台设置 login_verify_geetest4_fail_open = "1" 时开启(默认 0,严格拒绝)。
|
||||
// 用于极验密钥配置错误或服务不可用的应急恢复。
|
||||
func geetestFailOpen() bool {
|
||||
return strings.TrimSpace(models.GetPlatformSettingValue("login_verify_geetest4_fail_open", "0")) == "1"
|
||||
}
|
||||
|
||||
// verifyGeetest4 调用极验 4.0 二次校验接口,确认验证结果未被伪造
|
||||
func verifyGeetest4(cfg LoginVerifyConfig, result CaptchaResult) error {
|
||||
// sign_token = HMAC-SHA256(captcha_key, lot_number) 的十六进制串
|
||||
mac := hmac.New(sha256.New, []byte(cfg.geetestKey))
|
||||
mac.Write([]byte(result.LotNumber))
|
||||
signToken := hex.EncodeToString(mac.Sum(nil))
|
||||
@@ -247,18 +222,11 @@ func verifyGeetest4(cfg LoginVerifyConfig, result CaptchaResult) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 校验未通过:记录原始响应,并把原因转成可读提示,便于定位是密钥配置问题还是验证过期
|
||||
logs.Warn("[auth] 极验二次校验未通过 captcha_id=%s lot_number=%s result=%q status=%q reason=%q body=%s",
|
||||
captchaID, result.LotNumber, res.Result, res.Status, res.Reason, string(body))
|
||||
return &captchaError{kind: captchaFailFailed, msg: geetestFailReason(res.Reason)}
|
||||
}
|
||||
|
||||
// DiagnoseGeetest4 极验 4.0 配置自检。
|
||||
//
|
||||
// 用一个固定的 lot_number 调二次校验接口,依据极验返回判断问题所在:
|
||||
// - 请求超时/失败 → 服务器无法访问极验服务(网络或防火墙)
|
||||
// - sign_token error → 网络可达,但 captcha_key 与 captcha_id 不匹配
|
||||
// - lot_number error → 网络可达且密钥正确(lot_number 是捏造的,报错属正常)
|
||||
func DiagnoseGeetest4() map[string]interface{} {
|
||||
cfg := GetLoginVerifyConfig(0)
|
||||
out := map[string]interface{}{
|
||||
@@ -334,7 +302,6 @@ func DiagnoseGeetest4() map[string]interface{} {
|
||||
return out
|
||||
}
|
||||
|
||||
// geetestFailReason 极验失败原因(reason)转中文提示,帮助区分“密钥配置错误”与“验证已失效”
|
||||
func geetestFailReason(reason string) string {
|
||||
r := strings.ToLower(strings.TrimSpace(reason))
|
||||
switch r {
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// Package auth 统一认证中心(UAC)业务层。
|
||||
//
|
||||
// 认证中心只负责「你是谁、你能进哪些企业、你能用哪些应用」,
|
||||
// 菜单/按钮/数据权限仍由各业务端自治。
|
||||
package auth
|
||||
|
||||
import (
|
||||
@@ -12,7 +8,6 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// TenantOption 登录后可选择进入的企业(一人可在多家企业任职)
|
||||
type TenantOption struct {
|
||||
Tid uint64 `json:"tid"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
@@ -22,7 +17,6 @@ type TenantOption struct {
|
||||
IsDefault bool `json:"is_default"`
|
||||
}
|
||||
|
||||
// IdentityProfile 认证中心视角的身份概要
|
||||
type IdentityProfile struct {
|
||||
ID uint64 `json:"id"`
|
||||
UnionID string `json:"union_id"`
|
||||
@@ -35,8 +29,6 @@ type IdentityProfile struct {
|
||||
Tenants []TenantOption `json:"tenants"`
|
||||
}
|
||||
|
||||
// FindIdentityByAccount 按登录账号查找身份。
|
||||
// 匹配顺序:全局账号(账号注册)→ 手机号 → 邮箱 → 企业内账号(先查绑定再回查身份)。
|
||||
func FindIdentityByAccount(account string) (*models.AuthIdentity, error) {
|
||||
account = strings.TrimSpace(account)
|
||||
if account == "" {
|
||||
@@ -51,7 +43,6 @@ func FindIdentityByAccount(account string) (*models.AuthIdentity, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// 企业内账号:yz_auth_tenant_user.account → identity_id
|
||||
var bind models.AuthTenantUser
|
||||
if err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
Filter("account", account).
|
||||
@@ -66,7 +57,6 @@ func FindIdentityByAccount(account string) (*models.AuthIdentity, error) {
|
||||
return nil, orm.ErrNoRows
|
||||
}
|
||||
|
||||
// ListTenantOptions 列出该身份可登录的企业(过滤企业停用与绑定停用)。
|
||||
func ListTenantOptions(identityID uint64) ([]TenantOption, error) {
|
||||
var binds []models.AuthTenantUser
|
||||
if _, err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
@@ -85,10 +75,10 @@ func ListTenantOptions(identityID uint64) ([]TenantOption, error) {
|
||||
Filter("id", b.Tid).
|
||||
Filter("delete_time__isnull", true).
|
||||
One(&tenant); err != nil {
|
||||
continue // 租户不存在或已删除
|
||||
continue
|
||||
}
|
||||
if tenant.Status != 1 {
|
||||
continue // 租户停用
|
||||
continue
|
||||
}
|
||||
opt := TenantOption{
|
||||
Tid: b.Tid,
|
||||
@@ -105,7 +95,6 @@ func ListTenantOptions(identityID uint64) ([]TenantOption, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetTenantUser 获取身份在指定企业的绑定关系
|
||||
func GetTenantUser(identityID, tid uint64) (*models.AuthTenantUser, error) {
|
||||
var bind models.AuthTenantUser
|
||||
err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
@@ -119,8 +108,6 @@ func GetTenantUser(identityID, tid uint64) (*models.AuthTenantUser, error) {
|
||||
return &bind, nil
|
||||
}
|
||||
|
||||
// FindIdentityIDByAccount 按「企业 + 账号」查找认证中心身份ID。
|
||||
// 账号可以是企业内账号、手机号或邮箱(老登录入口按账号登录时使用)。
|
||||
func FindIdentityIDByAccount(tid uint64, account string) uint64 {
|
||||
account = strings.TrimSpace(account)
|
||||
if tid == 0 || account == "" {
|
||||
@@ -138,7 +125,6 @@ func FindIdentityIDByAccount(tid uint64, account string) uint64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// BuildProfile 组装身份概要(含可选企业列表)
|
||||
func BuildProfile(m *models.AuthIdentity) (*IdentityProfile, error) {
|
||||
tenants, err := ListTenantOptions(m.ID)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// Package idp 第三方身份源(微信/钉钉/飞书/QQ/GitHub/Google)统一适配层。
|
||||
//
|
||||
// 各平台 OAuth2 流程基本一致,差异只在端点地址、参数名与用户字段,
|
||||
// 因此用一份通用实现 + 预设配置覆盖,新增平台只需加一条 preset。
|
||||
package idp
|
||||
|
||||
import (
|
||||
@@ -17,16 +13,14 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// UserInfo 第三方返回的标准化用户信息
|
||||
type UserInfo struct {
|
||||
OpenID string // 该平台内的唯一 ID(必填)
|
||||
UnionID string // 跨平台唯一 ID(微信/钉钉有,GitHub/Google 用 OpenID 代替)
|
||||
OpenID string
|
||||
UnionID string
|
||||
Nickname string
|
||||
Avatar string
|
||||
Raw string // 原始 JSON,便于排查
|
||||
Raw string
|
||||
}
|
||||
|
||||
// Config 一个第三方身份源的配置
|
||||
type Config struct {
|
||||
Provider string
|
||||
AuthURL string
|
||||
@@ -35,21 +29,17 @@ type Config struct {
|
||||
Scopes []string
|
||||
AppID string
|
||||
AppSecret string
|
||||
ProxyURL string // GitHub/Google 在国内服务器需要代理时填写
|
||||
ProxyURL string
|
||||
|
||||
// 参数风格:微信/QQ 用 appid+secret,其余用 client_id+client_secret
|
||||
UseAppIDStyle bool
|
||||
// 用户信息接口风格:query=拼在 URL 上(微信/QQ),bearer=放 Authorization 头
|
||||
UserinfoStyle string
|
||||
|
||||
// 用户信息字段映射(一级 JSON 字段)
|
||||
OpenIDField string
|
||||
UnionIDField string
|
||||
NicknameField string
|
||||
AvatarField string
|
||||
}
|
||||
|
||||
// presets 各平台预设(端点与字段映射)
|
||||
var presets = map[string]Config{
|
||||
models.IdPWechat: {
|
||||
Provider: models.IdPWechat,
|
||||
@@ -124,7 +114,6 @@ var presets = map[string]Config{
|
||||
},
|
||||
}
|
||||
|
||||
// Supported 返回支持的第三方平台列表
|
||||
func Supported() []string {
|
||||
return []string{
|
||||
models.IdPWechat, models.IdPDingTalk, models.IdPFeishu,
|
||||
@@ -132,17 +121,11 @@ func Supported() []string {
|
||||
}
|
||||
}
|
||||
|
||||
// IsSupported 是否为已知平台
|
||||
func IsSupported(provider string) bool {
|
||||
_, ok := presets[provider]
|
||||
return ok
|
||||
}
|
||||
|
||||
// LoadConfig 读取身份源配置:
|
||||
// - tid > 0 时优先取租户自带身份源(yz_auth_tenant_idp)
|
||||
// - 取不到或 tid=0 时取平台全局配置(tid=0 的记录)
|
||||
//
|
||||
// 未配置任何记录时返回 false,调用方应提示「该登录方式未开通」。
|
||||
func LoadConfig(provider string, tid uint64) (Config, bool) {
|
||||
base, ok := presets[provider]
|
||||
if !ok {
|
||||
@@ -159,7 +142,6 @@ func LoadConfig(provider string, tid uint64) (Config, bool) {
|
||||
return applyDBConfig(base, &row), true
|
||||
}
|
||||
}
|
||||
// 回落到平台全局配置(tid=0)
|
||||
if err := qs.Filter("tid", 0).One(&row); err == nil {
|
||||
return applyDBConfig(base, &row), true
|
||||
}
|
||||
@@ -202,7 +184,6 @@ func splitList(s string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// BuildAuthURL 生成跳转到第三方授权页的地址
|
||||
func BuildAuthURL(cfg Config, redirectURI, state string) string {
|
||||
v := url.Values{}
|
||||
if cfg.UseAppIDStyle {
|
||||
@@ -217,19 +198,16 @@ func BuildAuthURL(cfg Config, redirectURI, state string) string {
|
||||
|
||||
addr := cfg.AuthURL + "?" + v.Encode()
|
||||
if cfg.Provider == models.IdPWechat {
|
||||
// 微信要求在 hash 后带 #wechat_redirect
|
||||
return addr + "#wechat_redirect"
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
// Exchange 用授权码换取用户信息
|
||||
func Exchange(cfg Config, code string) (*UserInfo, error) {
|
||||
if cfg.AppID == "" || cfg.AppSecret == "" {
|
||||
return nil, errors.New("该登录方式尚未配置,请联系管理员")
|
||||
}
|
||||
|
||||
// 1. code 换 access_token
|
||||
v := url.Values{}
|
||||
if cfg.UseAppIDStyle {
|
||||
v.Set("appid", cfg.AppID)
|
||||
@@ -252,7 +230,6 @@ func Exchange(cfg Config, code string) (*UserInfo, error) {
|
||||
}
|
||||
openID := firstStr(tokenMap, "openid", "unionId", "open_id", "sub", "id")
|
||||
|
||||
// 2. 取用户信息
|
||||
var infoMap map[string]interface{}
|
||||
if cfg.UserinfoStyle == "query" {
|
||||
q := url.Values{}
|
||||
@@ -260,7 +237,6 @@ func Exchange(cfg Config, code string) (*UserInfo, error) {
|
||||
if openID != "" {
|
||||
q.Set("openid", openID)
|
||||
}
|
||||
// QQ 需要额外带 oauth_consumer_key
|
||||
if cfg.Provider == models.IdPQQ {
|
||||
q.Set("oauth_consumer_key", cfg.AppID)
|
||||
}
|
||||
@@ -277,7 +253,6 @@ func Exchange(cfg Config, code string) (*UserInfo, error) {
|
||||
return nil, err
|
||||
}
|
||||
infoMap = parseMap(body)
|
||||
// 飞书把数据包在 data 里
|
||||
if d, ok := infoMap["data"].(map[string]interface{}); ok {
|
||||
infoMap = d
|
||||
}
|
||||
@@ -303,8 +278,6 @@ func Exchange(cfg Config, code string) (*UserInfo, error) {
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- HTTP
|
||||
|
||||
func client(cfg Config) *http.Client {
|
||||
c := &http.Client{Timeout: 15 * time.Second}
|
||||
if cfg.ProxyURL != "" {
|
||||
@@ -359,9 +332,6 @@ func get(cfg Config, target string, headers map[string]string) (string, error) {
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 解析工具
|
||||
|
||||
// parseMap 兼容 JSON 与 querystring 两种响应(微信/QQ 早期接口返回 form 格式)
|
||||
func parseMap(body string) map[string]interface{} {
|
||||
out := map[string]interface{}{}
|
||||
if err := json.Unmarshal([]byte(body), &out); err == nil {
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"server/pkg/passwordutil"
|
||||
)
|
||||
|
||||
// 登录方式与认证手段(amr)
|
||||
const (
|
||||
LoginTypePassword = "password"
|
||||
LoginTypeSMS = "sms"
|
||||
@@ -21,14 +20,12 @@ const (
|
||||
AmrOtp = "otp"
|
||||
)
|
||||
|
||||
// 失败锁定策略
|
||||
const (
|
||||
MaxFailCount = 5 // 连续失败次数阈值
|
||||
LockDuration = 15 * time.Minute // 锁定时长
|
||||
PendingTenantID = 0 // 未选择企业时的 tid
|
||||
MaxFailCount = 5
|
||||
LockDuration = 15 * time.Minute
|
||||
PendingTenantID = 0
|
||||
)
|
||||
|
||||
// 登录失败错误
|
||||
var (
|
||||
ErrAccountDisabled = errors.New("账号已禁用")
|
||||
ErrAccountLocked = errors.New("账号已被锁定,请稍后再试")
|
||||
@@ -38,9 +35,6 @@ var (
|
||||
ErrTenantUserDisabled = errors.New("在该企业的账号已被停用")
|
||||
)
|
||||
|
||||
// LoginResult 登录结果。
|
||||
// 当 NeedChooseTenant 为 true 时表示一人多企业,前端需展示企业列表让用户选择,
|
||||
// 选择后调用 ChooseTenant 换取正式令牌。
|
||||
type LoginResult struct {
|
||||
NeedChooseTenant bool `json:"need_choose_tenant"`
|
||||
Identity *IdentityProfile `json:"identity"`
|
||||
@@ -48,15 +42,10 @@ type LoginResult struct {
|
||||
Tokens *TokenPair `json:"tokens,omitempty"`
|
||||
}
|
||||
|
||||
// PasswordLogin 账号密码登录
|
||||
//
|
||||
// 流程:查身份 → 校验状态/锁定 → 校验密码 → 失败计数 → 列出可登录企业
|
||||
// - 只绑定 1 家企业:直接建会话并签发令牌
|
||||
// - 绑定多家企业:建待选会话(tid=0),签发临时令牌,等用户选择企业
|
||||
func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginResult, error) {
|
||||
identity, err := FindIdentityByAccount(account)
|
||||
if err != nil {
|
||||
return nil, ErrPasswordWrong // 不暴露账号是否存在
|
||||
return nil, ErrPasswordWrong
|
||||
}
|
||||
|
||||
if err := checkIdentityStatus(identity); err != nil {
|
||||
@@ -68,7 +57,6 @@ func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginRes
|
||||
return nil, ErrPasswordWrong
|
||||
}
|
||||
|
||||
// 登录成功:重置失败计数,旧算法密码自动升级
|
||||
_ = resetFail(identity.ID)
|
||||
if passwordutil.NeedsRehash(*identity.PasswordHash) {
|
||||
if hashed, hErr := passwordutil.Hash(password); hErr == nil {
|
||||
@@ -97,7 +85,6 @@ func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginRes
|
||||
|
||||
result := &LoginResult{Tenants: tenants, Identity: profile}
|
||||
|
||||
// 唯一企业直接进入;多家企业先建待选会话
|
||||
targetTid := uint64(PendingTenantID)
|
||||
if len(tenants) == 1 {
|
||||
targetTid = tenants[0].Tid
|
||||
@@ -115,7 +102,6 @@ func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginRes
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 待选状态下令牌有效期缩短为 10 分钟(仅够用户做完选择)
|
||||
accessTTL := 0
|
||||
if targetTid == PendingTenantID {
|
||||
accessTTL = 600
|
||||
@@ -130,7 +116,6 @@ func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginRes
|
||||
Username: profile.Nickname,
|
||||
Amr: AmrPwd,
|
||||
AccessTTL: accessTTL,
|
||||
// 不指定 UserType:由 IssueTokens 按应用编码给出 backend / app
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -151,7 +136,6 @@ func PasswordLogin(account, password, clientID, ip, userAgent string) (*LoginRes
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChooseTenant 选择进入的企业:校验绑定后更新会话 tid 并重新签发令牌
|
||||
func ChooseTenant(sid string, tid uint64, clientID string) (*TokenPair, *IdentityProfile, error) {
|
||||
sess, err := GetSession(sid)
|
||||
if err != nil {
|
||||
@@ -192,7 +176,6 @@ func ChooseTenant(sid string, tid uint64, clientID string) (*TokenPair, *Identit
|
||||
return tokens, profile, nil
|
||||
}
|
||||
|
||||
// checkIdentityStatus 校验身份状态与锁定时间
|
||||
func checkIdentityStatus(m *models.AuthIdentity) error {
|
||||
if m.Status == models.AuthIdentityStatusDisabled {
|
||||
return ErrAccountDisabled
|
||||
@@ -201,7 +184,6 @@ func checkIdentityStatus(m *models.AuthIdentity) error {
|
||||
if m.LockedUntil != nil && m.LockedUntil.After(time.Now()) {
|
||||
return ErrAccountLocked
|
||||
}
|
||||
// 锁定已到期,自动解锁
|
||||
_, _ = models.Orm.QueryTable(new(models.AuthIdentity)).
|
||||
Filter("id", m.ID).
|
||||
Update(map[string]interface{}{"status": models.AuthIdentityStatusEnabled, "fail_count": 0, "locked_until": nil})
|
||||
@@ -209,7 +191,6 @@ func checkIdentityStatus(m *models.AuthIdentity) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// recordFail 记录一次失败,达到阈值则锁定
|
||||
func recordFail(identityID uint64) error {
|
||||
var m models.AuthIdentity
|
||||
if err := models.Orm.QueryTable(new(models.AuthIdentity)).Filter("id", identityID).One(&m); err != nil {
|
||||
@@ -226,7 +207,6 @@ func recordFail(identityID uint64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// resetFail 登录成功后重置失败计数与锁定
|
||||
func resetFail(identityID uint64) error {
|
||||
_, err := models.Orm.QueryTable(new(models.AuthIdentity)).
|
||||
Filter("id", identityID).
|
||||
@@ -239,7 +219,6 @@ func resetFail(identityID uint64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// writeLoginLog 写入统一登录日志(失败不影响主流程)
|
||||
func writeLoginLog(tid uint64, identityID uint64, account, userName, clientID, loginType, amr string, status int8, message, ip, userAgent string) error {
|
||||
log := &models.AuthLoginLog{
|
||||
IdentityID: &identityID,
|
||||
@@ -262,11 +241,9 @@ func writeLoginLog(tid uint64, identityID uint64, account, userName, clientID, l
|
||||
return err
|
||||
}
|
||||
|
||||
// Logout 登出:吊销刷新令牌、会话与访问令牌,并通知其他应用(单点登出)
|
||||
func Logout(accessToken, refreshToken string) error {
|
||||
err := RevokeTokenPair(refreshToken, accessToken, models.RevokeReasonLogout)
|
||||
|
||||
// 单点登出:通知该用户在其他应用的会话(如后台登出后 APP 同步下线)
|
||||
identityID := uint64(0)
|
||||
if claims, e := jwtutil.ParseTokenRaw(accessToken); e == nil && claims.UserID > 0 {
|
||||
identityID = uint64(claims.UserID)
|
||||
@@ -282,7 +259,6 @@ func Logout(accessToken, refreshToken string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// findRefreshToken 按明文查找刷新令牌记录
|
||||
func findRefreshToken(plain string) (*models.AuthRefreshToken, error) {
|
||||
var rt models.AuthRefreshToken
|
||||
if err := models.Orm.QueryTable(new(models.AuthRefreshToken)).
|
||||
|
||||
@@ -14,10 +14,8 @@ import (
|
||||
"server/pkg/jwtutil"
|
||||
)
|
||||
|
||||
// BackchannelLogoutEvent OIDC 标准登出事件声明
|
||||
const BackchannelLogoutEvent = "http://schemas.openid.net/event/backchannel-logout"
|
||||
|
||||
// logoutTarget 需要收到登出通知的应用
|
||||
type logoutTarget struct {
|
||||
ClientID string
|
||||
Endpoint string
|
||||
@@ -25,13 +23,6 @@ type logoutTarget struct {
|
||||
Identity uint64
|
||||
}
|
||||
|
||||
// NotifyBackchannelLogout 单点登出:通知该用户已登录的所有应用。
|
||||
//
|
||||
// 流程:查库收集目标应用(同步)→ 异步逐个 POST logout_token。
|
||||
// 各应用收到后应清除本地会话,否则用户在这边登出了,其他应用仍显示已登录。
|
||||
//
|
||||
// 注意:查库必须在请求上下文内同步完成(beego 全局 Ormer 不适合跨 goroutine 使用),
|
||||
// 异步部分只做 HTTP 通知,不再触碰数据库。
|
||||
func NotifyBackchannelLogout(identityID uint64) {
|
||||
targets, err := collectLogoutTargets(identityID)
|
||||
if err != nil || len(targets) == 0 {
|
||||
@@ -46,7 +37,6 @@ func NotifyBackchannelLogout(identityID uint64) {
|
||||
}()
|
||||
}
|
||||
|
||||
// collectLogoutTargets 收集该用户当前活跃会话涉及的应用(按 client_id 去重)
|
||||
func collectLogoutTargets(identityID uint64) ([]logoutTarget, error) {
|
||||
var sessions []models.AuthSession
|
||||
if _, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -81,7 +71,6 @@ func collectLogoutTargets(identityID uint64) ([]logoutTarget, error) {
|
||||
return targets, nil
|
||||
}
|
||||
|
||||
// sendLogoutToken 按 OIDC Back-Channel Logout 规范发送 logout_token
|
||||
func sendLogoutToken(t logoutTarget) error {
|
||||
token, err := jwtutil.SignToken(jwtutil.TokenOptions{
|
||||
Alg: jwtutil.AlgRS256,
|
||||
|
||||
@@ -8,20 +8,17 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// 默认会话配置(租户未配置 yz_auth_tenant_auth_config 时使用)
|
||||
const (
|
||||
DefaultSessionTTL = 7200 // 会话有效期(秒)
|
||||
DefaultMaxSession = 1 // 默认 1 号 1 机
|
||||
DefaultSessionTTL = 7200
|
||||
DefaultMaxSession = 1
|
||||
)
|
||||
|
||||
// TenantSessionPolicy 租户会话策略
|
||||
type TenantSessionPolicy struct {
|
||||
SessionTTL int
|
||||
MaxSession int
|
||||
KickStrategy int8
|
||||
}
|
||||
|
||||
// GetTenantSessionPolicy 读取租户登录策略,未配置时返回默认值
|
||||
func GetTenantSessionPolicy(tid uint64) TenantSessionPolicy {
|
||||
policy := TenantSessionPolicy{
|
||||
SessionTTL: DefaultSessionTTL,
|
||||
@@ -45,7 +42,6 @@ func GetTenantSessionPolicy(tid uint64) TenantSessionPolicy {
|
||||
return policy
|
||||
}
|
||||
|
||||
// SessionInfo 创建会话的入参
|
||||
type SessionInfo struct {
|
||||
IdentityID uint64
|
||||
Tid uint64
|
||||
@@ -58,15 +54,9 @@ type SessionInfo struct {
|
||||
Amr string
|
||||
}
|
||||
|
||||
// CreateSession 创建会话并执行并发控制。
|
||||
//
|
||||
// 并发策略(租户可配):
|
||||
// - KickStrategyKickOld(默认):超出上限时踢掉最旧的会话(1号1机)
|
||||
// - KickStrategyReject:超出上限时拒绝新登录
|
||||
func CreateSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
policy := GetTenantSessionPolicy(info.Tid)
|
||||
|
||||
// 已占用的活跃会话
|
||||
var actives []models.AuthSession
|
||||
if _, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
Filter("identity_id", info.IdentityID).
|
||||
@@ -75,7 +65,6 @@ func CreateSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
All(&actives); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 过期会话先作废,不计入占用
|
||||
now := time.Now()
|
||||
valid := make([]models.AuthSession, 0, len(actives))
|
||||
for _, s := range actives {
|
||||
@@ -90,7 +79,6 @@ func CreateSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
if policy.KickStrategy == models.KickStrategyReject {
|
||||
return nil, ErrSessionLimitExceeded
|
||||
}
|
||||
// 踢掉最旧的,直到腾出名额
|
||||
kick := len(valid) - policy.MaxSession + 1
|
||||
for i := 0; i < kick && i < len(valid); i++ {
|
||||
_ = RevokeSession(valid[i].Sid, models.RevokeReasonKicked)
|
||||
@@ -133,14 +121,6 @@ func CreateSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// ReuseSession 授权码换令牌时复用登录阶段已经建立的会话。
|
||||
//
|
||||
// authorize 阶段已经用 yz_sid Cookie 校验过登录态,换码只是给这个已登录会话
|
||||
// 签发令牌,不应再 CreateSession:默认「1 号 1 机」策略会把刚登录的会话踢成
|
||||
// revoked,而浏览器 Cookie 里仍是旧 sid,之后任何一次回到认证中心都会被判定
|
||||
// 未登录并重新显示登录页(表现为「登录成功后又跳回登录界面」)。
|
||||
//
|
||||
// 找不到有效会话(过期、被下线等)时才回退到新建会话。
|
||||
func ReuseSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
var list []models.AuthSession
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -156,8 +136,6 @@ func ReuseSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
if !list[i].ExpiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
// 优先复用同一应用的登录会话;同一浏览器会话被多个应用共享时,
|
||||
// client_id 可能为空(直接访问登录页),此时复用最近的有效会话。
|
||||
if list[i].ClientID == info.ClientID {
|
||||
_ = TouchSession(list[i].Sid)
|
||||
return &list[i], nil
|
||||
@@ -174,7 +152,6 @@ func ReuseSession(info SessionInfo) (*models.AuthSession, error) {
|
||||
return CreateSession(info)
|
||||
}
|
||||
|
||||
// GetSession 查询有效会话(已吊销或已过期返回错误)
|
||||
func GetSession(sid string) (*models.AuthSession, error) {
|
||||
var s models.AuthSession
|
||||
if err := models.Orm.QueryTable(new(models.AuthSession)).Filter("sid", sid).One(&s); err != nil {
|
||||
@@ -189,7 +166,6 @@ func GetSession(sid string) (*models.AuthSession, error) {
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// TouchSession 更新会话最近访问时间(建议每 5~10 分钟一次,避免高频写库)
|
||||
func TouchSession(sid string) error {
|
||||
last := time.Now()
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -198,7 +174,6 @@ func TouchSession(sid string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// SwitchSessionTenant 切换当前会话所属企业(免密切换)
|
||||
func SwitchSessionTenant(sid string, tid uint64) error {
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
Filter("sid", sid).
|
||||
@@ -206,7 +181,6 @@ func SwitchSessionTenant(sid string, tid uint64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// RevokeSession 吊销单个会话
|
||||
func RevokeSession(sid, reason string) error {
|
||||
now := time.Now()
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -219,7 +193,6 @@ func RevokeSession(sid, reason string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// RevokeAllSessions 吊销该身份的全部会话(改密、管理员下线等场景)
|
||||
func RevokeAllSessions(identityID uint64, reason string) error {
|
||||
now := time.Now()
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -233,7 +206,6 @@ func RevokeAllSessions(identityID uint64, reason string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ListActiveSessions 在线设备列表
|
||||
func ListActiveSessions(identityID uint64) ([]models.AuthSession, error) {
|
||||
var list []models.AuthSession
|
||||
_, err := models.Orm.QueryTable(new(models.AuthSession)).
|
||||
@@ -244,7 +216,6 @@ func ListActiveSessions(identityID uint64) ([]models.AuthSession, error) {
|
||||
return list, err
|
||||
}
|
||||
|
||||
// randomToken 生成 URL 安全的随机串(用于 sid / refresh token 明文)
|
||||
func randomToken(n int) (string, error) {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
|
||||
@@ -10,44 +10,26 @@ import (
|
||||
"server/pkg/passwordutil"
|
||||
)
|
||||
|
||||
// SyncTenantUserInput 老表 → 认证中心同步入参
|
||||
type SyncTenantUserInput struct {
|
||||
Tid uint64
|
||||
Account string // 企业内账号
|
||||
Account string
|
||||
Name string
|
||||
Phone string
|
||||
Email string
|
||||
// PasswordHash 已哈希的密码;为空表示不修改密码。
|
||||
// 注意:身份已存在时,只有 UpdatePassword=true 才会生效(改密场景),
|
||||
// 否则保持不动 —— 避免 B 企业建同名用户时把 A 企业的密码静默覆盖掉。
|
||||
PasswordHash string
|
||||
GroupID uint64
|
||||
OrgID uint64
|
||||
Status int8
|
||||
IsDefault int8
|
||||
|
||||
// UpdatePassword 身份已存在时是否允许更新密码(仅改密场景传 true)
|
||||
UpdatePassword bool
|
||||
}
|
||||
|
||||
// SyncTenantUser 把租户用户同步到统一认证中心(幂等,可重复调用)。
|
||||
//
|
||||
// 归并规则与迁移脚本一致:手机号 > 邮箱 > 企业内账号。
|
||||
// - 身份不存在 → 创建;已存在 → 更新手机/邮箱/昵称/状态
|
||||
// - 绑定不存在 → 创建;已存在 → 更新账号/姓名/部门/角色/状态
|
||||
//
|
||||
// 注意:密码属于身份层(一人一份),因此在任一企业修改密码,
|
||||
// 该用户在其他企业的登录密码会同步变化——这是统一认证的预期行为。
|
||||
func SyncTenantUser(in SyncTenantUserInput) error {
|
||||
_, err := SyncTenantUserAndGetIdentity(in)
|
||||
return err
|
||||
}
|
||||
|
||||
// SyncTenantUserAndGetIdentity 同 SyncTenantUser,但额外返回认证中心身份ID。
|
||||
//
|
||||
// 用途:新增租户用户时先把身份建出来,再用 identity_id 作为
|
||||
// yz_system_tenant_user.uid——业务表(文件/客户/合同…)已在 uid 全量迁移中
|
||||
// 统一成 identity_id,老表 uid 只有与它一致,业务侧才不需要任何换算。
|
||||
func SyncTenantUserAndGetIdentity(in SyncTenantUserInput) (uint64, error) {
|
||||
identity, err := findOrCreateIdentity(in)
|
||||
if err != nil {
|
||||
@@ -59,12 +41,10 @@ func SyncTenantUserAndGetIdentity(in SyncTenantUserInput) (uint64, error) {
|
||||
return identity.ID, nil
|
||||
}
|
||||
|
||||
// RemoveTenantUser 删除该用户在指定企业的绑定(保留身份本身,
|
||||
// 因为该身份可能还绑定着其他企业)。
|
||||
func RemoveTenantUser(tid uint64, account, phone, email string) error {
|
||||
identity := findIdentityByKey(account, phone, email)
|
||||
if identity == nil {
|
||||
return nil // 认证中心无此身份,无需处理
|
||||
return nil
|
||||
}
|
||||
_, err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
Filter("tid", tid).
|
||||
@@ -73,10 +53,8 @@ func RemoveTenantUser(tid uint64, account, phone, email string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// findOrCreateIdentity 按归并键查找身份,不存在则创建
|
||||
func findOrCreateIdentity(in SyncTenantUserInput) (*models.AuthIdentity, error) {
|
||||
if m := findIdentityByKey(in.Account, in.Phone, in.Email); m != nil {
|
||||
// 补全手机/邮箱/昵称;密码仅在显式授权(改密场景)时更新
|
||||
update := map[string]interface{}{}
|
||||
if in.Phone != "" {
|
||||
update["mobile"] = in.Phone
|
||||
@@ -99,7 +77,6 @@ func findOrCreateIdentity(in SyncTenantUserInput) (*models.AuthIdentity, error)
|
||||
Filter("id", m.ID).
|
||||
Update(update)
|
||||
}
|
||||
// 重新读取,返回最新值
|
||||
_ = models.Orm.QueryTable(new(models.AuthIdentity)).Filter("id", m.ID).One(m)
|
||||
return m, nil
|
||||
}
|
||||
@@ -133,7 +110,6 @@ func findOrCreateIdentity(in SyncTenantUserInput) (*models.AuthIdentity, error)
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// findIdentityByKey 按 手机 > 邮箱 > 账号 查找身份
|
||||
func findIdentityByKey(account, phone, email string) *models.AuthIdentity {
|
||||
base := models.Orm.QueryTable(new(models.AuthIdentity)).Filter("delete_time__isnull", true)
|
||||
|
||||
@@ -149,7 +125,6 @@ func findIdentityByKey(account, phone, email string) *models.AuthIdentity {
|
||||
return m
|
||||
}
|
||||
}
|
||||
// 企业内账号:先找绑定关系再回查身份
|
||||
if v := strings.TrimSpace(account); v != "" {
|
||||
var bind models.AuthTenantUser
|
||||
if err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
@@ -167,7 +142,6 @@ func findIdentityByKey(account, phone, email string) *models.AuthIdentity {
|
||||
return nil
|
||||
}
|
||||
|
||||
// upsertTenantBinding 创建或更新身份-企业绑定
|
||||
func upsertTenantBinding(identity *models.AuthIdentity, in SyncTenantUserInput) error {
|
||||
var existed models.AuthTenantUser
|
||||
err := models.Orm.QueryTable(new(models.AuthTenantUser)).
|
||||
@@ -176,7 +150,6 @@ func upsertTenantBinding(identity *models.AuthIdentity, in SyncTenantUserInput)
|
||||
One(&existed)
|
||||
|
||||
if err != nil {
|
||||
// 新建绑定
|
||||
item := &models.AuthTenantUser{
|
||||
Tid: in.Tid,
|
||||
IdentityID: identity.ID,
|
||||
@@ -238,15 +211,11 @@ func upsertTenantBinding(identity *models.AuthIdentity, in SyncTenantUserInput)
|
||||
return err
|
||||
}
|
||||
|
||||
// LocateIdentityByKey 按归并键(手机 > 邮箱 > 账号)查找已有身份。
|
||||
// 第二个返回值表示是否命中。供「新增租户用户」流程判断:
|
||||
// 命中则要求先验证该身份的登录密码,验证通过后只建企业绑定。
|
||||
func LocateIdentityByKey(account, phone, email string) (*models.AuthIdentity, bool) {
|
||||
m := findIdentityByKey(account, phone, email)
|
||||
return m, m != nil
|
||||
}
|
||||
|
||||
// GetIdentityByID 按主键读取认证身份
|
||||
func GetIdentityByID(id uint64) (*models.AuthIdentity, error) {
|
||||
var m models.AuthIdentity
|
||||
if err := models.Orm.QueryTable(new(models.AuthIdentity)).Filter("id", id).One(&m); err != nil {
|
||||
@@ -255,7 +224,6 @@ func GetIdentityByID(id uint64) (*models.AuthIdentity, error) {
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// VerifyIdentityPassword 校验身份的登录密码(兼容 legacy 哈希算法)
|
||||
func VerifyIdentityPassword(identity *models.AuthIdentity, plain string) bool {
|
||||
if identity == nil || identity.PasswordHash == nil || *identity.PasswordHash == "" {
|
||||
return false
|
||||
@@ -263,8 +231,6 @@ func VerifyIdentityPassword(identity *models.AuthIdentity, plain string) bool {
|
||||
return passwordutil.Verify(*identity.PasswordHash, plain)
|
||||
}
|
||||
|
||||
// BindIdentityToTenant 把已有身份绑定到企业(只写绑定层,不改身份资料与密码)。
|
||||
// 供「验证密码后绑定到新企业」流程使用,绑定层的企业内账号/姓名/联系方式独立维护。
|
||||
func BindIdentityToTenant(identity *models.AuthIdentity, in SyncTenantUserInput) error {
|
||||
if identity == nil {
|
||||
return errors.New("身份不存在")
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"server/pkg/jwtutil"
|
||||
)
|
||||
|
||||
// 认证中心错误定义
|
||||
var (
|
||||
ErrSessionLimitExceeded = errors.New("同时在线设备数已达上限")
|
||||
ErrSessionRevoked = errors.New("会话已失效,请重新登录")
|
||||
@@ -23,7 +22,6 @@ var (
|
||||
ErrRefreshTokenReused = errors.New("刷新令牌已被使用,疑似重放攻击,已吊销该登录")
|
||||
)
|
||||
|
||||
// TokenPair 签发的令牌对
|
||||
type TokenPair struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
@@ -32,7 +30,6 @@ type TokenPair struct {
|
||||
Sid string `json:"sid"`
|
||||
}
|
||||
|
||||
// TokenIssue 签发令牌的入参
|
||||
type TokenIssue struct {
|
||||
IdentityID uint64
|
||||
Tid uint64
|
||||
@@ -41,16 +38,10 @@ type TokenIssue struct {
|
||||
Username string
|
||||
UserType string
|
||||
Amr string
|
||||
AccessTTL int // 秒
|
||||
RefreshTTL int // 秒
|
||||
AccessTTL int
|
||||
RefreshTTL int
|
||||
}
|
||||
|
||||
// IssueTokens 签发访问令牌与刷新令牌。
|
||||
// 刷新令牌明文只在本次返回,库中仅存哈希。
|
||||
//
|
||||
// 令牌中的 user_id 为认证中心 identity_id(yz_auth_identity.id)。
|
||||
// 业务表(文件/客户/合同/日程等)中的 uid 已由 scripts/uidmigrate 全量迁移为
|
||||
// 同一套 ID,因此无需任何兼容换算。
|
||||
func IssueTokens(opt TokenIssue) (*TokenPair, error) {
|
||||
accessTTL := opt.AccessTTL
|
||||
if accessTTL <= 0 {
|
||||
@@ -61,12 +52,8 @@ func IssueTokens(opt TokenIssue) (*TokenPair, error) {
|
||||
refreshTTL = 2592000
|
||||
}
|
||||
|
||||
// 全量迁移后,令牌中的 user_id 统一为认证中心的 identity_id
|
||||
userID := int(opt.IdentityID)
|
||||
|
||||
// userType 需与现有业务接口的判定保持一致:
|
||||
// 后端接口普遍要求 user_type 为 "backend"(租户后台)或 "app"(移动端),
|
||||
// 若签发 "tenant" 会被判为无权访问。这里按应用编码给出默认值。
|
||||
userType := opt.UserType
|
||||
if userType == "" {
|
||||
userType = "backend"
|
||||
@@ -122,10 +109,6 @@ func IssueTokens(opt TokenIssue) (*TokenPair, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RefreshTokens 用刷新令牌换取新的令牌对(轮换 + 重放检测)。
|
||||
//
|
||||
// 安全要点:检测到已使用的刷新令牌再次出现时,判定为重放,
|
||||
// 吊销整个 family(该次登录的全部令牌)。
|
||||
func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
h := hashToken(plain)
|
||||
var rt models.AuthRefreshToken
|
||||
@@ -139,7 +122,6 @@ func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
return nil, ErrRefreshTokenInvalid
|
||||
}
|
||||
if rt.Used != 0 {
|
||||
// 重放:吊销同族全部令牌与该会话
|
||||
_, _ = models.Orm.QueryTable(new(models.AuthRefreshToken)).
|
||||
Filter("family_id", rt.FamilyID).
|
||||
Update(map[string]interface{}{"revoked": 1})
|
||||
@@ -147,12 +129,10 @@ func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
return nil, ErrRefreshTokenReused
|
||||
}
|
||||
|
||||
// 标记已用(保留 Row 以便审计)
|
||||
_, _ = models.Orm.QueryTable(new(models.AuthRefreshToken)).
|
||||
Filter("id", rt.ID).
|
||||
Update(map[string]interface{}{"used": 1})
|
||||
|
||||
// 会话校验:已吊销/过期则拒绝续期
|
||||
s, err := GetSession(rt.Sid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -161,7 +141,7 @@ func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
|
||||
pair, err := IssueTokens(TokenIssue{
|
||||
IdentityID: rt.IdentityID,
|
||||
Tid: s.Tid, // 以会话当前企业为准(支持切换企业后刷新)
|
||||
Tid: s.Tid,
|
||||
ClientID: rt.ClientID,
|
||||
Sid: rt.Sid,
|
||||
Amr: derefStr(s.Amr),
|
||||
@@ -169,7 +149,6 @@ func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 新令牌继承同一 family,便于后续溯源与整族吊销
|
||||
if _, err := models.Orm.QueryTable(new(models.AuthRefreshToken)).
|
||||
Filter("token_hash", hashToken(pair.RefreshToken)).
|
||||
Update(map[string]interface{}{"family_id": rt.FamilyID, "rotated_from": h}); err != nil {
|
||||
@@ -178,11 +157,6 @@ func RefreshTokens(plain, clientID string) (*TokenPair, error) {
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
// FindLegacyUID 通过「身份 + 企业」在老表 yz_system_tenant_user 中找到对应 uid。
|
||||
//
|
||||
// 双轨期(老登录与统一认证并行)下业务接口仍以老 uid 识别用户,
|
||||
// 因此签发令牌、返回用户信息时都要换算回老 uid。
|
||||
// 匹配顺序:账号 → 手机号 → 邮箱;都匹配不到返回 0。
|
||||
func FindLegacyUID(tid, identityID uint64) uint64 {
|
||||
if tid == 0 || identityID == 0 {
|
||||
return 0
|
||||
@@ -218,7 +192,6 @@ func FindLegacyUID(tid, identityID uint64) uint64 {
|
||||
return match("email", bind.Email)
|
||||
}
|
||||
|
||||
// RevokeTokenPair 登出:吊销刷新令牌、会话,并把 access token 的 jti 加入黑名单。
|
||||
func RevokeTokenPair(plain, accessToken, reason string) error {
|
||||
if plain != "" {
|
||||
_, _ = models.Orm.QueryTable(new(models.AuthRefreshToken)).
|
||||
@@ -236,7 +209,6 @@ func RevokeTokenPair(plain, accessToken, reason string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Blacklist 把 jti 加入吊销表
|
||||
func Blacklist(jti, sid, reason string, expiresAt time.Time) error {
|
||||
if jti == "" {
|
||||
return nil
|
||||
@@ -255,7 +227,6 @@ func Blacklist(jti, sid, reason string, expiresAt time.Time) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// IsBlacklisted 判断 jti 是否已被吊销
|
||||
func IsBlacklisted(jti string) bool {
|
||||
if jti == "" {
|
||||
return false
|
||||
|
||||
Reference in new issue
Block a user