Files
yunzerwebsiteallinone/go/services/auth/session.go
T
2026-11-16 17:22:50 +08:00

233 lines
5.2 KiB
Go

package auth
import (
"crypto/rand"
"encoding/hex"
"time"
"server/models"
)
const (
DefaultSessionTTL = 7200
DefaultMaxSession = 1
)
type TenantSessionPolicy struct {
SessionTTL int
MaxSession int
KickStrategy int8
}
func GetTenantSessionPolicy(tid uint64) TenantSessionPolicy {
policy := TenantSessionPolicy{
SessionTTL: DefaultSessionTTL,
MaxSession: DefaultMaxSession,
KickStrategy: models.KickStrategyKickOld,
}
var cfg models.AuthTenantAuthConfig
if err := models.Orm.QueryTable(new(models.AuthTenantAuthConfig)).
Filter("tid", tid).One(&cfg); err != nil {
return policy
}
if cfg.SessionTTL > 0 {
policy.SessionTTL = cfg.SessionTTL
}
if cfg.MaxSession > 0 {
policy.MaxSession = cfg.MaxSession
}
if cfg.KickStrategy == models.KickStrategyReject {
policy.KickStrategy = models.KickStrategyReject
}
return policy
}
type SessionInfo struct {
IdentityID uint64
Tid uint64
ClientID string
DeviceID string
DeviceName string
IP string
UserAgent string
LoginType string
Amr string
}
func CreateSession(info SessionInfo) (*models.AuthSession, error) {
policy := GetTenantSessionPolicy(info.Tid)
var actives []models.AuthSession
if _, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("identity_id", info.IdentityID).
Filter("revoked", 0).
OrderBy("login_at").
All(&actives); err != nil {
return nil, err
}
now := time.Now()
valid := make([]models.AuthSession, 0, len(actives))
for _, s := range actives {
if s.ExpiresAt.Before(now) {
_ = RevokeSession(s.Sid, models.RevokeReasonExpired)
continue
}
valid = append(valid, s)
}
if len(valid) >= policy.MaxSession {
if policy.KickStrategy == models.KickStrategyReject {
return nil, ErrSessionLimitExceeded
}
kick := len(valid) - policy.MaxSession + 1
for i := 0; i < kick && i < len(valid); i++ {
_ = RevokeSession(valid[i].Sid, models.RevokeReasonKicked)
}
}
sid, err := randomToken(32)
if err != nil {
return nil, err
}
ttl := time.Duration(policy.SessionTTL) * time.Second
s := &models.AuthSession{
Sid: sid,
IdentityID: info.IdentityID,
Tid: info.Tid,
ClientID: info.ClientID,
LoginType: orDefault(info.LoginType, "password"),
LoginAt: now,
LastAccessAt: now,
ExpiresAt: now.Add(ttl),
}
if info.DeviceID != "" {
s.DeviceID = &info.DeviceID
}
if info.DeviceName != "" {
s.DeviceName = &info.DeviceName
}
if info.IP != "" {
s.IP = &info.IP
}
if info.UserAgent != "" {
s.UserAgent = &info.UserAgent
}
if info.Amr != "" {
s.Amr = &info.Amr
}
if _, err := models.Orm.Insert(s); err != nil {
return nil, err
}
return s, nil
}
func ReuseSession(info SessionInfo) (*models.AuthSession, error) {
var list []models.AuthSession
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("identity_id", info.IdentityID).
Filter("tid", info.Tid).
Filter("revoked", 0).
OrderBy("-login_at").
All(&list)
if err == nil {
now := time.Now()
var fallback *models.AuthSession
for i := range list {
if !list[i].ExpiresAt.After(now) {
continue
}
if list[i].ClientID == info.ClientID {
_ = TouchSession(list[i].Sid)
return &list[i], nil
}
if fallback == nil {
fallback = &list[i]
}
}
if fallback != nil {
_ = TouchSession(fallback.Sid)
return fallback, nil
}
}
return CreateSession(info)
}
func GetSession(sid string) (*models.AuthSession, error) {
var s models.AuthSession
if err := models.Orm.QueryTable(new(models.AuthSession)).Filter("sid", sid).One(&s); err != nil {
return nil, err
}
if s.Revoked != 0 {
return nil, ErrSessionRevoked
}
if s.ExpiresAt.Before(time.Now()) {
return nil, ErrSessionExpired
}
return &s, nil
}
func TouchSession(sid string) error {
last := time.Now()
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("sid", sid).
Update(map[string]interface{}{"last_access_at": last})
return err
}
func SwitchSessionTenant(sid string, tid uint64) error {
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("sid", sid).
Update(map[string]interface{}{"tid": tid})
return err
}
func RevokeSession(sid, reason string) error {
now := time.Now()
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("sid", sid).
Update(map[string]interface{}{
"revoked": 1,
"revoke_reason": reason,
"revoke_at": now,
})
return err
}
func RevokeAllSessions(identityID uint64, reason string) error {
now := time.Now()
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("identity_id", identityID).
Filter("revoked", 0).
Update(map[string]interface{}{
"revoked": 1,
"revoke_reason": reason,
"revoke_at": now,
})
return err
}
func ListActiveSessions(identityID uint64) ([]models.AuthSession, error) {
var list []models.AuthSession
_, err := models.Orm.QueryTable(new(models.AuthSession)).
Filter("identity_id", identityID).
Filter("revoked", 0).
OrderBy("-login_at").
All(&list)
return list, err
}
func randomToken(n int) (string, error) {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
func orDefault(v, def string) string {
if v == "" {
return def
}
return v
}