feat(security): 支持按客户端独立设置专属授权码并重构紧凑单屏无滚动条布局
This commit is contained in:
1 parent
bc5e369487
commit
f047a61f87
13 files changed
+1165
-376
No files matched your search
@@ -0,0 +1,111 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
// ListClientCredentials 返回当前用户的客户端授权码列表
|
||||
func ListClientCredentials(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, err := service.ListClientCredentials(ctx.UserID)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "读取客户端授权码失败")
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(items).FPrint(w)
|
||||
}
|
||||
|
||||
// CreateClientCredential 为当前用户创建客户端授权码
|
||||
func CreateClientCredential(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ClientName string `json:"client_name"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.ClientName) == "" {
|
||||
writeSecurityError(w, response.ParamsError, "请输入客户端名称")
|
||||
return
|
||||
}
|
||||
code, item, err := service.CreateClientCredential(ctx.UserID, input.ClientName)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, err.Error())
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"code": code, "client": item}).FPrint(w)
|
||||
}
|
||||
|
||||
// RegenerateClientCredential 重新生成客户端专属授权码
|
||||
func RegenerateClientCredential(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ClientID int `json:"client_id"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.ClientID <= 0 {
|
||||
writeSecurityError(w, response.ParamsError, "客户端标识无效")
|
||||
return
|
||||
}
|
||||
code, err := service.RegenerateClientCredential(ctx.UserID, input.ClientID)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, err.Error())
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"code": code, "client_id": input.ClientID}).FPrint(w)
|
||||
}
|
||||
|
||||
// RevokeClientCredential 撤销客户端授权码
|
||||
func RevokeClientCredential(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ClientID int `json:"client_id"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.ClientID <= 0 {
|
||||
writeSecurityError(w, response.ParamsError, "客户端标识无效")
|
||||
return
|
||||
}
|
||||
if err := service.RevokeClientCredential(ctx.UserID, input.ClientID); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, err.Error())
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"client_id": input.ClientID, "revoked": true}).FPrint(w)
|
||||
}
|
||||
|
||||
// RevealClientCredentials 在安全身份验证成功后解密返回所有客户端授权码
|
||||
func RevealClientCredentials(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.Password) == "" {
|
||||
writeSecurityError(w, response.ParamsError, "请输入当前账号密码进行安全验证")
|
||||
return
|
||||
}
|
||||
if _, err := auth.AuthenticateUserByID(ctx.UserID, input.Password); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "密码验证失败")
|
||||
return
|
||||
}
|
||||
codes, err := service.RevealClientCredentials(ctx.UserID)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ServerError, "解密授权码失败")
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(codes).FPrint(w)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package migration
|
||||
|
||||
func clientCredentialStatements() map[Dialect][]string {
|
||||
return map[Dialect][]string{
|
||||
DialectSQLite: {
|
||||
`CREATE TABLE IF NOT EXISTS "client_credential" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "client_name" TEXT NOT NULL, "code_hash" TEXT NOT NULL DEFAULT '', "code_ciphertext" TEXT NULL, "code_version" INTEGER NOT NULL DEFAULT 1, "created_at" DATETIME NOT NULL, "updated_at" DATETIME NOT NULL, "last_used_at" DATETIME NULL, "revoked_at" DATETIME NULL, UNIQUE("user_id", "client_name"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_client_credential_user_id" ON "client_credential"("user_id")`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_client_credential_revoked" ON "client_credential"("revoked_at")`,
|
||||
},
|
||||
DialectMySQL: {
|
||||
"CREATE TABLE IF NOT EXISTS `client_credential` (`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `user_id` BIGINT NOT NULL, `client_name` VARCHAR(64) NOT NULL, `code_hash` VARCHAR(255) NOT NULL DEFAULT '', `code_ciphertext` VARCHAR(512) NULL, `code_version` INT NOT NULL DEFAULT 1, `created_at` DATETIME(6) NOT NULL, `updated_at` DATETIME(6) NOT NULL, `last_used_at` DATETIME(6) NULL, `revoked_at` DATETIME(6) NULL, UNIQUE KEY `uq_client_credential_user_client` (`user_id`, `client_name`), KEY `idx_client_credential_user_id` (`user_id`), KEY `idx_client_credential_revoked` (`revoked_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
|
||||
},
|
||||
DialectPostgres: {
|
||||
`CREATE TABLE IF NOT EXISTS "client_credential" ("id" BIGSERIAL PRIMARY KEY, "user_id" BIGINT NOT NULL, "client_name" VARCHAR(64) NOT NULL, "code_hash" VARCHAR(255) NOT NULL DEFAULT '', "code_ciphertext" VARCHAR(512) NULL, "code_version" INTEGER NOT NULL DEFAULT 1, "created_at" TIMESTAMPTZ NOT NULL, "updated_at" TIMESTAMPTZ NOT NULL, "last_used_at" TIMESTAMPTZ NULL, "revoked_at" TIMESTAMPTZ NULL, UNIQUE("user_id", "client_name"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_client_credential_user_id" ON "client_credential"("user_id")`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_client_credential_revoked" ON "client_credential"("revoked_at")`,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package migration
|
||||
package migration
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
@@ -31,6 +31,7 @@ func DefaultMigrations() []Migration {
|
||||
DefineForDialects(19, "create_user_contacts_and_trusted_senders", userContactStatements()),
|
||||
DefineCustom(20, "expand_protocol_credential_ciphertext", "expand_protocol_credential_ciphertext_v1", applyProtocolCredentialCiphertextSchema),
|
||||
DefineCustom(21, "expand_trusted_sender_blacklist", "expand_trusted_sender_blacklist_v1", applyTrustedSenderBlacklistSchema),
|
||||
DefineForDialects(22, "create_client_credentials", clientCredentialStatements()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -295,6 +295,7 @@ func TestDefaultMigrationChecksumsAreImmutable(t *testing.T) {
|
||||
19: "f24b94ca9e4c25b7973f6c15fcaddccc7f02bcf7886c0a4995d2f7b79f4a3a16",
|
||||
20: "e0bc01f4c2df742bc23c519c2a399cc1c3f341565dbed014509a8c63d68bf725",
|
||||
21: "ac1a0b3be90128c0e0512d2cec858f8cd7e70abc5ff4734d7113b9674f08dbb0",
|
||||
22: "1047cb22f5a32c8a09ba4ccedff8713a5225c14fdb98357db86a6e0723c30d8b",
|
||||
}
|
||||
migrations := DefaultMigrations()
|
||||
if len(migrations) != len(expected) {
|
||||
@@ -355,3 +356,5 @@ func TestDefaultMigrationsResumePublishedVersionOne(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,11 @@ func registerV1Routes(mux *http.ServeMux) {
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/protocols/generate", "/api/security/credentials/protocols/generate", http.MethodPost, 16<<10, controllers.GenerateProtocolCredential)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/protocols/revoke", "/api/security/credentials/protocols/revoke", http.MethodPost, 16<<10, controllers.RevokeProtocolCredential)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/protocols/reveal", "/api/security/credentials/protocols/reveal", http.MethodPost, 16<<10, controllers.RevealProtocolCredentials)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/clients", "/api/security/credentials/clients", http.MethodGet, 0, controllers.ListClientCredentials)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/clients/create", "/api/security/credentials/clients/create", http.MethodPost, 16<<10, controllers.CreateClientCredential)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/clients/regenerate", "/api/security/credentials/clients/regenerate", http.MethodPost, 16<<10, controllers.RegenerateClientCredential)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/clients/revoke", "/api/security/credentials/clients/revoke", http.MethodPost, 16<<10, controllers.RevokeClientCredential)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/credentials/clients/reveal", "/api/security/credentials/clients/reveal", http.MethodPost, 16<<10, controllers.RevealClientCredentials)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/external-email/list", "/api/security/external-email/list", http.MethodGet, 0, controllers.ListExternalEmails)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/external-email/bind", "/api/security/external-email/bind", http.MethodPost, 16<<10, controllers.BindExternalEmail)
|
||||
registerV1MethodRoute(mux, "/api/v1/security/external-email/verify", "/api/security/external-email/verify", http.MethodPost, 16<<10, controllers.VerifyExternalEmail)
|
||||
|
||||
@@ -72,6 +72,11 @@ func router(mux *http.ServeMux) error {
|
||||
mux.HandleFunc("/api/security/credentials/protocols/generate", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.GenerateProtocolCredential))))
|
||||
mux.HandleFunc("/api/security/credentials/protocols/revoke", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.RevokeProtocolCredential))))
|
||||
mux.HandleFunc("/api/security/credentials/protocols/reveal", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.RevealProtocolCredentials))))
|
||||
mux.HandleFunc("/api/security/credentials/clients", onlyMethod(http.MethodGet, contextIterceptor(controllers.ListClientCredentials)))
|
||||
mux.HandleFunc("/api/security/credentials/clients/create", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.CreateClientCredential))))
|
||||
mux.HandleFunc("/api/security/credentials/clients/regenerate", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.RegenerateClientCredential))))
|
||||
mux.HandleFunc("/api/security/credentials/clients/revoke", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.RevokeClientCredential))))
|
||||
mux.HandleFunc("/api/security/credentials/clients/reveal", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.RevealClientCredentials))))
|
||||
mux.HandleFunc("/api/security/external-email/list", onlyMethod(http.MethodGet, contextIterceptor(controllers.ListExternalEmails)))
|
||||
mux.HandleFunc("/api/security/external-email/bind", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.BindExternalEmail))))
|
||||
mux.HandleFunc("/api/security/external-email/verify", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(controllers.VerifyExternalEmail))))
|
||||
|
||||
@@ -41,6 +41,10 @@ var loggedOperations = map[string]string{
|
||||
"/api/security/credentials/protocols/generate": "生成邮件客户端安全码",
|
||||
"/api/security/credentials/protocols/revoke": "撤销邮件客户端安全码",
|
||||
"/api/security/credentials/protocols/reveal": "查看邮件客户端安全码",
|
||||
"/api/security/credentials/clients/create": "创建客户端专属授权码",
|
||||
"/api/security/credentials/clients/regenerate": "重新生成客户端授权码",
|
||||
"/api/security/credentials/clients/revoke": "撤销客户端专属授权码",
|
||||
"/api/security/credentials/clients/reveal": "查看客户端专属授权码",
|
||||
"/api/security/external-email/bind": "申请绑定外部邮箱",
|
||||
"/api/security/external-email/verify": "验证外部邮箱",
|
||||
"/api/security/external-email/change": "申请修改外部邮箱",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// ClientCredential 保存用户为特定客户端(如 iPhone、Foxmail 等)创建的专属授权码
|
||||
type ClientCredential struct {
|
||||
ID int `xorm:"id bigint unsigned not null pk autoincr" json:"id"`
|
||||
UserID int `xorm:"user_id bigint not null index" json:"user_id"`
|
||||
ClientName string `xorm:"client_name varchar(64) notnull" json:"client_name"`
|
||||
CodeHash string `xorm:"code_hash varchar(255) notnull" json:"-"`
|
||||
CodeCiphertext string `xorm:"code_ciphertext varchar(512) null" json:"-"`
|
||||
CodeVersion int `xorm:"code_version int notnull default(1)" json:"code_version"`
|
||||
CreatedAt time.Time `xorm:"created_at datetime created notnull" json:"created_at"`
|
||||
UpdatedAt time.Time `xorm:"updated_at datetime updated notnull" json:"updated_at"`
|
||||
LastUsedAt *time.Time `xorm:"last_used_at datetime null" json:"last_used_at,omitempty"`
|
||||
RevokedAt *time.Time `xorm:"revoked_at datetime null index" json:"revoked_at,omitempty"`
|
||||
}
|
||||
|
||||
func (ClientCredential) TableName() string { return "client_credential" }
|
||||
@@ -1,4 +1,4 @@
|
||||
package auth
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
@@ -66,16 +66,30 @@ func AuthenticateProtocol(protocol string, remoteAddress string, account string,
|
||||
if protocolErr != nil || db.Instance == nil {
|
||||
return fail()
|
||||
}
|
||||
|
||||
identity, err := ResolveIdentifier(account)
|
||||
if err != nil || identity.Kind != IdentifierEmail || identity.UserID <= 0 {
|
||||
if err != nil {
|
||||
return fail()
|
||||
}
|
||||
userID := identity.UserID
|
||||
if identity.Kind == IdentifierAccount {
|
||||
var u models.User
|
||||
has, err := db.Instance.Where("account = ? AND disabled = 0", identity.Account).Get(&u)
|
||||
if err != nil || !has || u.ID <= 0 {
|
||||
return fail()
|
||||
}
|
||||
userID = u.ID
|
||||
}
|
||||
if userID <= 0 {
|
||||
return fail()
|
||||
}
|
||||
|
||||
service, err := credentials.NewService(db.Instance)
|
||||
if err != nil || !service.VerifyProtocolCode(identity.UserID, normalizedProtocol, plain) {
|
||||
if err != nil || !service.VerifyClientOrProtocolCode(userID, normalizedProtocol, plain) {
|
||||
return fail()
|
||||
}
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(identity.UserID).Where("disabled = 0").Get(&user)
|
||||
has, err := db.Instance.ID(userID).Where("disabled = 0").Get(&user)
|
||||
if err != nil || !has || user.ID <= 0 {
|
||||
return fail()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
package credentials
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrClientNameRequired = errors.New("client name is required")
|
||||
ErrClientNotFound = errors.New("client credential not found")
|
||||
)
|
||||
|
||||
// ClientCredentialItem 表示返回给前端的客户端授权码视图
|
||||
type ClientCredentialItem struct {
|
||||
ID int `json:"id"`
|
||||
ClientName string `json:"client_name"`
|
||||
Configured bool `json:"configured"`
|
||||
CanReveal bool `json:"can_reveal"`
|
||||
CodeVersion int `json:"code_version"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
}
|
||||
|
||||
// CleanAuthCode 统一授权码格式:去除短横线、空格并转大写,提升各类客户端容错率
|
||||
func CleanAuthCode(raw string) string {
|
||||
raw = strings.ToUpper(strings.TrimSpace(raw))
|
||||
raw = strings.ReplaceAll(raw, "-", "")
|
||||
raw = strings.ReplaceAll(raw, " ", "")
|
||||
return raw
|
||||
}
|
||||
|
||||
// FormatAuthCode 将清洗后的授权码格式化为 4 字符一组带横线的易读格式
|
||||
func FormatAuthCode(raw string) string {
|
||||
cleaned := CleanAuthCode(raw)
|
||||
if len(cleaned) == 0 {
|
||||
return ""
|
||||
}
|
||||
var groups []string
|
||||
for len(cleaned) > 4 {
|
||||
groups = append(groups, cleaned[:4])
|
||||
cleaned = cleaned[4:]
|
||||
}
|
||||
if len(cleaned) > 0 {
|
||||
groups = append(groups, cleaned)
|
||||
}
|
||||
return strings.Join(groups, "-")
|
||||
}
|
||||
|
||||
// ListClientCredentials 返回指定用户的所有有效(未撤销)客户端授权凭证
|
||||
func (s *Service) ListClientCredentials(userID int) ([]ClientCredentialItem, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if userID <= 0 {
|
||||
return nil, ErrInvalidUser
|
||||
}
|
||||
var items []models.ClientCredential
|
||||
if err := s.engine.Where("user_id = ? AND revoked_at IS NULL", userID).OrderBy("id ASC").Find(&items); err != nil {
|
||||
return nil, fmt.Errorf("load client credentials: %w", err)
|
||||
}
|
||||
result := make([]ClientCredentialItem, 0, len(items))
|
||||
for _, item := range items {
|
||||
result = append(result, ClientCredentialItem{
|
||||
ID: item.ID,
|
||||
ClientName: item.ClientName,
|
||||
Configured: item.CodeHash != "",
|
||||
CanReveal: item.CodeCiphertext != "",
|
||||
CodeVersion: item.CodeVersion,
|
||||
CreatedAt: item.CreatedAt,
|
||||
UpdatedAt: item.UpdatedAt,
|
||||
LastUsedAt: item.LastUsedAt,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// CreateClientCredential 为指定客户端名称创建专属授权码
|
||||
func (s *Service) CreateClientCredential(userID int, clientName string) (string, *ClientCredentialItem, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return "", nil, ErrUnavailable
|
||||
}
|
||||
if userID <= 0 {
|
||||
return "", nil, ErrInvalidUser
|
||||
}
|
||||
clientName = strings.TrimSpace(clientName)
|
||||
if clientName == "" {
|
||||
return "", nil, ErrClientNameRequired
|
||||
}
|
||||
if len([]rune(clientName)) > 32 {
|
||||
return "", nil, errors.New("client name is too long (max 32 chars)")
|
||||
}
|
||||
|
||||
plain, err := newProtocolCode()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
normalizedCode := CleanAuthCode(plain)
|
||||
|
||||
ciphertext := ""
|
||||
if s.vaultRoot != "" {
|
||||
ciphertext, err = credential.Encrypt(s.vaultRoot, plain)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("protect client authorization code: %w", err)
|
||||
}
|
||||
}
|
||||
hash, err := password.Hash(normalizedCode)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("hash client authorization code: %w", err)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
var existing models.ClientCredential
|
||||
has, err := s.engine.Where("user_id = ? AND client_name = ?", userID, clientName).Get(&existing)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("check existing client credential: %w", err)
|
||||
}
|
||||
if has {
|
||||
// 如果此前被撤销,重新启用并更新密钥;如果未被撤销则不允许重名创建
|
||||
if existing.RevokedAt == nil {
|
||||
return "", nil, errors.New("client name already exists")
|
||||
}
|
||||
version := existing.CodeVersion + 1
|
||||
existing.CodeHash = hash
|
||||
existing.CodeCiphertext = ciphertext
|
||||
existing.CodeVersion = version
|
||||
existing.RevokedAt = nil
|
||||
existing.LastUsedAt = nil
|
||||
existing.UpdatedAt = s.now()
|
||||
if _, err := s.engine.ID(existing.ID).Cols("code_hash", "code_ciphertext", "code_version", "revoked_at", "last_used_at", "updated_at").Update(&existing); err != nil {
|
||||
return "", nil, fmt.Errorf("re-activate client credential: %w", err)
|
||||
}
|
||||
item := &ClientCredentialItem{
|
||||
ID: existing.ID,
|
||||
ClientName: existing.ClientName,
|
||||
Configured: true,
|
||||
CanReveal: existing.CodeCiphertext != "",
|
||||
CodeVersion: existing.CodeVersion,
|
||||
CreatedAt: existing.CreatedAt,
|
||||
UpdatedAt: existing.UpdatedAt,
|
||||
}
|
||||
return plain, item, nil
|
||||
}
|
||||
|
||||
record := models.ClientCredential{
|
||||
UserID: userID,
|
||||
ClientName: clientName,
|
||||
CodeHash: hash,
|
||||
CodeCiphertext: ciphertext,
|
||||
CodeVersion: 1,
|
||||
CreatedAt: s.now(),
|
||||
UpdatedAt: s.now(),
|
||||
}
|
||||
if _, err := s.engine.Insert(&record); err != nil {
|
||||
return "", nil, fmt.Errorf("insert client credential: %w", err)
|
||||
}
|
||||
|
||||
item := &ClientCredentialItem{
|
||||
ID: record.ID,
|
||||
ClientName: record.ClientName,
|
||||
Configured: true,
|
||||
CanReveal: record.CodeCiphertext != "",
|
||||
CodeVersion: record.CodeVersion,
|
||||
CreatedAt: record.CreatedAt,
|
||||
UpdatedAt: record.UpdatedAt,
|
||||
}
|
||||
return plain, item, nil
|
||||
}
|
||||
|
||||
// RegenerateClientCredential 重新生成已有客户端专属授权码
|
||||
func (s *Service) RegenerateClientCredential(userID int, clientID int) (string, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
if userID <= 0 || clientID <= 0 {
|
||||
return "", ErrInvalidUser
|
||||
}
|
||||
|
||||
plain, err := newProtocolCode()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
normalizedCode := CleanAuthCode(plain)
|
||||
|
||||
ciphertext := ""
|
||||
if s.vaultRoot != "" {
|
||||
ciphertext, err = credential.Encrypt(s.vaultRoot, plain)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("protect client authorization code: %w", err)
|
||||
}
|
||||
}
|
||||
hash, err := password.Hash(normalizedCode)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hash client authorization code: %w", err)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
var existing models.ClientCredential
|
||||
has, err := s.engine.Where("id = ? AND user_id = ? AND revoked_at IS NULL", clientID, userID).Get(&existing)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load client credential: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return "", ErrClientNotFound
|
||||
}
|
||||
|
||||
version := existing.CodeVersion + 1
|
||||
existing.CodeHash = hash
|
||||
existing.CodeCiphertext = ciphertext
|
||||
existing.CodeVersion = version
|
||||
existing.LastUsedAt = nil
|
||||
existing.UpdatedAt = s.now()
|
||||
|
||||
if _, err := s.engine.ID(existing.ID).Cols("code_hash", "code_ciphertext", "code_version", "last_used_at", "updated_at").Update(&existing); err != nil {
|
||||
return "", fmt.Errorf("update client authorization code: %w", err)
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
// RevokeClientCredential 撤销指定客户端授权码
|
||||
func (s *Service) RevokeClientCredential(userID int, clientID int) error {
|
||||
if s == nil || s.engine == nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if userID <= 0 || clientID <= 0 {
|
||||
return ErrInvalidUser
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := s.now()
|
||||
affected, err := s.engine.Where("id = ? AND user_id = ? AND revoked_at IS NULL", clientID, userID).
|
||||
Cols("revoked_at", "code_hash", "code_ciphertext", "updated_at").
|
||||
Update(&models.ClientCredential{RevokedAt: &now, CodeHash: "", CodeCiphertext: ""})
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke client credential: %w", err)
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrClientNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevealClientCredentials 解密当前用户所有有效客户端授权码明文,仅在密码验证后调用
|
||||
func (s *Service) RevealClientCredentials(userID int) (map[int]string, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if userID <= 0 {
|
||||
return nil, ErrInvalidUser
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
vaultRoot := s.vaultRoot
|
||||
if vaultRoot == "" {
|
||||
return make(map[int]string), nil
|
||||
}
|
||||
var items []models.ClientCredential
|
||||
if err := s.engine.Where("user_id = ? AND revoked_at IS NULL", userID).Find(&items); err != nil {
|
||||
return nil, fmt.Errorf("load client credentials for reveal: %w", err)
|
||||
}
|
||||
result := make(map[int]string, len(items))
|
||||
for _, item := range items {
|
||||
if item.CodeCiphertext == "" || item.CodeHash == "" {
|
||||
continue
|
||||
}
|
||||
plain, err := credential.Decrypt(vaultRoot, item.CodeCiphertext)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
result[item.ID] = plain
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// VerifyClientOrProtocolCode 同时支持客户端专属授权码以及遗留的协议授权码
|
||||
func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPlain string) bool {
|
||||
if s == nil || s.engine == nil || userID <= 0 || rawPlain == "" || len([]byte(rawPlain)) > 256 {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
}
|
||||
cleanedPlain := CleanAuthCode(rawPlain)
|
||||
if cleanedPlain == "" {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
}
|
||||
|
||||
// 1. 优先校验客户端专属授权码
|
||||
var clients []models.ClientCredential
|
||||
err := s.engine.Where("user_id = ? AND revoked_at IS NULL AND code_hash != ''", userID).Find(&clients)
|
||||
if err == nil && len(clients) > 0 {
|
||||
for _, client := range clients {
|
||||
// 比对清洗后的统一大写无横线授权码
|
||||
if password.Verify(client.CodeHash, cleanedPlain) {
|
||||
now := s.now()
|
||||
_, _ = s.engine.ID(client.ID).
|
||||
Where("revoked_at IS NULL AND code_version = ? AND code_hash = ?", client.CodeVersion, client.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ClientCredential{LastUsedAt: &now})
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 回退校验旧版按协议划分的授权码(支持 cleanedPlain 或原樣 rawPlain)
|
||||
protocol, err = NormalizeProtocol(protocol)
|
||||
if err != nil {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
}
|
||||
var item models.ProtocolCredential
|
||||
has, err := s.engine.Where("user_id = ? AND protocol = ? AND enabled = ? AND revoked_at IS NULL", userID, protocol, true).Get(&item)
|
||||
if err != nil || !has || item.CodeHash == "" {
|
||||
password.VerifyDummy(rawPlain)
|
||||
return false
|
||||
}
|
||||
|
||||
// 兼容旧哈希直接比对原始输入,或者比对清洗后的输入
|
||||
matched := password.Verify(item.CodeHash, strings.TrimSpace(rawPlain)) || password.Verify(item.CodeHash, cleanedPlain)
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
affected, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ProtocolCredential{LastUsedAt: &now})
|
||||
if err == nil && affected == 1 {
|
||||
return true
|
||||
}
|
||||
|
||||
valid, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Exist(&models.ProtocolCredential{})
|
||||
return err == nil && valid
|
||||
}
|
||||
Reference in new issue
Block a user