Skip to content

Commit

Permalink
refactor: Removing math/rand in favor of crypto/rand
Browse files Browse the repository at this point in the history
  • Loading branch information
ViBiOh committed Feb 12, 2021
1 parent cb0719c commit 8b5ce9b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
4 changes: 0 additions & 4 deletions pkg/ketchup/ketchup.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package ketchup

import (
"html/template"
"math/rand"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -35,8 +34,6 @@ type App interface {
}

type app struct {
rand *rand.Rand

rendererApp renderer.App
ketchupService ketchup.App
userService user.App
Expand All @@ -47,7 +44,6 @@ type app struct {
// New creates new App from Config
func New(rendererApp renderer.App, ketchupService ketchup.App, userService user.App, repositoryService repository.App) App {
return app{
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
tokenStore: NewTokenStore(),

rendererApp: rendererApp,
Expand Down
18 changes: 14 additions & 4 deletions pkg/ketchup/renderer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package ketchup

import (
"crypto/rand"
"fmt"
"math/big"
"net/http"
"time"

Expand All @@ -12,13 +15,20 @@ const (
suggestCount = uint64(5)
)

func (a app) generateToken() (string, int64) {
questionID := a.rand.Int63n(int64(len(colors)))
return a.tokenStore.Store(questionID, time.Minute*5), questionID
func (a app) generateToken() (string, int64, error) {
questionID, err := rand.Int(rand.Reader, big.NewInt(int64(len(colors))))
if err != nil {
return "", 0, fmt.Errorf("unable to generate random int: %w", err)
}

return a.tokenStore.Store(questionID, time.Minute*5), questionID.Int64(), nil
}

func (a app) PublicTemplateFunc(r *http.Request) (string, int, map[string]interface{}, error) {
token, questionID := a.generateToken()
token, questionID, err := a.generateToken()
if err != nil {
return "", http.StatusInternalServerError, nil, err
}

suggests, err := a.repositoryService.Suggest(r.Context(), []uint64{0}, 3)
if err != nil {
Expand Down

0 comments on commit 8b5ce9b

Please sign in to comment.