Skip to content

Commit

Permalink
Move randomString to main
Browse files Browse the repository at this point in the history
  • Loading branch information
SamuelWei committed Jan 2, 2025
1 parent 0243331 commit c037cb0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
26 changes: 3 additions & 23 deletions room-hub/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,20 @@ package main

import (
"context"
"crypto/rand"
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"log"
"math/big"
"time"
)

const pinRotationInterval = 10 // Interval in seconds

const Digits string = "0123456789"
const ASCIILettersUppercase string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

// generate a random string of given length from a given character set
func randomString(length int, characterSet string) (string, error) {
var generatedString = ""
for j := 0; j < length; j++ {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(characterSet))))
if err != nil {
log.Printf("failed to generate random string: %s", err)
return "", err
}
generatedString += string(characterSet[n.Int64()])
}
return generatedString, nil
func generateVerificationCode() (string, error) {
const length int = 4
return randomString(length, ASCIILettersUppercase+Digits)
}

// Struct to store room connection and configuration
type Room struct {
Id string
Conn *websocket.Conn
Expand Down Expand Up @@ -58,11 +43,6 @@ func (room *Room) getPlugin() *Plugin {
return connManager.getPlugin(room.PluginID)
}

func generateVerificationCode() (string, error) {
const length int = 4
return randomString(length, ASCIILettersUppercase+Digits)
}

func (room *Room) rotatePIN() bool {
// Generate a new PIN
newPIN, err := connManager.generatePIN()
Expand Down
19 changes: 19 additions & 0 deletions room-hub/server.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package main

import (
"crypto/rand"
"encoding/json"
"github.com/go-playground/validator/v10"
"github.com/gorilla/websocket"
"log"
"math/big"
"net/http"
"os"
)
Expand All @@ -25,6 +27,23 @@ var connManager = &ConnectionManager{
pinToRoom: make(map[string]string),
}

// generate a random string of given length from a given character set
const Digits string = "0123456789"
const ASCIILettersUppercase string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

func randomString(length int, characterSet string) (string, error) {
var generatedString = ""
for j := 0; j < length; j++ {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(characterSet))))
if err != nil {
log.Printf("failed to generate random string: %s", err)
return "", err
}
generatedString += string(characterSet[n.Int64()])
}
return generatedString, nil
}

func roomHandler(w http.ResponseWriter, r *http.Request) {
roomConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
Expand Down

0 comments on commit c037cb0

Please sign in to comment.