Initial clear old sessions implementation

This commit is contained in:
max 2023-04-04 14:37:36 -05:00
parent 242029f2e5
commit ec9c1a8fb5
2 changed files with 25 additions and 4 deletions

View File

@ -53,6 +53,12 @@ func main() {
} }
} }
// Assign and run scheduled tasks
appLoaded.ScheduledTasks = app.Scheduled{
EveryReboot: []func(app *app.App){models.ScheduledSessionCleanup},
EveryMinute: []func(app *app.App){models.ScheduledSessionCleanup},
}
// Define Routes // Define Routes
routes.GetRoutes(&appLoaded) routes.GetRoutes(&appLoaded)
routes.PostRoutes(&appLoaded) routes.PostRoutes(&appLoaded)
@ -70,6 +76,8 @@ func main() {
// Wait for interrupt signal and shut down the server // Wait for interrupt signal and shut down the server
interrupt := make(chan os.Signal, 1) interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
stop := make(chan struct{})
go app.RunScheduledTasks(&appLoaded, 100, stop)
<-interrupt <-interrupt
log.Println("Interrupt signal received. Shutting down server...") log.Println("Interrupt signal received. Shutting down server...")

View File

@ -25,6 +25,7 @@ const (
selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)" selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3) RETURNING \"Id\"" insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3) RETURNING \"Id\""
deleteSessionByAuthToken = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1" deleteSessionByAuthToken = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
deleteSessionsOlderThan30Days = "DELETE FROM " + sessionTable + " WHERE \"CreatedAt\" < NOW() - INTERVAL '30 days'"
) )
// CreateSession creates a new session for a user // CreateSession creates a new session for a user
@ -112,3 +113,15 @@ func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken str
return nil return nil
} }
// ScheduledSessionCleanup deletes expired sessions from the database
func ScheduledSessionCleanup(app *app.App) {
// Delete sessions older than 30 days
_, err := app.Db.Exec(deleteSessionsOlderThan30Days)
if err != nil {
log.Println("Error deleting expired sessions from database")
log.Println(err)
}
log.Println("Deleted expired sessions from database")
}