Files
EdgeAdmin/internal/nodes/session_manager.go

98 lines
2.2 KiB
Go
Raw Normal View History

2023-02-04 15:18:26 +08:00
// Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package nodes
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/rpc"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/logs"
2023-02-04 16:44:33 +08:00
"strings"
2023-02-04 15:18:26 +08:00
)
2023-04-09 17:10:53 +08:00
// SessionManager SESSION管理
2023-02-04 15:18:26 +08:00
type SessionManager struct {
2023-03-04 09:34:10 +08:00
life uint
2023-02-04 15:18:26 +08:00
}
func NewSessionManager() (*SessionManager, error) {
2023-03-04 09:34:10 +08:00
return &SessionManager{}, nil
2023-02-04 15:18:26 +08:00
}
func (this *SessionManager) Init(config *actions.SessionConfig) {
this.life = config.Life
}
func (this *SessionManager) Read(sid string) map[string]string {
2023-02-04 16:44:33 +08:00
// 忽略OTP
if strings.HasSuffix(sid, "_otp") {
return map[string]string{}
}
2023-02-04 15:18:26 +08:00
var result = map[string]string{}
2023-03-04 09:34:10 +08:00
rpcClient, err := rpc.SharedRPC()
if err != nil {
return map[string]string{}
}
resp, err := rpcClient.LoginSessionRPC().FindLoginSession(rpcClient.Context(0), &pb.FindLoginSessionRequest{Sid: sid})
2023-02-04 15:18:26 +08:00
if err != nil {
logs.Println("SESSION", "read '"+sid+"' failed: "+err.Error())
return result
}
var session = resp.LoginSession
if session == nil || len(session.ValuesJSON) == 0 {
return result
}
err = json.Unmarshal(session.ValuesJSON, &result)
if err != nil {
logs.Println("SESSION", "decode '"+sid+"' values failed: "+err.Error())
}
return result
}
func (this *SessionManager) WriteItem(sid string, key string, value string) bool {
2023-02-04 16:44:33 +08:00
// 忽略OTP
if strings.HasSuffix(sid, "_otp") {
return false
}
2023-03-04 09:34:10 +08:00
rpcClient, err := rpc.SharedRPC()
if err != nil {
return false
}
_, err = rpcClient.LoginSessionRPC().WriteLoginSessionValue(rpcClient.Context(0), &pb.WriteLoginSessionValueRequest{
2023-02-04 15:18:26 +08:00
Sid: sid,
Key: key,
Value: value,
})
if err != nil {
logs.Println("SESSION", "write sid:'"+sid+"' key:'"+key+"' failed: "+err.Error())
}
return true
}
func (this *SessionManager) Delete(sid string) bool {
2023-02-04 16:44:33 +08:00
// 忽略OTP
if strings.HasSuffix(sid, "_otp") {
return false
}
2023-03-04 09:34:10 +08:00
rpcClient, err := rpc.SharedRPC()
if err != nil {
return false
}
_, err = rpcClient.LoginSessionRPC().DeleteLoginSession(rpcClient.Context(0), &pb.DeleteLoginSessionRequest{Sid: sid})
2023-02-04 15:18:26 +08:00
if err != nil {
logs.Println("SESSION", "delete '"+sid+"' failed: "+err.Error())
}
return true
}