Skip to content

Commit bbae679

Browse files
authored
Merge pull request 0xJacky#830 from 0xJacky/enhance/error-handle
enhance: error handle
2 parents 3f95ae5 + 250bd8e commit bbae679

File tree

94 files changed

+5232
-3742
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

94 files changed

+5232
-3742
lines changed

api/api.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package api
22

33
import (
4+
"errors"
45
"github.com/0xJacky/Nginx-UI/model"
56
"github.com/gin-gonic/gin"
7+
"github.com/uozi-tech/cosy"
68
"github.com/uozi-tech/cosy/logger"
9+
"gorm.io/gorm"
710
"net/http"
811
)
912

@@ -13,9 +16,21 @@ func CurrentUser(c *gin.Context) *model.User {
1316

1417
func ErrHandler(c *gin.Context, err error) {
1518
logger.GetLogger().Errorln(err)
16-
c.JSON(http.StatusInternalServerError, gin.H{
17-
"message": err.Error(),
18-
})
19+
var cErr *cosy.Error
20+
switch {
21+
case errors.Is(err, gorm.ErrRecordNotFound):
22+
c.JSON(http.StatusNotFound, &cosy.Error{
23+
Code: http.StatusNotFound,
24+
Message: gorm.ErrRecordNotFound.Error(),
25+
})
26+
case errors.As(err, &cErr):
27+
c.JSON(http.StatusInternalServerError, cErr)
28+
default:
29+
c.JSON(http.StatusInternalServerError, &cosy.Error{
30+
Code: http.StatusInternalServerError,
31+
Message: err.Error(),
32+
})
33+
}
1934
}
2035

2136
func SetSSEHeaders(c *gin.Context) {

api/nginx/router.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package nginx
22

3-
import "github.com/gin-gonic/gin"
3+
import (
4+
"github.com/0xJacky/Nginx-UI/api/nginx_log"
5+
"github.com/gin-gonic/gin"
6+
)
47

58
func InitRouter(r *gin.RouterGroup) {
69
r.POST("ngx/build_config", BuildNginxConfig)
@@ -10,10 +13,6 @@ func InitRouter(r *gin.RouterGroup) {
1013
r.POST("nginx/restart", Restart)
1114
r.POST("nginx/test", Test)
1215
r.GET("nginx/status", Status)
13-
r.POST("nginx_log", GetNginxLogPage)
16+
r.POST("nginx_log", nginx_log.GetNginxLogPage)
1417
r.GET("nginx/directives", GetDirectives)
1518
}
16-
17-
func InitNginxLogRouter(r *gin.RouterGroup) {
18-
r.GET("nginx_log", Log)
19-
}

api/nginx/nginx_log.go renamed to api/nginx_log/nginx_log.go

Lines changed: 11 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
package nginx
1+
package nginx_log
22

33
import (
44
"encoding/json"
5-
"fmt"
6-
"github.com/0xJacky/Nginx-UI/internal/cache"
7-
"github.com/0xJacky/Nginx-UI/internal/helper"
85
"github.com/0xJacky/Nginx-UI/internal/nginx"
9-
"github.com/0xJacky/Nginx-UI/settings"
6+
"github.com/0xJacky/Nginx-UI/internal/nginx_log"
107
"github.com/gin-gonic/gin"
118
"github.com/gorilla/websocket"
129
"github.com/hpcloud/tail"
@@ -70,7 +67,7 @@ func GetNginxLogPage(c *gin.Context) {
7067
c.JSON(http.StatusInternalServerError, nginxLogPageResp{
7168
Error: "log file is not regular file",
7269
})
73-
logger.Error("log file is not regular file:", logPath)
70+
logger.Errorf("log file is not regular file: %s", logPath)
7471
return
7572
}
7673

@@ -132,30 +129,7 @@ func GetNginxLogPage(c *gin.Context) {
132129
})
133130
}
134131

135-
// isLogPathUnderWhiteList checks if the log path is under one of the paths in LogDirWhiteList
136-
func isLogPathUnderWhiteList(path string) bool {
137-
cacheKey := fmt.Sprintf("isLogPathUnderWhiteList:%s", path)
138-
res, ok := cache.Get(cacheKey)
139-
// no cache, check it
140-
if !ok {
141-
for _, whitePath := range settings.NginxSettings.LogDirWhiteList {
142-
if helper.IsUnderDirectory(path, whitePath) {
143-
cache.Set(cacheKey, true, 0)
144-
return true
145-
}
146-
}
147-
return false
148-
}
149-
return res.(bool)
150-
}
151-
152132
func getLogPath(control *controlStruct) (logPath string, err error) {
153-
if len(settings.NginxSettings.LogDirWhiteList) == 0 {
154-
err = errors.New("The settings.NginxSettings.LogDirWhiteList has not been configured. " +
155-
"For security reasons, please configure a whitelist of log directories. " +
156-
"Please visit https://nginxui.com/guide/config-nginx.html for more information.")
157-
return
158-
}
159133
switch control.Type {
160134
case "site":
161135
var config *nginx.NgxConfig
@@ -167,12 +141,12 @@ func getLogPath(control *controlStruct) (logPath string, err error) {
167141
}
168142

169143
if control.ServerIdx >= len(config.Servers) {
170-
err = errors.New("serverIdx out of range")
144+
err = nginx_log.ErrServerIdxOutOfRange
171145
return
172146
}
173147

174148
if control.DirectiveIdx >= len(config.Servers[control.ServerIdx].Directives) {
175-
err = errors.New("DirectiveIdx out of range")
149+
err = nginx_log.ErrDirectiveIdxOutOfRange
176150
return
177151
}
178152

@@ -181,12 +155,12 @@ func getLogPath(control *controlStruct) (logPath string, err error) {
181155
case "access_log", "error_log":
182156
// ok
183157
default:
184-
err = errors.New("directive.Params neither access_log nor error_log")
158+
err = nginx_log.ErrLogDirective
185159
return
186160
}
187161

188162
if directive.Params == "" {
189-
err = errors.New("directive.Params is empty")
163+
err = nginx_log.ErrDirectiveParamsIsEmpty
190164
return
191165
}
192166

@@ -200,8 +174,7 @@ func getLogPath(control *controlStruct) (logPath string, err error) {
200174
path := nginx.GetErrorLogPath()
201175

202176
if path == "" {
203-
err = errors.New("settings.NginxLogSettings.ErrorLogPath is empty," +
204-
" refer to https://nginxui.com/guide/config-nginx.html for more information")
177+
err = nginx_log.ErrErrorLogPathIsEmpty
205178
return
206179
}
207180

@@ -210,18 +183,16 @@ func getLogPath(control *controlStruct) (logPath string, err error) {
210183
path := nginx.GetAccessLogPath()
211184

212185
if path == "" {
213-
err = errors.New("settings.NginxLogSettings.AccessLogPath is empty," +
214-
" refer to https://nginxui.com/guide/config-nginx.html for more information")
186+
err = nginx_log.ErrAccessLogPathIsEmpty
215187
return
216188
}
217189

218190
logPath = path
219191
}
220192

221193
// check if logPath is under one of the paths in LogDirWhiteList
222-
if !isLogPathUnderWhiteList(logPath) {
223-
err = errors.New("The log path is not under the paths in LogDirWhiteList.")
224-
return "", err
194+
if !nginx_log.IsLogPathUnderWhiteList(logPath) {
195+
return "", nginx_log.ErrLogPathIsNotUnderTheLogDirWhiteList
225196
}
226197
return
227198
}

api/nginx_log/router.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package nginx_log
2+
3+
import "github.com/gin-gonic/gin"
4+
5+
func InitRouter(r *gin.RouterGroup) {
6+
r.GET("nginx_log", Log)
7+
}

api/openai/openai.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"github.com/0xJacky/Nginx-UI/internal/chatbot"
77
"github.com/0xJacky/Nginx-UI/settings"
88
"github.com/gin-gonic/gin"
9-
"github.com/pkg/errors"
9+
"errors"
1010
"github.com/sashabaranov/go-openai"
1111
"github.com/uozi-tech/cosy"
1212
"github.com/uozi-tech/cosy/logger"

api/user/2fa.go

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package user
22

33
import (
44
"encoding/base64"
5-
"fmt"
65
"github.com/0xJacky/Nginx-UI/api"
76
"github.com/0xJacky/Nginx-UI/internal/cache"
87
"github.com/0xJacky/Nginx-UI/internal/passkey"
@@ -77,23 +76,17 @@ func Start2FASecureSessionByOTP(c *gin.Context) {
7776
}
7877
u := api.CurrentUser(c)
7978
if !u.EnabledOTP() {
80-
c.JSON(http.StatusBadRequest, gin.H{
81-
"message": "User has not configured OTP as 2FA",
82-
})
79+
api.ErrHandler(c, user.ErrUserNotEnabledOTPAs2FA)
8380
return
8481
}
8582

8683
if json.OTP == "" && json.RecoveryCode == "" {
87-
c.JSON(http.StatusBadRequest, LoginResponse{
88-
Message: "The user has enabled OTP as 2FA",
89-
})
84+
api.ErrHandler(c, user.ErrOTPOrRecoveryCodeEmpty)
9085
return
9186
}
9287

9388
if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
94-
c.JSON(http.StatusBadRequest, LoginResponse{
95-
Message: "Invalid OTP or recovery code",
96-
})
89+
api.ErrHandler(c, err)
9790
return
9891
}
9992

@@ -106,7 +99,7 @@ func Start2FASecureSessionByOTP(c *gin.Context) {
10699

107100
func BeginStart2FASecureSessionByPasskey(c *gin.Context) {
108101
if !passkey.Enabled() {
109-
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
102+
api.ErrHandler(c, user.ErrWebAuthnNotConfigured)
110103
return
111104
}
112105
webauthnInstance := passkey.GetInstance()
@@ -126,13 +119,13 @@ func BeginStart2FASecureSessionByPasskey(c *gin.Context) {
126119

127120
func FinishStart2FASecureSessionByPasskey(c *gin.Context) {
128121
if !passkey.Enabled() {
129-
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
122+
api.ErrHandler(c, user.ErrWebAuthnNotConfigured)
130123
return
131124
}
132125
passkeySessionID := c.GetHeader("X-Passkey-Session-ID")
133126
sessionDataBytes, ok := cache.Get(passkeySessionID)
134127
if !ok {
135-
api.ErrHandler(c, fmt.Errorf("session not found"))
128+
api.ErrHandler(c, user.ErrSessionNotFound)
136129
return
137130
}
138131
sessionData := sessionDataBytes.(*webauthn.SessionData)

api/user/auth.go

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"github.com/0xJacky/Nginx-UI/query"
77
"github.com/0xJacky/Nginx-UI/settings"
88
"github.com/gin-gonic/gin"
9-
"github.com/pkg/errors"
9+
"errors"
1010
"github.com/uozi-tech/cosy"
1111
"github.com/uozi-tech/cosy/logger"
1212
"math/rand/v2"
@@ -25,12 +25,10 @@ type LoginUser struct {
2525
}
2626

2727
const (
28-
ErrPasswordIncorrect = 4031
29-
ErrMaxAttempts = 4291
30-
ErrUserBanned = 4033
31-
Enabled2FA = 199
32-
Error2FACode = 4034
33-
LoginSuccess = 200
28+
ErrMaxAttempts = 4291
29+
Enabled2FA = 199
30+
Error2FACode = 4034
31+
LoginSuccess = 200
3432
)
3533

3634
type LoginResponse struct {
@@ -73,15 +71,9 @@ func Login(c *gin.Context) {
7371
time.Sleep(random * time.Second)
7472
switch {
7573
case errors.Is(err, user.ErrPasswordIncorrect):
76-
c.JSON(http.StatusForbidden, LoginResponse{
77-
Message: "Password incorrect",
78-
Code: ErrPasswordIncorrect,
79-
})
74+
c.JSON(http.StatusForbidden, user.ErrPasswordIncorrect)
8075
case errors.Is(err, user.ErrUserBanned):
81-
c.JSON(http.StatusForbidden, LoginResponse{
82-
Message: "The user is banned",
83-
Code: ErrUserBanned,
84-
})
76+
c.JSON(http.StatusForbidden, user.ErrUserBanned)
8577
default:
8678
api.ErrHandler(c, err)
8779
}

api/user/casdoor.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/0xJacky/Nginx-UI/settings"
88
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
99
"github.com/gin-gonic/gin"
10-
"github.com/pkg/errors"
10+
"errors"
1111
"github.com/uozi-tech/cosy"
1212
"gorm.io/gorm"
1313
"net/http"

api/user/passkey.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func FinishPasskeyRegistration(c *gin.Context) {
5353
webauthnInstance := passkey.GetInstance()
5454
sessionDataBytes, ok := cache.Get(buildCachePasskeyRegKey(cUser.ID))
5555
if !ok {
56-
api.ErrHandler(c, fmt.Errorf("session not found"))
56+
api.ErrHandler(c, user.ErrSessionNotFound)
5757
return
5858
}
5959

@@ -87,7 +87,7 @@ func FinishPasskeyRegistration(c *gin.Context) {
8787

8888
func BeginPasskeyLogin(c *gin.Context) {
8989
if !passkey.Enabled() {
90-
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
90+
api.ErrHandler(c, user.ErrWebAuthnNotConfigured)
9191
return
9292
}
9393
webauthnInstance := passkey.GetInstance()
@@ -107,13 +107,13 @@ func BeginPasskeyLogin(c *gin.Context) {
107107

108108
func FinishPasskeyLogin(c *gin.Context) {
109109
if !passkey.Enabled() {
110-
api.ErrHandler(c, fmt.Errorf("WebAuthn settings are not configured"))
110+
api.ErrHandler(c, user.ErrWebAuthnNotConfigured)
111111
return
112112
}
113113
sessionId := c.GetHeader("X-Passkey-Session-ID")
114114
sessionDataBytes, ok := cache.Get(sessionId)
115115
if !ok {
116-
api.ErrHandler(c, fmt.Errorf("session not found"))
116+
api.ErrHandler(c, user.ErrSessionNotFound)
117117
return
118118
}
119119
webauthnInstance := passkey.GetInstance()

app/src/components/NginxControl/NginxControl.vue

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,6 @@ function reloadNginx() {
2828
message.warn(r.message)
2929
else
3030
message.error(r.message)
31-
}).catch(e => {
32-
message.error(`${$gettext('Server error')} ${e?.message}`)
3331
}).finally(() => getStatus())
3432
}
3533
@@ -44,8 +42,6 @@ async function restartNginx() {
4442
message.warn(r.message)
4543
else
4644
message.error(r.message)
47-
}).catch(e => {
48-
message.error(`${$gettext('Server error')} ${e?.message}`)
4945
})
5046
}
5147

0 commit comments

Comments
 (0)