2023-08-29 23:40:19 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (r *RedisRouter) CreateInvitation(invitation []byte, timeout int, password string, serverTimeout int, urlLen int) (string, time.Time) {
|
2023-08-31 23:51:20 +02:00
|
|
|
id := r.createShortId(urlLen)
|
2023-08-29 23:40:19 +02:00
|
|
|
if timeout > serverTimeout {
|
|
|
|
timeout = serverTimeout
|
|
|
|
}
|
2023-12-31 20:22:56 +01:00
|
|
|
r.Client.Set("mwiv:"+id, invitation, 0) //, time.Duration(timeout*1000000))
|
2023-08-29 23:40:19 +02:00
|
|
|
if len(password) > 0 {
|
2023-12-31 20:22:56 +01:00
|
|
|
r.Client.Set("mwpw:"+id, password, 0) //, time.Duration(timeout*1000000))
|
2023-08-29 23:40:19 +02:00
|
|
|
}
|
|
|
|
return id, time.Now().Add(time.Duration(timeout * 1000000)).UTC()
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2023-08-31 23:38:03 +02:00
|
|
|
return nil, errors.New("auth failed")
|
2023-08-29 23:40:19 +02:00
|
|
|
}
|
|
|
|
mwiv, err := r.Client.Get("mwiv:" + id).Result()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return []byte(mwiv), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RedisRouter) AnswerInvitation(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()
|
|
|
|
}
|
|
|
|
|
2023-08-30 21:16:13 +02:00
|
|
|
func (r *RedisRouter) GetInvitationAnswer(id string) ([]byte, error) {
|
2023-08-29 23:40:19 +02:00
|
|
|
mwan, err := r.Client.Get("mwiv:" + id).Result()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return []byte(mwan), nil
|
|
|
|
}
|
|
|
|
|
2023-08-31 23:51:20 +02:00
|
|
|
func (r *RedisRouter) createShortId(length int) string {
|
|
|
|
id := ""
|
2023-08-29 23:40:19 +02:00
|
|
|
alphabet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
|
|
// for not in redis
|
|
|
|
for {
|
|
|
|
for i := 1; i <= length; i++ {
|
2023-08-31 23:51:20 +02:00
|
|
|
id += string(alphabet[rand.Intn(61)])
|
2023-08-29 23:40:19 +02:00
|
|
|
}
|
2023-08-31 23:51:20 +02:00
|
|
|
if r.Client.Get("mwiv:"+id).Err() == redis.Nil {
|
2023-08-29 23:40:19 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2023-08-31 23:51:20 +02:00
|
|
|
return id
|
2023-08-29 23:40:19 +02:00
|
|
|
}
|