2023-02-09 19:18:06 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
2025-02-11 08:10:21 +00:00
|
|
|
"fmt"
|
2023-02-09 19:18:06 +00:00
|
|
|
"net/http"
|
2025-02-11 08:10:21 +00:00
|
|
|
"strings"
|
2024-03-10 21:31:24 +00:00
|
|
|
|
2023-05-20 15:19:39 +00:00
|
|
|
"x-ui/logger"
|
|
|
|
"x-ui/web/locale"
|
2023-02-09 19:18:06 +00:00
|
|
|
"x-ui/web/session"
|
2023-04-29 15:17:44 +00:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2025-02-11 08:10:21 +00:00
|
|
|
"x-ui/web/service"
|
2023-02-09 19:18:06 +00:00
|
|
|
)
|
|
|
|
|
2025-02-11 08:10:21 +00:00
|
|
|
type BaseController struct{
|
|
|
|
settingService service.SettingService
|
|
|
|
}
|
2023-02-09 19:18:06 +00:00
|
|
|
|
|
|
|
func (a *BaseController) checkLogin(c *gin.Context) {
|
|
|
|
if !session.IsLogin(c) {
|
|
|
|
if isAjax(c) {
|
2024-03-10 21:31:24 +00:00
|
|
|
pureJsonMsg(c, http.StatusUnauthorized, false, I18nWeb(c, "pages.login.loginAgain"))
|
2023-02-09 19:18:06 +00:00
|
|
|
} else {
|
|
|
|
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
|
|
|
|
}
|
|
|
|
c.Abort()
|
|
|
|
} else {
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-20 22:59:27 +00:00
|
|
|
func I18nWeb(c *gin.Context, name string, params ...string) string {
|
2023-05-20 15:19:39 +00:00
|
|
|
anyfunc, funcExists := c.Get("I18n")
|
|
|
|
if !funcExists {
|
|
|
|
logger.Warning("I18n function not exists in gin context!")
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
i18nFunc, _ := anyfunc.(func(i18nType locale.I18nType, key string, keyParams ...string) string)
|
|
|
|
msg := i18nFunc(locale.Web, name, params...)
|
|
|
|
return msg
|
2023-02-09 19:18:06 +00:00
|
|
|
}
|
2025-02-11 08:10:21 +00:00
|
|
|
|
|
|
|
func (a *BaseController) apiTokenGuard(c *gin.Context) {
|
2025-02-11 08:41:17 +00:00
|
|
|
bearerToken := c.Request.Header.Get("Authorization")
|
|
|
|
tokenParts := strings.Split(bearerToken, " ")
|
|
|
|
if len(tokenParts) != 2 {
|
2025-02-11 08:10:21 +00:00
|
|
|
pureJsonMsg(c, http.StatusUnauthorized, false, "Invalid token format")
|
2025-02-11 08:41:17 +00:00
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
reqToken := tokenParts[1]
|
2025-02-11 08:10:21 +00:00
|
|
|
token, err := a.settingService.GetApiToken()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
pureJsonMsg(c, http.StatusUnauthorized, false, err.Error())
|
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if reqToken != token {
|
2025-02-11 08:41:17 +00:00
|
|
|
pureJsonMsg(c, http.StatusUnauthorized, false, "Auth failed")
|
2025-02-11 08:10:21 +00:00
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
userService := service.UserService{}
|
|
|
|
user, err := userService.GetFirstUser()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("get current user info failed, error info:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
session.SetSessionUser(c, user)
|
|
|
|
|
2025-02-11 08:41:17 +00:00
|
|
|
c.Next()
|
2025-02-11 08:10:21 +00:00
|
|
|
|
|
|
|
session.ClearSession(c)
|
|
|
|
}
|