86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
package server
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-redis/redis"
|
|
)
|
|
|
|
func (r *RedisRouter) StoreInvitation(invitation []byte, timeout int, password string, serverTimeout int, urlLen int) (string, time.Time, error) {
|
|
id, err := r.createShortId(urlLen)
|
|
if err != nil {
|
|
return "", time.Time{}, fmt.Errorf("failed to create invitation ID: %w", err)
|
|
}
|
|
if timeout > serverTimeout {
|
|
timeout = serverTimeout
|
|
}
|
|
r.Client.Set("mwiv:"+id, invitation, 0) //, time.Duration(timeout*1000000))
|
|
if len(password) > 0 {
|
|
r.Client.Set("mwpw:"+id, password, 0) //, time.Duration(timeout*1000000))
|
|
}
|
|
return id, time.Now().Add(time.Duration(timeout * 1000000)).UTC(), nil
|
|
}
|
|
|
|
func (r *RedisRouter) GetInvitation(id string, password string) ([]byte, error) {
|
|
passRequired := false
|
|
expectedpass, err := r.Client.Get("mwpw:" + id).Result()
|
|
if err != nil {
|
|
passRequired = false
|
|
} else {
|
|
passRequired = true
|
|
}
|
|
if passRequired && password != expectedpass {
|
|
return nil, errors.New("auth failed")
|
|
}
|
|
mwiv, err := r.Client.Get("mwiv:" + id).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return []byte(mwiv), nil
|
|
}
|
|
|
|
func (r *RedisRouter) StoreAnswerToInvitation(id string, timeout int, invitation []byte, serverTimeout int) time.Time {
|
|
if timeout > serverTimeout {
|
|
timeout = serverTimeout
|
|
}
|
|
r.Client.Set("mwan:"+id, invitation, time.Duration(timeout*1000000))
|
|
return time.Now().Add(time.Duration(timeout * 1000000)).UTC()
|
|
}
|
|
|
|
func (r *RedisRouter) GetAnswerToInvitation(id string) ([]byte, error) {
|
|
mwan, err := r.Client.Get("mwan:" + id).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return []byte(mwan), nil
|
|
}
|
|
|
|
func (r *RedisRouter) createShortId(length int) (string, error) {
|
|
alphabet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
alphabetLen := big.NewInt(int64(len(alphabet)))
|
|
|
|
// for not in redis
|
|
for {
|
|
var id strings.Builder
|
|
id.Grow(length)
|
|
|
|
for i := 0; i < length; i++ {
|
|
n, err := rand.Int(rand.Reader, alphabetLen)
|
|
if err != nil {
|
|
return "", fmt.Errorf("random generation failed: %w", err)
|
|
}
|
|
id.WriteByte(alphabet[n.Int64()])
|
|
}
|
|
|
|
idStr := id.String()
|
|
if r.Client.Get("mwiv:"+idStr).Err() == redis.Nil {
|
|
return idStr, nil
|
|
}
|
|
}
|
|
}
|