3x-ui/web/controller/index.go

172 lines
5.6 KiB
Go
Raw Normal View History

2023-02-09 19:18:06 +00:00
package controller
import (
"net/http"
"text/template"
2023-02-09 19:18:06 +00:00
"time"
2025-09-19 08:05:43 +00:00
"github.com/mhsanaei/3x-ui/v2/logger"
"github.com/mhsanaei/3x-ui/v2/web/middleware"
2025-09-19 08:05:43 +00:00
"github.com/mhsanaei/3x-ui/v2/web/service"
"github.com/mhsanaei/3x-ui/v2/web/session"
2023-02-09 19:18:06 +00:00
"github.com/gin-gonic/gin"
)
2025-09-20 07:35:50 +00:00
// LoginForm represents the login request structure.
2023-02-09 19:18:06 +00:00
type LoginForm struct {
2025-09-18 20:06:01 +00:00
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// IndexController handles the main index and login-related routes.
2023-02-09 19:18:06 +00:00
type IndexController struct {
BaseController
settingService service.SettingService
userService service.UserService
tgbot service.Tgbot
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// NewIndexController creates a new IndexController and initializes its routes.
2023-02-09 19:18:06 +00:00
func NewIndexController(g *gin.RouterGroup) *IndexController {
a := &IndexController{}
a.initRouter(g)
return a
}
2025-09-20 07:35:50 +00:00
// initRouter sets up the routes for index, login, logout, and two-factor authentication.
2023-02-09 19:18:06 +00:00
func (a *IndexController) initRouter(g *gin.RouterGroup) {
g.GET("/", a.index)
g.GET("/logout", a.logout)
// Public CSRF endpoint — the SPA login page (served by Vite in
// dev or by serveDistPage in prod) needs a token to POST /login,
// but the panel-side /panel/csrf-token sits behind checkLogin.
// EnsureCSRFToken creates a session token even for anonymous
// callers, so any pre-login flow can bootstrap from here.
g.GET("/csrf-token", a.csrfToken)
2025-09-24 09:47:14 +00:00
g.POST("/login", middleware.CSRFMiddleware(), a.login)
g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// index handles the root route, redirecting logged-in users to the panel or showing the login page.
2023-02-09 19:18:06 +00:00
func (a *IndexController) index(c *gin.Context) {
if session.IsLogin(c) {
2023-05-12 18:06:05 +00:00
c.Redirect(http.StatusTemporaryRedirect, "panel/")
2023-02-09 19:18:06 +00:00
return
}
feat(server): Phase 8 — cut HTML routes over to web/dist/ Production cutover. Every user-facing HTML route now serves the Vue-3-built bundle from web/dist/ instead of rendering the legacy Go template; the long-hashed Vite assets are served at /assets/ from the same embedded filesystem. The legacy templates in web/html/ and the legacy static tree in web/assets/ are kept on disk for now in case a quick revert is needed, but nothing the binary serves references them. What changed: - web.go: a new //go:embed dist/* feeds the controller package via a SetDistFS hand-off before controller construction. The static /assets/ route is rebound: in dev to web/dist/assets/ on disk so Vite's incremental rebuilds show up live; in prod to the embedded dist via wrapDistFS (rooted one level deeper than wrapAssetsFS). - controller/dist.go: serveDistPage helper used by every HTML handler. Reads dist/<name> from the embedded FS and applies two transforms before sending: 1. injects <script>window.__X_UI_BASE_PATH__="..."</script> just before </head> so AppSidebar links resolve under the panel's basePath. 2. when basePath != "/", rewrites Vite's absolute /assets/ URLs to <basePath>assets/ so installs running under a custom URL prefix load the bundle where the static handler lives. HTML responses go out with no-cache so panel upgrades reach users on the next refresh; hashed JS/CSS stays cacheable. - controller/index.go: IndexController.index now serves dist/login.html for logged-out callers (the redirect for logged-in users is unchanged). - controller/xui.go: XUIController.{index,inbounds,settings,xraySettings} each become a one-line wrapper around serveDistPage. Smoke checklist for the maintainer: - run `cd frontend && npm run build` to refresh web/dist/ before building the Go binary (the embed snapshot is taken at compile time); - visit /panel/, /panel/inbounds, /panel/settings, /panel/xray and confirm each loads its Vue page; - log out and log back in to verify the login flow; - confirm the sidebar links navigate correctly under your install's basePath; - POST flows (e.g. saving settings) still need the CSRF token — that endpoint (/panel/csrf-token, added earlier) is unchanged. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 12:39:55 +00:00
serveDistPage(c, "login.html")
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// login handles user authentication and session creation.
2023-02-09 19:18:06 +00:00
func (a *IndexController) login(c *gin.Context) {
var form LoginForm
2024-12-16 13:24:59 +00:00
if err := c.ShouldBind(&form); err != nil {
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.invalidFormData"))
2023-02-09 19:18:06 +00:00
return
}
if form.Username == "" {
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyUsername"))
2023-02-09 19:18:06 +00:00
return
}
if form.Password == "" {
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyPassword"))
2023-02-09 19:18:06 +00:00
return
}
2023-05-20 15:09:01 +00:00
remoteIP := getRemoteIp(c)
safeUser := template.HTMLEscapeString(form.Username)
timeStr := time.Now().Format("2006-01-02 15:04:05")
if blockedUntil, ok := defaultLoginLimiter.allow(remoteIP, form.Username); !ok {
reason := "too many failed attempts"
logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
a.tgbot.UserLoginNotify(service.LoginAttempt{
Username: safeUser,
IP: remoteIP,
Time: timeStr,
Status: service.LoginFail,
Reason: reason,
})
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
return
}
2026-03-17 21:30:05 +00:00
user, checkErr := a.userService.CheckUser(form.Username, form.Password, form.TwoFactorCode)
2026-03-17 21:30:05 +00:00
if user == nil {
reason := loginFailureReason(checkErr)
if blockedUntil, blocked := defaultLoginLimiter.registerFailure(remoteIP, form.Username); blocked {
logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
} else {
logger.Warningf("failed login: username=%q, IP=%q, reason=%q", safeUser, remoteIP, reason)
}
a.tgbot.UserLoginNotify(service.LoginAttempt{
Username: safeUser,
IP: remoteIP,
Time: timeStr,
Status: service.LoginFail,
Reason: reason,
})
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
2023-02-09 19:18:06 +00:00
return
2023-04-25 22:39:56 +00:00
}
defaultLoginLimiter.registerSuccess(remoteIP, form.Username)
logger.Infof("%s logged in successfully, Ip Address: %s\n", safeUser, remoteIP)
a.tgbot.UserLoginNotify(service.LoginAttempt{
Username: safeUser,
IP: remoteIP,
Time: timeStr,
Status: service.LoginSuccess,
})
2024-12-16 13:24:59 +00:00
ws/inbounds: realtime fixes + perf for 10k+ client inbounds (#4123) * ws/inbounds: realtime fixes + perf for 10k+ client inbounds - hub: dedup, throttle, panic-restart, deadlock fix, race tests - client: backoff cap + slow-retry instead of giving up - broadcast: delta-only payload, count-based invalidate fallback - filter: fix empty online list (Inbound has no .id, use dbInbound.toInbound) - perf: O(N²)→O(N) traffic merge, bulk delete, /setEnable endpoint - traffic: monotonic all_time + UI clamp + propagate in delta handler - session: persist on update/logout (fixes logout-after-password-change) - ui: protocol tags flex, traffic bar normalize * Remove hub_test.go file * fix: ws hub, inbound service, and frontend correctness - propagate DelInbound error on disable path in SetInboundEnable - skip empty emails in updateClientTraffics to avoid constraint violations - use consistent IN ? clause, drop redundant ErrRecordNotFound guards - Hub.Unregister: direct removeClient fallback when channel is full - applyClientStatsDelta: O(1) email lookup via per-inbound Map cache - WS payload size check: Blob.size instead of .length for real byte count * fix: chunk large IN ? queries and fix IPv6 same-origin check * fix: chunk large IN ? queries and fix IPv6 same-origin check * fix: unify clientStats cache, throttle clarity, hub constants * fix(ui): align traffic/expiry cell columns across all rows * style(ui): redesign outbounds table for visual consistency * style(ui): redesign routing table for visual consistency * fix: * fix: * fix: * fix: * fix: * fix: font * refactor: simplify outbound tone functions for consistency and maintainability --------- Co-authored-by: lolka1333 <test123@gmail.com>
2026-05-05 15:27:49 +00:00
if err := session.SetLoginUser(c, user); err != nil {
logger.Warning("Unable to save session:", err)
2024-12-16 13:24:59 +00:00
return
2023-02-09 19:18:06 +00:00
}
2024-12-16 13:24:59 +00:00
logger.Infof("%s logged in successfully", safeUser)
jsonMsg(c, I18nWeb(c, "pages.login.toasts.successLogin"), nil)
2023-02-09 19:18:06 +00:00
}
func loginFailureReason(err error) string {
if err != nil && err.Error() == "invalid 2fa code" {
return "invalid 2FA code"
}
return "invalid credentials"
}
2025-09-20 07:35:50 +00:00
// logout handles user logout by clearing the session and redirecting to the login page.
2023-02-09 19:18:06 +00:00
func (a *IndexController) logout(c *gin.Context) {
user := session.GetLoginUser(c)
if user != nil {
2024-07-08 21:08:00 +00:00
logger.Infof("%s logged out successfully", user.Username)
2023-02-09 19:18:06 +00:00
}
ws/inbounds: realtime fixes + perf for 10k+ client inbounds (#4123) * ws/inbounds: realtime fixes + perf for 10k+ client inbounds - hub: dedup, throttle, panic-restart, deadlock fix, race tests - client: backoff cap + slow-retry instead of giving up - broadcast: delta-only payload, count-based invalidate fallback - filter: fix empty online list (Inbound has no .id, use dbInbound.toInbound) - perf: O(N²)→O(N) traffic merge, bulk delete, /setEnable endpoint - traffic: monotonic all_time + UI clamp + propagate in delta handler - session: persist on update/logout (fixes logout-after-password-change) - ui: protocol tags flex, traffic bar normalize * Remove hub_test.go file * fix: ws hub, inbound service, and frontend correctness - propagate DelInbound error on disable path in SetInboundEnable - skip empty emails in updateClientTraffics to avoid constraint violations - use consistent IN ? clause, drop redundant ErrRecordNotFound guards - Hub.Unregister: direct removeClient fallback when channel is full - applyClientStatsDelta: O(1) email lookup via per-inbound Map cache - WS payload size check: Blob.size instead of .length for real byte count * fix: chunk large IN ? queries and fix IPv6 same-origin check * fix: chunk large IN ? queries and fix IPv6 same-origin check * fix: unify clientStats cache, throttle clarity, hub constants * fix(ui): align traffic/expiry cell columns across all rows * style(ui): redesign outbounds table for visual consistency * style(ui): redesign routing table for visual consistency * fix: * fix: * fix: * fix: * fix: * fix: font * refactor: simplify outbound tone functions for consistency and maintainability --------- Co-authored-by: lolka1333 <test123@gmail.com>
2026-05-05 15:27:49 +00:00
if err := session.ClearSession(c); err != nil {
logger.Warning("Unable to clear session on logout:", err)
2024-12-16 13:24:59 +00:00
}
2023-02-09 19:18:06 +00:00
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
}
// csrfToken returns the session CSRF token. Public — the login page
// needs a token before authenticating.
func (a *IndexController) csrfToken(c *gin.Context) {
token, err := session.EnsureCSRFToken(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "msg": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "obj": token})
}
2025-09-20 07:35:50 +00:00
// getTwoFactorEnable retrieves the current status of two-factor authentication.
func (a *IndexController) getTwoFactorEnable(c *gin.Context) {
status, err := a.settingService.GetTwoFactorEnable()
if err == nil {
jsonObj(c, status, nil)
}
}