updated stuff
This commit is contained in:
46
internal/session/newlogin.go
Normal file
46
internal/session/newlogin.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.haelnorr.com/h/oslstats/internal/discord"
|
||||
"github.com/bwmarrin/discordgo"
|
||||
)
|
||||
|
||||
type RegistrationSession struct {
|
||||
DiscordUser *discordgo.User
|
||||
Token *discord.Token
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (s *Store) CreateRegistrationSession(user *discordgo.User, token *discord.Token) (string, error) {
|
||||
if user == nil {
|
||||
return "", errors.New("user cannot be nil")
|
||||
}
|
||||
if token == nil {
|
||||
return "", errors.New("token cannot be nil")
|
||||
}
|
||||
id := generateID()
|
||||
s.sessions.Store(id, &RegistrationSession{
|
||||
DiscordUser: user,
|
||||
Token: token,
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
})
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetRegistrationSession(id string) (*RegistrationSession, bool) {
|
||||
val, ok := s.sessions.Load(id)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
session := val.(*RegistrationSession)
|
||||
if time.Now().After(session.ExpiresAt) {
|
||||
s.sessions.Delete(id)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return session, true
|
||||
}
|
||||
46
internal/session/store.go
Normal file
46
internal/session/store.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
sessions sync.Map
|
||||
cleanup *time.Ticker
|
||||
}
|
||||
|
||||
func NewStore() *Store {
|
||||
s := &Store{
|
||||
cleanup: time.NewTicker(1 * time.Minute),
|
||||
}
|
||||
|
||||
// Background cleanup of expired sessions
|
||||
go func() {
|
||||
for range s.cleanup.C {
|
||||
s.cleanupExpired()
|
||||
}
|
||||
}()
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Store) Delete(id string) {
|
||||
s.sessions.Delete(id)
|
||||
}
|
||||
func (s *Store) cleanupExpired() {
|
||||
s.sessions.Range(func(key, value any) bool {
|
||||
session := value.(*RegistrationSession)
|
||||
if time.Now().After(session.ExpiresAt) {
|
||||
s.sessions.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
func generateID() string {
|
||||
b := make([]byte, 32)
|
||||
rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
Reference in New Issue
Block a user