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

71 lines
1.7 KiB
Go
Raw Normal View History

2020-07-22 22:19:39 +08:00
package helpers
import (
2020-11-10 12:47:24 +08:00
teaconst "github.com/TeaOSLab/EdgeAdmin/internal/const"
2020-11-10 20:30:47 +08:00
"github.com/TeaOSLab/EdgeAdmin/internal/utils/numberutils"
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) {
this.action = actionPtr.Object()
2020-11-10 12:47:24 +08:00
// 安全相关
action := this.action
if !teaconst.EnabledFrame {
action.AddHeader("X-Frame-Options", "SAMEORIGIN")
}
action.AddHeader("Content-Security-Policy", "default-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'")
2020-07-22 22:19:39 +08:00
return true
}
// 存储用户名到SESSION
2020-11-10 20:30:47 +08:00
func (this *UserShouldAuth) StoreAdmin(adminId int64, remember bool) {
2020-07-22 22:19:39 +08:00
// 修改sid的时间
if remember {
cookie := &http.Cookie{
2020-11-10 12:47:24 +08:00
Name: "sid",
Value: this.action.Session().Sid,
Path: "/",
MaxAge: 14 * 86400,
HttpOnly: true,
}
if this.action.Request.TLS != nil {
cookie.SameSite = http.SameSiteStrictMode
cookie.Secure = true
2020-07-22 22:19:39 +08:00
}
this.action.AddCookie(cookie)
} else {
cookie := &http.Cookie{
2020-11-10 12:47:24 +08:00
Name: "sid",
Value: this.action.Session().Sid,
Path: "/",
MaxAge: 0,
HttpOnly: true,
}
if this.action.Request.TLS != nil {
cookie.SameSite = http.SameSiteStrictMode
cookie.Secure = true
2020-07-22 22:19:39 +08:00
}
this.action.AddCookie(cookie)
}
2020-11-10 20:30:47 +08:00
this.action.Session().Write("adminId", numberutils.FormatInt64(adminId))
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() {
this.action.Session().Delete()
}