保存外部邮箱验证码绑定当前进度
This commit is contained in:
1 parent
d0f543d413
commit
2a3d3b420e
12 files changed
+681
-106
No files matched your search
@@ -653,6 +653,9 @@ func ListExternalEmails(ctx *context.Context, w http.ResponseWriter, req *http.R
|
||||
}
|
||||
result := make([]map[string]any, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item.Status == models.ExternalEmailStatusPending {
|
||||
continue
|
||||
}
|
||||
email, err := runtime.external.Decrypt(item)
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -669,7 +672,7 @@ func BindExternalEmail(ctx *context.Context, w http.ResponseWriter, req *http.Re
|
||||
return
|
||||
}
|
||||
if !ctx.RecentAuth {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "此操作需要最近十分钟内完成登录,请重新登录后再试")
|
||||
writeSecurityErrorWithCode(w, response.NoAccessPrivileges, "此操作需要最近十分钟内完成登录,请确认当前密码", string(access.CodeRecentAuthRequired))
|
||||
return
|
||||
}
|
||||
var input externalEmailRequest
|
||||
@@ -679,7 +682,7 @@ func BindExternalEmail(ctx *context.Context, w http.ResponseWriter, req *http.Re
|
||||
}
|
||||
normalizedEmail, err := externalemail.NormalizeEmail(input.Email)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "外部邮箱绑定失败")
|
||||
writeSecurityError(w, response.ParamsError, "请输入有效的外部邮箱地址")
|
||||
return
|
||||
}
|
||||
owned, err := currentUserPrimaryEmail(ctx.UserID, normalizedEmail)
|
||||
@@ -694,14 +697,31 @@ func BindExternalEmail(ctx *context.Context, w http.ResponseWriter, req *http.Re
|
||||
}
|
||||
input.Email = normalizedEmail
|
||||
item, err := runtime.external.Bind(externalemail.BindRequest{UserID: ctx.UserID, Email: input.Email, Type: input.Type})
|
||||
created := err == nil
|
||||
if errors.Is(err, externalemail.ErrBindingExists) {
|
||||
item, err = runtime.external.FindPending(ctx.UserID, input.Email, input.Type)
|
||||
if errors.Is(err, externalemail.ErrBindingNotFound) {
|
||||
writeSecurityError(w, response.ParamsError, "该外部邮箱已经绑定")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "外部邮箱绑定失败")
|
||||
switch {
|
||||
case errors.Is(err, externalemail.ErrPrimaryLimit):
|
||||
writeSecurityError(w, response.ParamsError, "主要外部邮箱已存在,请先停用后再绑定")
|
||||
case errors.Is(err, externalemail.ErrBackupLimit):
|
||||
writeSecurityError(w, response.ParamsError, "备用外部邮箱已存在,请先停用后再绑定")
|
||||
default:
|
||||
writeSecurityError(w, response.ParamsError, "外部邮箱绑定失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
challenge, err := runtime.verification.Issue(verification.IssueRequest{Purpose: verification.PurposeExternalEmailBind, UserID: ctx.UserID, Account: ctx.UserAccount, Email: input.Email, ResourceID: item.ID}, remoteIP(req))
|
||||
if err != nil {
|
||||
_ = runtime.external.AbandonPending(ctx.UserID, item.ID)
|
||||
writeSecurityError(w, response.ParamsError, "外部邮箱绑定失败")
|
||||
if created {
|
||||
_ = runtime.external.AbandonPending(ctx.UserID, item.ID)
|
||||
}
|
||||
writeSecurityError(w, response.ParamsError, externalEmailVerificationIssueMessage(err))
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"id": item.ID, "challenge_id": challenge.ID, "status": item.Status, "email": maskEmail(input.Email), "expires_at": challenge.ExpiresAt.UTC()}).FPrint(w)
|
||||
@@ -727,7 +747,7 @@ func VerifyExternalEmail(ctx *context.Context, w http.ResponseWriter, req *http.
|
||||
return
|
||||
}
|
||||
if err := runtime.verification.VerifyBound(input.ID, ctx.UserAccount, input.Email, input.Code, verification.PurposeExternalEmailBind, input.BindingID, remoteIP(req)); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败")
|
||||
writeSecurityError(w, response.ParamsError, externalEmailVerificationCheckMessage(err))
|
||||
return
|
||||
}
|
||||
if err := runtime.external.Verify(ctx.UserID, input.BindingID); err != nil {
|
||||
@@ -805,3 +825,31 @@ func maskEmail(value string) string {
|
||||
func writeSecurityError(w http.ResponseWriter, code int, message string) {
|
||||
response.NewErrorResponse(code, message, "").FPrint(w)
|
||||
}
|
||||
|
||||
func writeSecurityErrorWithCode(w http.ResponseWriter, errorNo int, message, code string) {
|
||||
response.NewErrorResponse(errorNo, message, response.ConfigErrorData{Code: code}).FPrint(w)
|
||||
}
|
||||
|
||||
func externalEmailVerificationIssueMessage(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, verification.ErrRateLimited):
|
||||
return "验证码发送过于频繁,请稍后再试"
|
||||
case errors.Is(err, verification.ErrSMTPRelayUnavailable),
|
||||
errors.Is(err, verification.ErrInvalidSMTPConfig),
|
||||
errors.Is(err, verification.ErrUnsupportedSMTP):
|
||||
return "验证码发信服务尚未配置,请先完成 SMTP 发信配置"
|
||||
default:
|
||||
return "验证码发送失败,请检查发信服务后重试"
|
||||
}
|
||||
}
|
||||
|
||||
func externalEmailVerificationCheckMessage(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, verification.ErrExpiredChallenge):
|
||||
return "验证码已过期,请重新发送"
|
||||
case errors.Is(err, verification.ErrTooManyAttempts):
|
||||
return "验证码错误次数过多,请重新发送"
|
||||
default:
|
||||
return "验证码错误或验证请求已失效"
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
"git.pcux.cn/xuans/Smail/services/externalemail"
|
||||
"git.pcux.cn/xuans/Smail/services/verification"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
@@ -67,6 +69,30 @@ func TestSuperAdminCannotManageRecoveryCodesThroughWeb(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindExternalEmailReturnsStableRecentAuthenticationCode(t *testing.T) {
|
||||
previous := securityRuntime
|
||||
securityRuntime.external = &externalemail.Repository{}
|
||||
securityRuntime.verification = &verification.Service{}
|
||||
t.Cleanup(func() { securityRuntime = previous })
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/security/external-email/bind",
|
||||
strings.NewReader(`{"email":"backup@example.com","type":"backup"}`),
|
||||
)
|
||||
BindExternalEmail(&appcontext.Context{UserID: 1, UserAccount: "alice"}, recorder, request)
|
||||
|
||||
var result response.Response
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
|
||||
t.Fatalf("invalid JSON response: %v", err)
|
||||
}
|
||||
data, ok := result.Data.(map[string]any)
|
||||
if result.ErrorNo != response.NoAccessPrivileges || !ok || data["code"] != string(access.CodeRecentAuthRequired) {
|
||||
t.Fatalf("recent authentication response = %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
_, _, engine, user, _ := newPublicSecurityFixture(t)
|
||||
credentialService, err := credentials.NewService(engine)
|
||||
|
||||
@@ -93,6 +93,39 @@ func (r *Repository) Bind(request BindRequest) (*models.ExternalEmail, error) {
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// FindPending 返回当前用户同一地址和用途尚未完成的绑定,供重新发送验证码复用。
|
||||
func (r *Repository) FindPending(userID int, email, emailType string) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || r.vault == nil || userID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
if emailType != models.ExternalEmailTypePrimary && emailType != models.ExternalEmailTypeBackup {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
normalized, err := NormalizeEmail(email)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
fingerprint, err := r.vault.Fingerprint(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := r.engine.Where(
|
||||
"user_id = ? AND email_fingerprint = ? AND email_type = ? AND status = ?",
|
||||
userID,
|
||||
fingerprint,
|
||||
emailType,
|
||||
models.ExternalEmailStatusPending,
|
||||
).Get(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find pending external email binding: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return nil, ErrBindingNotFound
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) List(userID int) ([]models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || userID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
|
||||
@@ -30,6 +30,10 @@ func TestRepositoryBindsVerifiesAndScopesByUser(t *testing.T) {
|
||||
if item.Status != models.ExternalEmailStatusPending || item.EmailCiphertext == "" {
|
||||
t.Fatalf("unexpected binding: %+v", item)
|
||||
}
|
||||
pending, err := repo.FindPending(1, "OWNER@example.com", models.ExternalEmailTypePrimary)
|
||||
if err != nil || pending.ID != item.ID {
|
||||
t.Fatalf("pending binding = %+v, err = %v", pending, err)
|
||||
}
|
||||
if _, err := repo.Bind(BindRequest{UserID: 1, Email: "other@example.com", Type: models.ExternalEmailTypePrimary}); err != ErrPrimaryLimit {
|
||||
t.Fatalf("primary limit error = %v", err)
|
||||
}
|
||||
@@ -39,6 +43,9 @@ func TestRepositoryBindsVerifiesAndScopesByUser(t *testing.T) {
|
||||
if err := repo.Verify(1, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repo.FindPending(1, "owner@example.com", models.ExternalEmailTypePrimary); err != ErrBindingNotFound {
|
||||
t.Fatalf("verified binding remained pending: %v", err)
|
||||
}
|
||||
stored, err := repo.List(1)
|
||||
if err != nil || len(stored) != 1 {
|
||||
t.Fatalf("list result = %v, %v", stored, err)
|
||||
|
||||
Reference in new issue
Block a user