keypair err mgt + shorturl random improve
This commit is contained in:
@@ -1,15 +1,21 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"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) {
|
||||
id := r.createShortId(urlLen)
|
||||
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
|
||||
}
|
||||
@@ -17,7 +23,7 @@ func (r *RedisRouter) StoreInvitation(invitation []byte, timeout int, password s
|
||||
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()
|
||||
return id, time.Now().Add(time.Duration(timeout * 1000000)).UTC(), nil
|
||||
}
|
||||
|
||||
func (r *RedisRouter) GetInvitation(id string, password string) ([]byte, error) {
|
||||
@@ -54,17 +60,26 @@ func (r *RedisRouter) GetAnswerToInvitation(id string) ([]byte, error) {
|
||||
return []byte(mwan), nil
|
||||
}
|
||||
|
||||
func (r *RedisRouter) createShortId(length int) string {
|
||||
id := ""
|
||||
func (r *RedisRouter) createShortId(length int) (string, error) {
|
||||
alphabet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
alphabetLen := big.NewInt(int64(len(alphabet)))
|
||||
|
||||
// for not in redis
|
||||
for {
|
||||
for i := 1; i <= length; i++ {
|
||||
id += string(alphabet[rand.Intn(61)])
|
||||
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()])
|
||||
}
|
||||
if r.Client.Get("mwiv:"+id).Err() == redis.Nil {
|
||||
break
|
||||
|
||||
idStr := id.String()
|
||||
if r.Client.Get("mwiv:"+idStr).Err() == redis.Nil {
|
||||
return idStr, nil
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user