From 13a2383597c90399d7c8a8abfd6fca0b114e9e77 Mon Sep 17 00:00:00 2001
From: hyg <hyg@webterren.com>
Date: Tue, 12 Sep 2023 23:34:28 +0800
Subject: [PATCH] Show error instead of 500 HTTP error if authenticate fails
 via external SMTP

Close #27043
---
 .../auth/source/smtp/source_authenticate.go     | 17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)

diff --git a/services/auth/source/smtp/source_authenticate.go b/services/auth/source/smtp/source_authenticate.go
index b2e94933a6..d8396c21a9 100644
--- a/services/auth/source/smtp/source_authenticate.go
+++ b/services/auth/source/smtp/source_authenticate.go
@@ -42,16 +42,13 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
 	}
 
 	if err := Authenticate(auth, source); err != nil {
-		// Check standard error format first,
-		// then fallback to worse case.
-		tperr, ok := err.(*textproto.Error)
-		if (ok && tperr.Code == 535) ||
-			strings.Contains(err.Error(), "Username and Password not accepted") {
-			return nil, user_model.ErrUserNotExist{Name: userName}
-		}
-		if (ok && tperr.Code == 534) ||
-			strings.Contains(err.Error(), "Application-specific password required") {
-			return nil, user_model.ErrUserNotExist{Name: userName}
+		// when authentication via smtp fails, wraps ErrInvalidArgument
+		// with the original textproto.Error as the cause,
+		// so it will show username_password_incorrect to the user
+		// while log the original error so that admin can check.
+		// see: routers/web/auth/auth.go SiginPost
+		if tperr, ok := err.(*textproto.Error); ok {
+			return nil, errors.Join(util.ErrInvalidArgument, tperr)
 		}
 		return nil, err
 	}