60 lines
1.6 KiB
Go
60 lines
1.6 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.ewellenr.ca/receipt_indexer/backend/internal/lcrypto"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// game plan. store the session token/id and a salt. then, hash them to create the csrf token. give this csrf token out to the user. when the user ends a session, it ends the session but also deletes it from the csrf store
|
|
|
|
// const csrfSaltLength = 32
|
|
// const csrfTokenLength = 128
|
|
|
|
// should be set by the hasher
|
|
|
|
type RedisSessionStore struct {
|
|
rdb *redis.Client
|
|
sessionTokenLength uint
|
|
expirationTime uint
|
|
}
|
|
|
|
func (r *RedisSessionStore) AddSession(ctx context.Context, userid int64) (token string, err error) {
|
|
temp, err := lcrypto.GenerateRandomBytes(r.sessionTokenLength)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
token = string(temp)
|
|
err = r.rdb.Set(ctx, token, userid, time.Duration(r.expirationTime)).Err()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return token, err
|
|
}
|
|
|
|
func (r *RedisSessionStore) GetSession(ctx context.Context, token string) (valid bool, userid int64, err error) { // should also extend it by the lifespan if near the end of the time. maybe a 5 min window at the end?
|
|
userid, err = r.rdb.Get(ctx, token).Int64()
|
|
if err == redis.Nil {
|
|
valid = false
|
|
userid = -1
|
|
} else if err != nil {
|
|
return false, -1, err
|
|
} else {
|
|
valid = true
|
|
}
|
|
|
|
err = r.rdb.ExpireXX(ctx, token, time.Duration(r.expirationTime)).Err()
|
|
if err != nil {
|
|
return false, -1, err
|
|
}
|
|
|
|
return valid, userid, err
|
|
}
|
|
|
|
func (r *RedisSessionStore) RemoveSession(ctx context.Context, token string) error {
|
|
return r.rdb.Del(ctx, token).Err()
|
|
}
|