Changes in tokens

This commit is contained in:
qowevisa 2024-08-02 23:36:31 +03:00
parent 7a54ea796e
commit 5b7daead95

View File

@ -5,6 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"errors" "errors"
"log" "log"
"strings"
"sync" "sync"
"time" "time"
) )
@ -24,8 +25,8 @@ func (t Token) IsExpired() bool {
type TokensMapMu struct { type TokensMapMu struct {
Initialized bool Initialized bool
Tokmap map[uint]Token Tokmap map[uint]*Token
TokmapRev map[string]Token TokmapRev map[string]*Token
Mu sync.RWMutex Mu sync.RWMutex
} }
@ -37,16 +38,22 @@ func StartTokens() {
if toks.Initialized { if toks.Initialized {
return return
} }
toks.Tokmap = make(map[uint]Token) toks.Tokmap = make(map[uint]*Token)
toks.TokmapRev = make(map[string]Token) toks.TokmapRev = make(map[string]*Token)
toks.Initialized = true toks.Initialized = true
for { for {
// //
toks.Mu.Lock() toks.Mu.Lock()
for id, token := range toks.Tokmap { for id, token := range toks.Tokmap {
if token.IsExpired() { if token == nil {
log.Printf("DAFUQ: 001\n")
delete(toks.Tokmap, id) delete(toks.Tokmap, id)
} }
if token.IsExpired() {
val := token.Val
delete(toks.Tokmap, id)
delete(toks.TokmapRev, val)
}
} }
toks.Mu.Unlock() toks.Mu.Unlock()
// //
@ -59,12 +66,12 @@ var (
ERROR_ALREADY_HAVE_TOKEN = errors.New("Already have token") ERROR_ALREADY_HAVE_TOKEN = errors.New("Already have token")
) )
func GetToken(id uint) (Token, error) { func GetToken(id uint) (*Token, error) {
toks.Mu.RLock() toks.Mu.RLock()
val, exists := toks.Tokmap[id] val, exists := toks.Tokmap[id]
toks.Mu.RUnlock() toks.Mu.RUnlock()
if !exists { if !exists {
return Token{}, ERROR_DONT_HAVE_TOKEN return nil, ERROR_DONT_HAVE_TOKEN
} }
return val, nil return val, nil
} }
@ -106,21 +113,28 @@ func generateRandomString(length int) string {
func generateTokenVal() string { func generateTokenVal() string {
for { for {
tok := generateRandomString(32) tok := generateRandomString(32)
if !haveTokenVal(tok) { trimedToken := strings.Trim(tok, "=")
return tok if !haveTokenVal(trimedToken) {
return trimedToken
} }
} }
} }
func AddToken(id uint) (Token, error) { func AddToken(id uint) (*Token, error) {
toks.Mu.RLock() toks.Mu.RLock()
_, exists := toks.Tokmap[id] _, exists := toks.Tokmap[id]
toks.Mu.RUnlock() toks.Mu.RUnlock()
if exists { if exists {
return Token{}, ERROR_ALREADY_HAVE_TOKEN return nil, ERROR_ALREADY_HAVE_TOKEN
} }
return Token{ val := generateTokenVal()
Val: generateTokenVal(), token := &Token{
Val: val,
LastActive: time.Now(), LastActive: time.Now(),
}, nil }
toks.Mu.Lock()
toks.Tokmap[id] = token
toks.TokmapRev[val] = token
toks.Mu.Unlock()
return token, nil
} }