Files
EdgeAdmin/internal/web/helpers/user_should_auth.go

70 lines
2.0 KiB
Go
Raw Normal View History

2020-07-22 22:19:39 +08:00
package helpers
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configloaders"
2020-12-07 11:45:45 +08:00
teaconst "github.com/TeaOSLab/EdgeAdmin/internal/const"
2020-11-10 20:30:47 +08:00
"github.com/TeaOSLab/EdgeAdmin/internal/utils/numberutils"
2023-04-09 17:10:53 +08:00
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/index/loginutils"
2020-07-22 22:19:39 +08:00
"github.com/iwind/TeaGo/actions"
"net/http"
)
type UserShouldAuth struct {
action *actions.ActionObject
}
func (this *UserShouldAuth) BeforeAction(actionPtr actions.ActionWrapper, paramName string) (goNext bool) {
2021-07-20 17:15:17 +08:00
if teaconst.IsRecoverMode {
actionPtr.Object().RedirectURL("/recover")
return false
}
2020-07-22 22:19:39 +08:00
this.action = actionPtr.Object()
2020-11-10 12:47:24 +08:00
// 安全相关
var action = this.action
securityConfig, _ := configloaders.LoadSecurityConfig()
2020-11-20 18:06:54 +08:00
if securityConfig == nil {
2020-11-10 12:47:24 +08:00
action.AddHeader("X-Frame-Options", "SAMEORIGIN")
2020-11-20 18:06:54 +08:00
} else if len(securityConfig.Frame) > 0 {
action.AddHeader("X-Frame-Options", securityConfig.Frame)
2020-11-10 12:47:24 +08:00
}
action.AddHeader("Content-Security-Policy", "default-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'")
// 检查IP
if !checkIP(securityConfig, loginutils.RemoteIP(action)) {
action.ResponseWriter.WriteHeader(http.StatusForbidden)
return false
}
// 检查请求
if !checkRequestSecurity(securityConfig, action.Request) {
action.ResponseWriter.WriteHeader(http.StatusForbidden)
return false
}
2020-07-22 22:19:39 +08:00
return true
}
2021-07-20 17:15:17 +08:00
// StoreAdmin 存储用户名到SESSION
2020-11-10 20:30:47 +08:00
func (this *UserShouldAuth) StoreAdmin(adminId int64, remember bool) {
2023-04-09 17:10:53 +08:00
loginutils.SetCookie(this.action, remember)
var session = this.action.Session()
session.Write("adminId", numberutils.FormatInt64(adminId))
session.Write("@fingerprint", loginutils.CalculateClientFingerprint(this.action))
session.Write("@ip", loginutils.RemoteIP(this.action))
2020-07-22 22:19:39 +08:00
}
func (this *UserShouldAuth) IsUser() bool {
return this.action.Session().GetInt("adminId") > 0
}
func (this *UserShouldAuth) AdminId() int {
return this.action.Session().GetInt("adminId")
}
func (this *UserShouldAuth) Logout() {
2023-04-09 17:10:53 +08:00
loginutils.UnsetCookie(this.action)
2020-07-22 22:19:39 +08:00
this.action.Session().Delete()
}