Implement session cleanup

This commit is contained in:
2024-05-05 15:27:02 +07:00
parent dce11e3569
commit f1d70fc74a
3 changed files with 36 additions and 6 deletions

2
cache/user.go vendored
View File

@ -26,7 +26,7 @@ func init() {
log = logger.Logger() log = logger.Logger()
userCache = make(map[string]*UserWithExpired) userCache = make(map[string]*UserWithExpired)
ticker := time.NewTicker(time.Hour) ticker := time.NewTicker(time.Minute)
go func() { go func() {
for { for {

View File

@ -50,7 +50,7 @@ func init() {
for _, data := range VerifyUser { for _, data := range VerifyUser {
data.mu.Lock() data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute*1 { if currentTime.Sub(data.CreateTime) > time.Minute*10 {
delete(VerifyUser, data.Code) delete(VerifyUser, data.Code)
delete(VerifyEmail, data.User.Email) delete(VerifyEmail, data.User.Email)
cacheClean++ cacheClean++

View File

@ -1,6 +1,8 @@
package session package session
import ( import (
"fmt"
"github.com/fossyy/filekeeper/logger"
"github.com/fossyy/filekeeper/types" "github.com/fossyy/filekeeper/types"
"net/http" "net/http"
"strconv" "strconv"
@ -13,6 +15,7 @@ import (
type Session struct { type Session struct {
ID string ID string
Values map[string]interface{} Values map[string]interface{}
CreateTime time.Time
mu sync.Mutex mu sync.Mutex
} }
@ -28,6 +31,7 @@ type SessionInfo struct {
} }
type UserStatus string type UserStatus string
type SessionNotFoundError struct{}
const ( const (
Authorized UserStatus = "authorized" Authorized UserStatus = "authorized"
@ -37,8 +41,34 @@ const (
var GlobalSessionStore = make(map[string]*Session) var GlobalSessionStore = make(map[string]*Session)
var UserSessionInfoList = make(map[string]map[string]*SessionInfo) var UserSessionInfoList = make(map[string]map[string]*SessionInfo)
var log *logger.AggregatedLogger
type SessionNotFoundError struct{} func init() {
log = logger.Logger()
ticker := time.NewTicker(time.Minute)
go func() {
for {
<-ticker.C
currentTime := time.Now()
cacheClean := 0
cleanID := utils.GenerateRandomString(10)
log.Info(fmt.Sprintf("Cache cleanup [Session] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range GlobalSessionStore {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Hour*24*7 {
RemoveSessionInfo(data.Values["user"].(types.User).Email, data.ID)
delete(GlobalSessionStore, data.ID)
cacheClean++
}
data.mu.Unlock()
}
log.Info(fmt.Sprintf("Cache cleanup [Session] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func (e *SessionNotFoundError) Error() string { func (e *SessionNotFoundError) Error() string {
return "session not found" return "session not found"