From 8eb72831c15e87a4d9aee280cf52d350ad85e82c Mon Sep 17 00:00:00 2001 From: yanghuanglin Date: Thu, 14 Sep 2023 12:45:21 +0800 Subject: [PATCH] store auth information with session --- README.md | 4 +- README_zh.md | 4 +- assets/static/js/login.js | 3 +- assets/templates/index.html | 2 +- cmd/frps-panel/cmd.go | 5 +++ config/frps-panel.ini | 2 + go.mod | 4 ++ go.sum | 8 ++++ pkg/server/controller/authorizer.go | 64 ++++++++++++++++++++++------- pkg/server/controller/controller.go | 37 +++++------------ pkg/server/controller/variables.go | 19 ++++++--- pkg/server/server.go | 11 +++++ 12 files changed, 110 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index fc5003a..7135963 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ plugin_port = 7200 admin_user = admin ;the password of manage ui,optional admin_pwd = admin +;specified login state keep time in seconds.0 - before the browser completely exit, don't need to re-login,greater than 0: when Idle time exceeds this value,you should re-login +admin_keep_time = 0 ; enable tls tls_mode = false @@ -58,8 +60,6 @@ dashboard_addr = 127.0.0.1 dashboard_port = 7500 dashboard_user = admin dashboard_pwd = admin -; if your frps dashboard enable tls, change this to true -dashboard_tls = false [users] ;user user1 with meta_token 123 diff --git a/README_zh.md b/README_zh.md index 332495b..b1b67c7 100644 --- a/README_zh.md +++ b/README_zh.md @@ -49,6 +49,8 @@ plugin_port = 7200 admin_user = admin ;插件管理页面密码,与账号一起进行鉴权,可选 admin_pwd = admin +;登录状态空闲时间(秒):0-浏览器完全退出前不用重新登录,大于0-空闲超过此时间则需要重新登录. +admin_keep_time = 0 ; frps 面板页面是否启用https访问,如果为true,则只能通过https访问 tls_mode = false @@ -60,8 +62,6 @@ dashboard_addr = 127.0.0.1 dashboard_port = 7500 dashboard_user = admin dashboard_pwd = admin -; 如果frps的dashboard启用了tls,则把这个选项置为true,否则无法获取服务器信息 -dashboard_tls = false [users] ;user1的meta_token为123 diff --git a/assets/static/js/login.js b/assets/static/js/login.js index 2dfc2ea..caf5a6a 100644 --- a/assets/static/js/login.js +++ b/assets/static/js/login.js @@ -14,8 +14,7 @@ }, success: function (result) { if (result.success) { - document.cookie = 'token=' + result.token + ';path=/' - window.location.href = "/" + window.location.reload(); } else { layui.layer.msg(result.message); } diff --git a/assets/templates/index.html b/assets/templates/index.html index fd23a47..2f026f5 100644 --- a/assets/templates/index.html +++ b/assets/templates/index.html @@ -26,7 +26,7 @@
- +
${ if .showExit } diff --git a/cmd/frps-panel/cmd.go b/cmd/frps-panel/cmd.go index 96512a7..101dec9 100644 --- a/cmd/frps-panel/cmd.go +++ b/cmd/frps-panel/cmd.go @@ -119,12 +119,17 @@ func ParseConfigFile(file string) (controller.HandleController, server.TLS, erro common.PluginPort = commonSection.Key("plugin_port").MustInt(7200) common.User = commonSection.Key("admin_user").Value() common.Pwd = commonSection.Key("admin_pwd").Value() + common.KeepTime = commonSection.Key("admin_keep_time").MustInt(0) common.DashboardAddr = commonSection.Key("dashboard_addr").MustString("127.0.0.1") common.DashboardPort = commonSection.Key("dashboard_port").MustInt(7500) common.DashboardUser = commonSection.Key("dashboard_user").Value() common.DashboardPwd = commonSection.Key("dashboard_pwd").Value() common.DashboardTLS = strings.HasPrefix(strings.ToLower(common.DashboardAddr), "https://") + if common.KeepTime < 0 { + common.KeepTime = 0 + } + tls.Enable = commonSection.Key("tls_mode").MustBool(false) tls.Cert = commonSection.Key("tls_cert_file").MustString("") tls.Key = commonSection.Key("tls_key_file").MustString("") diff --git a/config/frps-panel.ini b/config/frps-panel.ini index 483f422..3d1e3bc 100644 --- a/config/frps-panel.ini +++ b/config/frps-panel.ini @@ -5,6 +5,8 @@ plugin_addr = 127.0.0.1 plugin_port = 7200 admin_user = admin admin_pwd = admin +; specified login state keep time +admin_keep_time = 0 ; enable tls tls_mode = false diff --git a/go.mod b/go.mod index fed7ec7..e8d583d 100644 --- a/go.mod +++ b/go.mod @@ -17,11 +17,15 @@ require ( github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb // indirect github.com/fatedier/golib v0.1.1-0.20200901083111-1f870741e185 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/gin-contrib/sessions v0.0.5 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.14.1 // indirect github.com/goccy/go-json v0.10.2 // indirect + github.com/gorilla/context v1.1.1 // indirect + github.com/gorilla/securecookie v1.1.1 // indirect + github.com/gorilla/sessions v1.2.1 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect diff --git a/go.sum b/go.sum index 23865fc..ac72ab6 100644 --- a/go.sum +++ b/go.sum @@ -46,6 +46,8 @@ github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9 github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/i18n v1.0.0 h1:e5uEOmaAr09Iyr4vuWuvvpByjmvxGDO7iSkmiFpSsk0= github.com/gin-contrib/i18n v1.0.0/go.mod h1:yyyTArpVZeXCFT/kbLbD5CS192+OZ8Y+angnJjvnB98= +github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE= +github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= @@ -95,7 +97,13 @@ github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= diff --git a/pkg/server/controller/authorizer.go b/pkg/server/controller/authorizer.go index 4dd873e..e400dc3 100644 --- a/pkg/server/controller/authorizer.go +++ b/pkg/server/controller/authorizer.go @@ -3,25 +3,36 @@ package controller import ( "encoding/base64" "fmt" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "net/http" "strings" + "time" ) func (c *HandleController) BasicAuth() gin.HandlerFunc { return func(context *gin.Context) { if strings.TrimSpace(c.CommonInfo.User) == "" || strings.TrimSpace(c.CommonInfo.Pwd) == "" { - ClearLogin(context) if context.Request.RequestURI == LoginUrl { context.Redirect(http.StatusTemporaryRedirect, LoginSuccessUrl) } return } - auth, err := context.Request.Cookie("token") + session := sessions.Default(context) + auth := session.Get(AuthName) - if err == nil { - username, password, _ := ParseBasicAuth(auth.Value) + if auth != nil { + if c.CommonInfo.KeepTime > 0 { + cookie, _ := context.Request.Cookie(SessionName) + if cookie != nil { + //important thx https://blog.csdn.net/zhanghongxia8285/article/details/107321838/ + cookie.Expires = time.Now().Add(time.Second * time.Duration(c.CommonInfo.KeepTime)) + http.SetCookie(context.Writer, cookie) + } + } + + username, password, _ := parseBasicAuth(fmt.Sprintf("%v", auth)) usernameMatch := username == c.CommonInfo.User passwordMatch := password == c.CommonInfo.Pwd @@ -42,11 +53,40 @@ func (c *HandleController) BasicAuth() gin.HandlerFunc { } } -func ParseBasicAuth(auth string) (username, password string, ok bool) { - if len(auth) < len(AuthPrefix) || auth[:len(AuthPrefix)] != AuthPrefix { - return "", "", false +func (c *HandleController) LoginAuth(username, password string, context *gin.Context) bool { + if strings.TrimSpace(c.CommonInfo.User) == "" || strings.TrimSpace(c.CommonInfo.Pwd) == "" { + return true } - c, err := base64.StdEncoding.DecodeString(auth[len(AuthPrefix):]) + + session := sessions.Default(context) + + sessionAuth := session.Get(AuthName) + internalAuth := encodeBasicAuth(c.CommonInfo.User, c.CommonInfo.Pwd) + + if sessionAuth == internalAuth { + return true + } else { + basicAuth := encodeBasicAuth(username, password) + if basicAuth == internalAuth { + session.Set(AuthName, basicAuth) + _ = session.Save() + return true + } else { + session.Delete(AuthName) + _ = session.Save() + return false + } + } +} + +func ClearAuth(context *gin.Context) { + session := sessions.Default(context) + session.Delete(AuthName) + _ = session.Save() +} + +func parseBasicAuth(auth string) (username, password string, ok bool) { + c, err := base64.StdEncoding.DecodeString(auth) if err != nil { return "", "", false } @@ -58,11 +98,7 @@ func ParseBasicAuth(auth string) (username, password string, ok bool) { return username, password, true } -func EncodeBasicAuth(username, password string) string { +func encodeBasicAuth(username, password string) string { authString := fmt.Sprintf("%s:%s", username, password) - return AuthPrefix + base64.StdEncoding.EncodeToString([]byte(authString)) -} - -func ClearLogin(context *gin.Context) { - context.SetCookie("token", "", -1, "/", context.Request.Host, false, false) + return base64.StdEncoding.EncodeToString([]byte(authString)) } diff --git a/pkg/server/controller/controller.go b/pkg/server/controller/controller.go index 8b59de9..77b8db5 100644 --- a/pkg/server/controller/controller.go +++ b/pkg/server/controller/controller.go @@ -2,7 +2,6 @@ package controller import ( "crypto/tls" - "encoding/base64" "encoding/json" "errors" "fmt" @@ -17,10 +16,6 @@ import ( "strings" ) -func (e *HTTPError) Error() string { - return e.Err.Error() -} - func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc { return func(context *gin.Context) { var response plugin.Response @@ -28,19 +23,13 @@ func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc { request := plugin.Request{} if err := context.BindJSON(&request); err != nil { - _ = context.Error(&HTTPError{ - Code: http.StatusBadRequest, - Err: err, - }) + _ = context.AbortWithError(http.StatusBadRequest, err) return } jsonStr, err := json.Marshal(request.Content) if err != nil { - _ = context.Error(&HTTPError{ - Code: http.StatusBadRequest, - Err: err, - }) + _ = context.AbortWithError(http.StatusBadRequest, err) return } @@ -88,8 +77,7 @@ func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc { func (c *HandleController) MakeLoginFunc() func(context *gin.Context) { return func(context *gin.Context) { if context.Request.Method == "GET" { - if strings.TrimSpace(c.CommonInfo.User) == "" || strings.TrimSpace(c.CommonInfo.Pwd) == "" { - ClearLogin(context) + if c.LoginAuth("", "", context) { if context.Request.RequestURI == LoginUrl { context.Redirect(http.StatusTemporaryRedirect, LoginSuccessUrl) } @@ -107,19 +95,15 @@ func (c *HandleController) MakeLoginFunc() func(context *gin.Context) { } else if context.Request.Method == "POST" { username := context.PostForm("username") password := context.PostForm("password") - - auth := EncodeBasicAuth(username, password) - if auth == EncodeBasicAuth(c.CommonInfo.User, c.CommonInfo.Pwd) { + if c.LoginAuth(username, password, context) { context.JSON(http.StatusOK, gin.H{ "success": true, "message": ginI18n.MustGetMessage(context, "Login success"), - "token": auth, }) } else { context.JSON(http.StatusOK, gin.H{ "success": false, "message": ginI18n.MustGetMessage(context, "Username or password incorrect"), - "token": "", }) } } @@ -128,7 +112,8 @@ func (c *HandleController) MakeLoginFunc() func(context *gin.Context) { func (c *HandleController) MakeLogoutFunc() func(context *gin.Context) { return func(context *gin.Context) { - ClearLogin(context) + ClearAuth(context) + context.Redirect(http.StatusTemporaryRedirect, LogoutSuccessUrl) } } @@ -681,12 +666,10 @@ func (c *HandleController) MakeProxyFunc() func(context *gin.Context) { requestUrl := protocol + host + ":" + strconv.Itoa(port) + context.Param("serverApi") request, _ := http.NewRequest("GET", requestUrl, nil) username := c.CommonInfo.DashboardUser - if len(strings.TrimSpace(username)) != 0 { - password := c.CommonInfo.DashboardPwd - userAndPwd := []byte(username + ":" + password) - authorization := "Basic " + base64.StdEncoding.EncodeToString(userAndPwd) - request.Header.Add("Authorization", authorization) - log.Printf("Proxy to %s with Authorization %s", requestUrl, authorization) + password := c.CommonInfo.DashboardPwd + if len(strings.TrimSpace(username)) != 0 && len(strings.TrimSpace(password)) != 0 { + request.SetBasicAuth(username, password) + log.Printf("Proxy to %s", requestUrl) } response, err := client.Do(request) diff --git a/pkg/server/controller/variables.go b/pkg/server/controller/variables.go index 458855c..18eee94 100644 --- a/pkg/server/controller/variables.go +++ b/pkg/server/controller/variables.go @@ -1,6 +1,8 @@ package controller -import "regexp" +import ( + "regexp" +) const ( Success = 0 @@ -11,10 +13,12 @@ const ( TokenFormatError = 5 FrpServerError = 6 - AuthPrefix = "Basic " - LoginUrl = "/login" - LogoutUrl = "/logout" - LoginSuccessUrl = "/" + SessionName = "GOSESSION" + AuthName = "_PANEL_AUTH" + LoginUrl = "/login" + LoginSuccessUrl = "/" + LogoutUrl = "/logout" + LogoutSuccessUrl = "/login" ) var ( @@ -38,6 +42,7 @@ type CommonInfo struct { PluginPort int User string Pwd string + KeepTime int DashboardTLS bool DashboardAddr string DashboardPort int @@ -95,3 +100,7 @@ type TokenDisable struct { type TokenEnable struct { TokenDisable } + +func (e *HTTPError) Error() string { + return e.Err.Error() +} diff --git a/pkg/server/server.go b/pkg/server/server.go index 581b98a..b9ee940 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -7,6 +7,8 @@ import ( "fmt" "frps-panel/pkg/server/controller" ginI18n "github.com/gin-contrib/i18n" + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" "golang.org/x/text/language" "log" @@ -171,6 +173,15 @@ func GinI18nLocalize(rootDir string) gin.HandlerFunc { func (s *Server) initHTTPServer() error { gin.SetMode(gin.ReleaseMode) engine := gin.New() + authStore := cookie.NewStore([]byte("frps-panel")) + authStore.Options(sessions.Options{ + Secure: true, + HttpOnly: false, + SameSite: 4, + Path: "/", + MaxAge: s.cfg.CommonInfo.KeepTime, + }) + engine.Use(sessions.Sessions(controller.SessionName, authStore)) engine.Use(GinI18nLocalize(s.rootDir)) s.s = &http.Server{ Handler: engine,