Changed result ID's to be 7 random alphanumeric characters. Fixes #518

pull/539/merge
Jordan Wright 2017-01-27 21:16:47 -06:00
parent b3cadcb01f
commit ea7bb04156
3 changed files with 27 additions and 7 deletions

View File

@ -414,7 +414,11 @@ func PostCampaign(c *Campaign, uid int64) error {
// Insert a result for each target in the group // Insert a result for each target in the group
for _, t := range g.Targets { for _, t := range g.Targets {
r := &Result{Email: t.Email, Position: t.Position, Status: STATUS_SENDING, CampaignId: c.Id, UserId: c.UserId, FirstName: t.FirstName, LastName: t.LastName} r := &Result{Email: t.Email, Position: t.Position, Status: STATUS_SENDING, CampaignId: c.Id, UserId: c.UserId, FirstName: t.FirstName, LastName: t.LastName}
r.GenerateId() err = r.GenerateId()
if err != nil {
Logger.Println(err)
continue
}
err = db.Save(r).Error err = db.Save(r).Error
if err != nil { if err != nil {
Logger.Printf("Error adding result record for target %s\n", t.Email) Logger.Printf("Error adding result record for target %s\n", t.Email)

View File

@ -1,6 +1,7 @@
package models package models
import ( import (
"regexp"
"strings" "strings"
"testing" "testing"
@ -321,3 +322,11 @@ func (s *ModelsSuite) TestPostPage(c *check.C) {
c.Assert(ok, check.Equals, false) c.Assert(ok, check.Equals, false)
}) })
} }
func (s *ModelsSuite) TestGenerateResultId(c *check.C) {
r := Result{}
r.GenerateId()
match, err := regexp.Match("[a-zA-Z0-9]{7}", []byte(r.RId))
c.Assert(err, check.Equals, nil)
c.Assert(match, check.Equals, true)
}

View File

@ -2,9 +2,8 @@ package models
import ( import (
"crypto/rand" "crypto/rand"
"fmt"
"io"
"log" "log"
"math/big"
"net" "net"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
@ -68,17 +67,25 @@ func (r *Result) UpdateGeo(addr string) error {
// GenerateId generates a unique key to represent the result // GenerateId generates a unique key to represent the result
// in the database // in the database
func (r *Result) GenerateId() { func (r *Result) GenerateId() error {
// Keep trying until we generate a unique key (shouldn't take more than one or two iterations) // Keep trying until we generate a unique key (shouldn't take more than one or two iterations)
k := make([]byte, 32) const alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
k := make([]byte, 7)
for { for {
io.ReadFull(rand.Reader, k) for i := range k {
r.RId = fmt.Sprintf("%x", k) idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphaNum))))
if err != nil {
return err
}
k[i] = alphaNum[idx.Int64()]
}
r.RId = string(k)
err := db.Table("results").Where("r_id=?", r.RId).First(&Result{}).Error err := db.Table("results").Where("r_id=?", r.RId).First(&Result{}).Error
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
break break
} }
} }
return nil
} }
// GetResult returns the Result object from the database // GetResult returns the Result object from the database