feat: 修改路由中间件

pull/5993/head
ssongliu 2024-07-25 18:13:57 +08:00
parent fafa042ee9
commit c0b39ffcbf
13 changed files with 66 additions and 42 deletions

View File

@ -84,6 +84,12 @@ var InitHost = &gormigrate.Migration{
var InitSetting = &gormigrate.Migration{ var InitSetting = &gormigrate.Migration{
ID: "20240722-init-setting", ID: "20240722-init-setting",
Migrate: func(tx *gorm.DB) error { Migrate: func(tx *gorm.DB) error {
encryptKey := common.RandStr(16)
global.CONF.System.EncryptKey = encryptKey
if err := tx.Create(&model.Setting{Key: "EncryptKey", Value: encryptKey}).Error; err != nil {
return err
}
if err := tx.Create(&model.Setting{Key: "SystemIP", Value: ""}).Error; err != nil { if err := tx.Create(&model.Setting{Key: "SystemIP", Value: ""}).Error; err != nil {
return err return err
} }

View File

@ -46,4 +46,5 @@ var (
ErrTypePasswordExpired = "ErrPasswordExpired" ErrTypePasswordExpired = "ErrPasswordExpired"
ErrDemoEnvironment = "ErrDemoEnvironment" ErrDemoEnvironment = "ErrDemoEnvironment"
ErrEntrance = "ErrEntrance" ErrEntrance = "ErrEntrance"
ErrProxy = "ErrProxy"
) )

View File

@ -8,6 +8,7 @@ ErrTransform: "Type conversion failure: {{ .detail }}"
ErrNotLogin: "User is not Login: {{ .detail }}" ErrNotLogin: "User is not Login: {{ .detail }}"
ErrPasswordExpired: "The current password has expired: {{ .detail }}" ErrPasswordExpired: "The current password has expired: {{ .detail }}"
ErrNotSupportType: "The system does not support the current type: {{ .detail }}" ErrNotSupportType: "The system does not support the current type: {{ .detail }}"
ErrProxy: "Request error, please check the node status"
#common #common
ErrNameIsExist: "Name is already exist" ErrNameIsExist: "Name is already exist"

View File

@ -8,6 +8,7 @@ ErrTransform: "類型轉換失敗: {{ .detail }}"
ErrNotLogin: "用戶未登入: {{ .detail }}" ErrNotLogin: "用戶未登入: {{ .detail }}"
ErrPasswordExpired: "當前密碼已過期: {{ .detail }}" ErrPasswordExpired: "當前密碼已過期: {{ .detail }}"
ErrNotSupportType: "系統暫不支持當前類型: {{ .detail }}" ErrNotSupportType: "系統暫不支持當前類型: {{ .detail }}"
ErrProxy: "請求錯誤,請檢查該節點狀態"
#common #common
ErrNameIsExist: "名稱已存在" ErrNameIsExist: "名稱已存在"

View File

@ -8,6 +8,7 @@ ErrTransform: "类型转换失败: {{ .detail }}"
ErrNotLogin: "用户未登录: {{ .detail }}" ErrNotLogin: "用户未登录: {{ .detail }}"
ErrPasswordExpired: "当前密码已过期: {{ .detail }}" ErrPasswordExpired: "当前密码已过期: {{ .detail }}"
ErrNotSupportType: "系统暂不支持当前类型: {{ .detail }}" ErrNotSupportType: "系统暂不支持当前类型: {{ .detail }}"
ErrProxy: "请求错误,请检查该节点状态"
#common #common
ErrDemoEnvironment: "演示服务器,禁止此操作!" ErrDemoEnvironment: "演示服务器,禁止此操作!"

View File

@ -39,13 +39,7 @@ func setWebStatic(rootRouter *gin.RouterGroup) {
func Routers() *gin.Engine { func Routers() *gin.Engine {
Router = gin.Default() Router = gin.Default()
Router.Use(middleware.OperationLog())
if global.CONF.System.IsDemo {
Router.Use(middleware.DemoHandle())
}
Router.Use(i18n.UseI18n()) Router.Use(i18n.UseI18n())
Router.Use(middleware.Proxy())
swaggerRouter := Router.Group("1panel") swaggerRouter := Router.Group("1panel")
docs.SwaggerInfo.BasePath = "/api/v1" docs.SwaggerInfo.BasePath = "/api/v1"
@ -58,6 +52,15 @@ func Routers() *gin.Engine {
PublicGroup.Use(gzip.Gzip(gzip.DefaultCompression)) PublicGroup.Use(gzip.Gzip(gzip.DefaultCompression))
setWebStatic(PublicGroup) setWebStatic(PublicGroup)
} }
Router.Use(middleware.OperationLog())
if global.CONF.System.IsDemo {
Router.Use(middleware.DemoHandle())
}
Router.Use(middleware.JwtAuth())
Router.Use(middleware.SessionAuth())
Router.Use(middleware.PasswordExpired())
Router.Use(middleware.Proxy())
PrivateGroup := Router.Group("/api/v2/core") PrivateGroup := Router.Group("/api/v2/core")
PrivateGroup.Use(middleware.WhiteAllow()) PrivateGroup.Use(middleware.WhiteAllow())
PrivateGroup.Use(middleware.BindDomain()) PrivateGroup.Use(middleware.BindDomain())

View File

@ -1,6 +1,8 @@
package middleware package middleware
import ( import (
"strings"
"github.com/1Panel-dev/1Panel/core/app/api/v1/helper" "github.com/1Panel-dev/1Panel/core/app/api/v1/helper"
"github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/constant"
jwtUtils "github.com/1Panel-dev/1Panel/core/utils/jwt" jwtUtils "github.com/1Panel-dev/1Panel/core/utils/jwt"
@ -10,6 +12,10 @@ import (
func JwtAuth() gin.HandlerFunc { func JwtAuth() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") {
c.Next()
return
}
token := c.Request.Header.Get(constant.JWTHeaderName) token := c.Request.Header.Get(constant.JWTHeaderName)
if token == "" { if token == "" {
c.Next() c.Next()

View File

@ -2,6 +2,7 @@ package middleware
import ( import (
"strconv" "strconv"
"strings"
"time" "time"
"github.com/1Panel-dev/1Panel/core/app/api/v1/helper" "github.com/1Panel-dev/1Panel/core/app/api/v1/helper"
@ -13,6 +14,12 @@ import (
func PasswordExpired() gin.HandlerFunc { func PasswordExpired() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") ||
c.Request.URL.Path == "/api/v2/core/settings/expired/handle" ||
c.Request.URL.Path == "/api/v2/core/settings/search" {
c.Next()
return
}
settingRepo := repo.NewISettingRepo() settingRepo := repo.NewISettingRepo()
setting, err := settingRepo.Get(settingRepo.WithByKey("ExpirationDays")) setting, err := settingRepo.Get(settingRepo.WithByKey("ExpirationDays"))
if err != nil { if err != nil {

View File

@ -8,6 +8,8 @@ import (
"os" "os"
"strings" "strings"
"github.com/1Panel-dev/1Panel/core/app/api/v1/helper"
"github.com/1Panel-dev/1Panel/core/constant"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -16,28 +18,28 @@ func Proxy() gin.HandlerFunc {
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core") { if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core") {
c.Next() c.Next()
return return
} else {
sockPath := "/tmp/agent.sock"
if _, err := os.Stat(sockPath); err != nil {
panic(err)
}
dialUnix := func() (conn net.Conn, err error) {
return net.Dial("unix", sockPath)
}
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialUnix()
},
}
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = "unix"
},
Transport: transport,
}
proxy.ServeHTTP(c.Writer, c.Request)
c.Abort()
} }
sockPath := "/tmp/agent.sock"
if _, err := os.Stat(sockPath); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrProxy, err)
return
}
dialUnix := func() (conn net.Conn, err error) {
return net.Dial("unix", sockPath)
}
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialUnix()
},
}
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = "unix"
},
Transport: transport,
}
proxy.ServeHTTP(c.Writer, c.Request)
c.Abort()
} }
} }

View File

@ -2,6 +2,7 @@ package middleware
import ( import (
"strconv" "strconv"
"strings"
"github.com/1Panel-dev/1Panel/core/app/api/v1/helper" "github.com/1Panel-dev/1Panel/core/app/api/v1/helper"
"github.com/1Panel-dev/1Panel/core/app/repo" "github.com/1Panel-dev/1Panel/core/app/repo"
@ -12,6 +13,10 @@ import (
func SessionAuth() gin.HandlerFunc { func SessionAuth() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") {
c.Next()
return
}
if method, exist := c.Get("authMethod"); exist && method == constant.AuthMethodJWT { if method, exist := c.Get("authMethod"); exist && method == constant.AuthMethodJWT {
c.Next() c.Next()
return return

View File

@ -2,7 +2,6 @@ package router
import ( import (
v1 "github.com/1Panel-dev/1Panel/core/app/api/v1" v1 "github.com/1Panel-dev/1Panel/core/app/api/v1"
"github.com/1Panel-dev/1Panel/core/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -11,7 +10,6 @@ type LogRouter struct{}
func (s *LogRouter) InitRouter(Router *gin.RouterGroup) { func (s *LogRouter) InitRouter(Router *gin.RouterGroup) {
operationRouter := Router.Group("logs") operationRouter := Router.Group("logs")
operationRouter.Use(middleware.JwtAuth()).Use(middleware.SessionAuth()).Use(middleware.PasswordExpired())
baseApi := v1.ApiGroupApp.BaseApi baseApi := v1.ApiGroupApp.BaseApi
{ {
operationRouter.POST("/login", baseApi.GetLoginLogs) operationRouter.POST("/login", baseApi.GetLoginLogs)

View File

@ -2,24 +2,17 @@ package router
import ( import (
v1 "github.com/1Panel-dev/1Panel/core/app/api/v1" v1 "github.com/1Panel-dev/1Panel/core/app/api/v1"
"github.com/1Panel-dev/1Panel/core/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
type SettingRouter struct{} type SettingRouter struct{}
func (s *SettingRouter) InitRouter(Router *gin.RouterGroup) { func (s *SettingRouter) InitRouter(Router *gin.RouterGroup) {
router := Router.Group("settings"). settingRouter := Router.Group("settings")
Use(middleware.JwtAuth()).
Use(middleware.SessionAuth())
settingRouter := Router.Group("settings").
Use(middleware.JwtAuth()).
Use(middleware.SessionAuth()).
Use(middleware.PasswordExpired())
baseApi := v1.ApiGroupApp.BaseApi baseApi := v1.ApiGroupApp.BaseApi
{ {
router.POST("/search", baseApi.GetSettingInfo) settingRouter.POST("/search", baseApi.GetSettingInfo)
router.POST("/expired/handle", baseApi.HandlePasswordExpired) settingRouter.POST("/expired/handle", baseApi.HandlePasswordExpired)
settingRouter.GET("/search/available", baseApi.GetSystemAvailable) settingRouter.GET("/search/available", baseApi.GetSystemAvailable)
settingRouter.POST("/update", baseApi.UpdateSetting) settingRouter.POST("/update", baseApi.UpdateSetting)
settingRouter.GET("/interface", baseApi.LoadInterfaceAddr) settingRouter.GET("/interface", baseApi.LoadInterfaceAddr)

View File

@ -3,11 +3,11 @@ import { ResPage } from '../interface';
import { Log } from '../interface/log'; import { Log } from '../interface/log';
export const getOperationLogs = (info: Log.SearchOpLog) => { export const getOperationLogs = (info: Log.SearchOpLog) => {
return http.post<ResPage<Log.OperationLog>>(`/logs/operation`, info); return http.post<ResPage<Log.OperationLog>>(`/core/logs/operation`, info);
}; };
export const getLoginLogs = (info: Log.SearchLgLog) => { export const getLoginLogs = (info: Log.SearchLgLog) => {
return http.post<ResPage<Log.OperationLog>>(`/logs/login`, info); return http.post<ResPage<Log.OperationLog>>(`/core/logs/login`, info);
}; };
export const getSystemFiles = () => { export const getSystemFiles = () => {