func newToken(db DB, user *User) (*Token, error) { tokenId := uniuri.NewLen(20) t, err := db.Get(Token{}, tokenId, user.UserId) for err == nil && t != nil { // Shit, we generated an existing token... // just one time in 10^32 // Let's play the lottery! tokenId := uniuri.NewLen(20) t, err = db.Get(Token{}, tokenId, user.UserId) } if err != nil { return nil, err } token := &Token{ TokenId: tokenId, UserId: user.UserId, Creation: time.Now(), } err = db.Insert(token) if err != nil { return nil, err } return token, nil }
func saveUrl(db DB, user *User, fullUrl string) (*Url, error) { log.Println("Starting SaveImage") urlId := uniuri.NewLen(5) u, err := db.Get(Url{}, urlId) for err == nil && u != nil { urlId := uniuri.NewLen(5) u, err = db.Get(Url{}, urlId) } if err != nil { return nil, err } url := &Url{ UrlId: urlId, FullUrl: fullUrl, UserId: user.UserId, Creation: time.Now(), ViewCount: 0, } err = db.Insert(url) if err != nil { return nil, err } return url, nil }
func CreateContent(db DB, user *User, url *Url, img *Image, content *Content) (*Content, error) { contentId := uniuri.NewLen(20) u, err := db.Get(Content{}, contentId) for err == nil && u != nil { contentId := uniuri.NewLen(20) u, err = db.Get(Content{}, contentId) } if err != nil { return nil, err } s := slug.Slug(content.Title) // Let's check if this slug already exists, // if existis, we will increment a sulfix to it newSlug := s increment := 1 count, err := db.SelectInt("select count(*) from content where slug=?", newSlug) for err == nil && count != 0 { increment += 1 newSlug = fmt.Sprintf("%s-%d", s, increment) count, err = db.SelectInt("select count(*) from content where slug=?", newSlug) } log.Printf("SLUG: %s, inc: %d, count: %d\n", newSlug, increment, count) if err != nil { return nil, err } newContent := &Content{ ContentId: contentId, UrlId: url.UrlId, CategoryId: "default", // First category will be "Sem categoria" Title: content.Title, Slug: newSlug, Description: content.Description, Host: content.Host, UserId: user.UserId, ImageId: "default", // We will check the if there is an image below LikeCount: 0, Creation: time.Now(), LastUpdate: time.Now(), Deleted: false, } if img != nil { newContent.ImageId = img.ImageId } err = db.Insert(newContent) if err != nil { return nil, err } return newContent, nil }
func newUser(db DB, profile *Profile) (*User, error) { userId := uniuri.NewLen(20) userName := profile.UserName var users []User var increment = 0 query := "select * from user where userid=? or username=?" _, err := db.Select(&users, query, userId, userName) for err == nil && len(users) != 0 { log.Printf("Trying to create another userid U[%v]: %#v \n", len(users), users) u := users[0] users = users[:0] // Clear my slice // I will play in lottery if we see it happennig // just one time in 10^32 if u.UserId == userId { userId = uniuri.NewLen(20) } // If already exists an user with this userName if u.UserName == userName { increment += 1 userName = fmt.Sprintf("%s%d", profile.UserName, increment) } // Check if still existing an user like this _, err = db.Select(&users, query, userId, userName) } // Checks if main loop didn't finish for an error if err != nil { return nil, err } user := &User{ UserId: userId, UserName: userName, PicId: "default", // Reference to default pic FullName: profile.FullName, LikeCount: 0, Creation: time.Now(), LastUpdate: time.Now(), Deleted: false, Admin: false, } err = db.Insert(user) if err != nil { return nil, err } return user, nil }
func createCluster(cmd *cobra.Command, args []string) { createClusterFlags.VaultAddress = vaultCfg.VaultAddr createClusterFlags.VaultCertificatePath = vaultCfg.VaultCACert requireProfile := false loadArgumentsFromCluster(cmd.Flags(), requireProfile) clusterInfoFromArgs(&createClusterFlags.ClusterInfo, args) provider := newProvider() createClusterFlags = provider.CreateClusterDefaults(createClusterFlags) // Create cluster ID if needed if createClusterFlags.ID == "" { createClusterFlags.ID = strings.ToLower(uniuri.NewLen(40)) } else { createClusterFlags.ID = strings.ToLower(createClusterFlags.ID) } // Create weave password if needed if createClusterFlags.WeavePassword == "" { createClusterFlags.WeavePassword = uniuri.NewLen(40) } // Validate if err := createClusterFlags.Validate(); err != nil { Exitf("Create failed: %s\n", err.Error()) } // See if there are already instances for the given cluster instances, err := provider.GetInstances(createClusterFlags.ClusterInfo) if err != nil { Exitf("Failed to query existing instances: %v\n", err) } if len(instances) > 0 { Exitf("Cluster %s.%s already exists.\n", createClusterFlags.Name, createClusterFlags.Domain) } // Confirm if err := confirm(fmt.Sprintf("Are you sure you want to create a %d instance cluster of %s?", createClusterFlags.InstanceCount, createClusterFlags.InstanceConfig)); err != nil { Exitf("%v\n", err) } // Create err = provider.CreateCluster(log, createClusterFlags, newDnsProvider()) if err != nil { Exitf("Failed to create new cluster: %v\n", err) } // Update all members reboot := true if err := providers.UpdateClusterMembers(log, createClusterFlags.ClusterInfo, reboot, nil, provider); err != nil { Exitf("Failed to update cluster members: %v\n", err) } Infof("Cluster created with ID: %s\n", createClusterFlags.ID) }
// Take a http client with a transport pre-configured with the user credentials // and return the Pic saved in public/img/pic/ and stored in DB func getPic(db DB, client *http.Client) (*Pic, error) { // OK WE HAVE THE PROFILE, BUT WE DON'T HAVE USER'S PICTURE // LETS TAKE IT res, err := client.Get("https://graph.facebook.com/me/picture") if err != nil { return nil, err } defer res.Body.Close() img, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } picId := uniuri.NewLen(20) p, err := db.Get(Pic{}, picId) for err == nil && p != nil { // Shit, we generated an existing picId! // Lotto, where are you? picId := uniuri.NewLen(20) p, err = db.Get(Pic{}, picId) } if err != nil { return nil, err } fo, err := os.Create("public/pic/" + picId + ".png") if err != nil { return nil, err } // close fo on exit and check for its returned error defer func() { if err := fo.Close(); err != nil { panic(err) } }() fo.Write(img) pic := &Pic{ PicId: picId, Creation: time.Now(), Deleted: false, } err = db.Insert(pic) if err != nil { return nil, err } return pic, nil }
func create(c *gin.Context) { var err error remote := c.ClientIP() c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.LimitSize*1000000) fd, h, err := c.Request.FormFile("file") if err != nil { log.Printf("[ERROR][%s]\tDuring reading file : %s", remote, err) c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.LimitSize) c.AbortWithStatus(http.StatusRequestEntityTooLarge) return } defer fd.Close() u := uniuri.NewLen(conf.C.UniURILength) k := uniuri.NewLen(16) kb := []byte(k) block, err := aes.NewCipher(kb) if err != nil { log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err) c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) return } var iv [aes.BlockSize]byte stream := cipher.NewCFBEncrypter(block, iv[:]) path := path.Join(conf.C.UploadDir, u) file, err := os.Create(path) if err != nil { log.Printf("[ERROR][%s]\tDuring file creation : %s\n", remote, err) c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) return } defer file.Close() writer := &cipher.StreamWriter{S: stream, W: file} // No encryption : wr, err := io.Copy(file, bufio.NewReaderSize(fd, 512)) // Copy the input file to the output file, encrypting as we go. wr, err := io.Copy(writer, bufio.NewReaderSize(fd, 512)) if err != nil { log.Printf("[ERROR][%s]\tDuring writing : %s\n", remote, err) c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) } db.Create(&models.ResourceEntry{Key: u, Name: h.Filename}) log.Printf("[INFO][%s]\tCreated %s file and entry (%v bytes written)\n", remote, u, wr) c.String(http.StatusCreated, "https://%s/v/%s/%s\n", conf.C.NameServer, u, k) }
func (p *portalAPI) createUser(res http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) n := struct { Email string Name string Password string Profile map[string]interface{} After string }{} if decoder.Decode(&n) != nil || n.Email == "" || n.Password == "" || n.Name == "" { abort(res, 400, "Request a new account by supplying your email, name and password.") return } u := User{Name: n.Name, Email: n.Email, Active: false, Profile: n.Profile} err := p.m.AddUser(n.Email, n.Password, &u) if err != nil { abort(res, 400, "Could not create new account: %s", err.Error()) return } if !u.Active { code := uniuri.NewLen(48) act := activationData{Email: n.Email, After: n.After} r := p.a.redis.Get() jsonAct, _ := json.Marshal(&act) r.Do("SETEX", "activation:"+code, (24 * time.Hour).Seconds(), jsonAct) // TODO send activation code email } finish(res, &u) }
func NewInsert(name, table string, args ...string) (Insert, error) { conn, err := connection.Get() if err != nil { return Insert{}, err } bi := Insert{} serial := uniuri.NewLen(5) bi.name = fmt.Sprintf(name, serial) bi.table = fmt.Sprintf(table, bi.name) tx, err := conn.Begin() if err != nil { return bi, err } // close up our defer tx.Rollback() bi.tx = tx _, err = bi.tx.Exec(bi.table) if err != nil { return bi, err } // prepare args for idx, i := range args { args[idx] = fmt.Sprintf(`"%s"`, i) } bi.args = args stmt := fmt.Sprintf( `COPY %s (%s) FROM STDIN`, bi.name, strings.Join(bi.args, ", "), ) bi.stmt, err = bi.tx.Prepare(stmt) if err != nil { return bi, err } return bi, nil }
func (p *portalAPI) createUser(res http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) n := struct { Email string Name string Password string Profile map[string]interface{} Link string }{} if decoder.Decode(&n) != nil || n.Email == "" || n.Password == "" || n.Name == "" || n.Link == "" { abort(res, 400, "Request a new account by supplying email, name, password and a template for an activation link.") return } u := User{Name: n.Name, Email: n.Email, Active: false, Profile: n.Profile} err := p.m.AddUser(n.Email, n.Password, &u) if err != nil { abort(res, 400, "Could not create new account: %s", err.Error()) return } if !u.Active { code := uniuri.NewLen(48) link := strings.Replace(n.Link, "CODE", code, 1) r := p.a.redis.Get() r.Do("SETEX", "activation:"+code, (24 * time.Hour).Seconds(), n.Email) p.a.sendEmail(n.Email, "Activate your account", "text/plain", fmt.Sprintf(`Hi %s, please activate your developer account by visiting this link: %s `, u.Name, link)) } finish(res, &u) }
func (p *portalAPI) requestResetPassword(res http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) rq := struct { Email string `json:"email"` Link string `json:"link"` }{} if decoder.Decode(&rq) != nil || rq.Email == "" || rq.Link == "" { abort(res, 400, "Specify your email and a link to reset your password.") return } u := p.m.GetUser(rq.Email) if u == nil { abort(res, 404, "User not found.") return } code := uniuri.NewLen(48) r := p.a.redis.Get() _, err := r.Do("SETEX", "password-reset:"+code, 60*60, rq.Email) if err != nil { abort(res, 500, "Couldn't store your password reset request. Please contact an administrator.") return } p.a.sendEmail(rq.Email, "Reset your password", "text/plain; charset=UTF-8", fmt.Sprintf(`Hi %s, to reset your password, please visit this link: %s `, u.Name, strings.Replace(rq.Link, "CODE", code, 1))) finish(res, &rq) }
func TestCard(t *testing.T) { clist := []int{1, 5, 10, 30, 60, 200, 500, 1000, 10000, 60000} n := 30 rel_err := 0.05 for _, card := range clist { s := 0.0 for c := 0; c < n; c++ { a, err := NewHyperLogLog(rel_err) if err != nil { t.Errorf("NewHyperLogLog(%v) returned an error", rel_err) } for i := 0; i < card; i++ { a.Add(uniuri.NewLen(20)) } s += a.Card() } z := (s/float64(n) - float64(card)) / (rel_err * float64(card) / math.Sqrt(float64(n))) if z < -1.96 || z > 1.96 { t.Errorf("The error rate in HyperLogLog.Card() was greater than %v", rel_err) } } }
// SetupNames configured the ClusterName and InstanceName of the given options // using the given cluster & domain name func (o *CreateInstanceOptions) SetupNames(prefix, clusterName, domain string) { if prefix == "" { prefix = strings.ToLower(uniuri.NewLen(6)) } o.ClusterName = fmt.Sprintf("%s.%s", clusterName, domain) o.InstanceName = fmt.Sprintf("%s.%s.%s", prefix, clusterName, domain) }
func checkAndCreateCategories(db DB) { for i, categoryName := range categoryList { categorySlug := slug.Slug(categoryName) count, err := db.SelectInt("select count(*) from category where categoryslug=?", categorySlug) if err != nil { log.Printf("Error searching for the category with categorySlug %s\n", categorySlug) log.Println("Stopping the creation of categories") return } if count == 0 { category := &Category{ CategoryId: uniuri.NewLen(20), CategoryName: categoryName, CategorySlug: categorySlug, LikeCount: 0, } if i == 0 { // "Sem Categoria" is my default category category.CategoryId = "default" } err := db.Insert(category) if err != nil { log.Printf("Error when creating the category %s. %s\n", category.CategoryName, err) } else { log.Printf("Category %s created!\n", category.CategoryName) } } } }
func linkAccess(url *Url, user *User) { url.ViewCount += 1 count, err := db.Update(url) if err != nil { log.Printf("Error when updating the url.ViewCount. %s.\n", err) return } if count != 1 { log.Printf("Error url.ViewCount was not updated.\n", err) return } access := &Access{ AccessId: uniuri.NewLen(20), UserId: user.UserId, // Could be anonymous UrlId: url.UrlId, Creation: time.Now(), } err = db.Insert(access) if err != nil { log.Printf("Error when inserting the access object. %s.\n", err) return } }
func GenerateTokenAndSave(userid uint64, deviceId string, deviceType int, role int, ip string) (string, int64, error) { // genareting expireDate := time.Now().AddDate(0, 0, tokenExistInDays) randStr := uniuri.NewLen(128) tokenHash := GenerateHashFromToken(randStr) // saving db, err := GetDBConnection() if err != nil { return "", 0, err } stmtIns, stmtErr := db.Prepare("REPLACE INTO ml_users_tokens(userId, tokenHash, ip, role, expireAt, deviceId, deviceType) VALUES( ?, ?, ?, ?, ?, ?, ?)") if stmtErr != nil { return "", 0, stmtErr } defer stmtIns.Close() _, err = stmtIns.Exec(userid, tokenHash, ip, uint8(role), expireDate.Unix(), deviceId, deviceType) if err != nil { return "", 0, err } return randStr, expireDate.Unix(), nil }
func RequestIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { id := uniuri.NewLen(uniuri.UUIDLen) GetContext(req).Set("Request-Id", id) req.Header.Set("X-Request-Id", id) next.ServeHTTP(rw, req) }) }
// NewResourceFromForm returns a new Resource instance with some fields calculated func NewResourceFromForm(h *multipart.FileHeader, once bool, duration time.Duration) Resource { return Resource{ Key: uniuri.NewLen(conf.C.UniURILength), Name: h.Filename, Once: once, DeleteAt: time.Now().Add(duration), } }
func (t *Token) PreInsert(s gorp.SqlExecutor) error { t.Created = milli.Timestamp(time.Now()) t.Updated = milli.Timestamp(time.Now()) t.Value = uniuri.NewLen(30) ex := time.Now().AddDate(0, 0, 14) t.Expiration = milli.Timestamp(ex) return t.Validate() }
// ExampleConfiguration generates an ApiplexConfig struct with example values // and the specified plugins inserted with their default configurations at // their appropriate places in the plugin tree. This is a good starting point // to give to the user for customization. func ExampleConfiguration(pluginNames []string) (*ApiplexConfig, error) { c := ApiplexConfig{ Redis: apiplexConfigRedis{ Host: "127.0.0.1", Port: 6379, DB: 0, }, Quotas: map[string]apiplexQuota{ "default": apiplexQuota{ Minutes: 5, MaxIP: 50, MaxKey: 5000, }, "keyless": apiplexQuota{ Minutes: 5, MaxIP: 20, }, }, Serve: apiplexConfigServe{ Port: 5000, API: "/", Upstreams: []string{"http://your-actual-api:8000/"}, PortalAPI: "/portal/api/", Portal: "/portal/", SigningKey: uniuri.NewLen(64), }, } plugins := apiplexConfigPlugins{} for _, pname := range pluginNames { pInfo, ok := registeredPlugins[pname] if !ok { return nil, fmt.Errorf("No plugin '%s' available.", pname) } pluginPtr := reflect.New(pInfo.pluginType) defConfig := pluginPtr.MethodByName("DefaultConfig").Call([]reflect.Value{})[0].Interface().(map[string]interface{}) pconfig := apiplexPluginConfig{Plugin: pname, Config: defConfig} switch pluginPtr.Interface().(type) { case AuthPlugin: plugins.Auth = append(plugins.Auth, pconfig) case ManagementBackendPlugin: plugins.Backend = append(plugins.Backend, pconfig) case BackendPlugin: plugins.Backend = append(plugins.Backend, pconfig) case PreUpstreamPlugin: plugins.PreUpstream = append(plugins.PreUpstream, pconfig) case PostUpstreamPlugin: plugins.PostUpstream = append(plugins.PostUpstream, pconfig) case PostAuthPlugin: plugins.PostAuth = append(plugins.PostAuth, pconfig) case LoggingPlugin: plugins.Logging = append(plugins.Logging, pconfig) } } c.Plugins = plugins return &c, nil }
func StartReceiver(c *client, signal chan error, opts *Options) { ch, err := c.openChannel() if err != nil { signal <- err return } if !opts.NoDeclare { q, err := declareQueue(ch, opts.Queue) if err != nil { signal <- err return } if opts.Queue == "" { opts.Queue = q.Name } } if err := ch.Qos(opts.Prefetch, 0, opts.GlobalPrefetch); err != nil { signal <- err return } tag := uniuri.NewLen(4) deliveries, err := subscribe(ch, opts, tag) if err != nil { signal <- err return } log.Infof("receiver (%s) subscribed to queue %s (prefetch=%d; global=%v; priority=%d) ", tag, opts.Queue, opts.Prefetch, opts.GlobalPrefetch, opts.Priority) cancelSubscription := make(chan bool) go handle(deliveries, opts, tag, c.signal, cancelSubscription) cancel := make(chan string, 1) ch.NotifyCancel(cancel) select { case tag := <-cancel: _ = tag cancelSubscription <- true if opts.Renew { log.Info("automatically renewing subscription") c, err := NewClient(opts, c.flake) if err != nil { signal <- err return } StartReceiver(c, signal, opts) } } signal <- nil }
func (p *Parser) Register(packet packets.Packet, hook Hook) (string, error) { if _, ok := p.hooks[packet.Id()]; !ok { p.hooks[packet.Id()] = []hookInfo{} } id := uniuri.NewLen(8) info := hookInfo{Id: id, F: hook} p.hooks[packet.Id()] = append(p.hooks[packet.Id()], info) return id, nil }
// MakeResource creates a new Resource object with sane defaults. func MakeResource(ownerID, name string) Resource { t := time.Now() return Resource{ ID: uniuri.NewLen(uniuri.UUIDLen), DateModified: t, DateCreated: t, Name: name, Owner: ownerID, } }
func (m *Member) PreInsert(s gorp.SqlExecutor) error { m.Created = milli.Timestamp(time.Now()) m.Updated = milli.Timestamp(time.Now()) if m.Email == "" { m.Email = fmt.Sprintf("*****@*****.**", uniuri.NewLen(8)) } if err := m.updateCategoires(s); err != nil { return err } return m.Validate() }
func registerForm(e string) *strings.Reader { form := url.Values{} form.Add("form_build_id", getFormID(registerURL, registerFormID)) form.Add("form_id", "account_api_member_registration_form") form.Add("financial_advisor", "1") form.Add("email", e+"@gmail.com") form.Add("display_name", uniuri.NewLen(20)) form.Add("password", password) form.Add("confirm_password", password) form.Add("op", "Register") return strings.NewReader(form.Encode()) }
// Generate a session token and register it in the DB. func newSession(room *Room) (string, error) { token := uniuri.NewLen(32) // Add the token to room's session set. db := dbPool.Get() defer db.Close() err := db.PutSet(config.CachePrefixSessions+room.Id, token) if err == nil { return token, nil } else { return "", err } }
// Generate png filename and encode it. The encoded code will // will save on html and will by post request decoded, that // use to identify, if the user have enter the right captcha code. func Create() (string, string) { image := uniuri.NewLen(25) secret := captcha.RandomDigits(7) c := redis.Get() if _, err := c.Do("SET", image, secret); err != nil { panic(err.Error()) } if _, err := c.Do("EXPIRE", image, expired); err != nil { panic(err.Error()) } return image, base64.StdEncoding.EncodeToString([]byte(image)) }
func NewPlayer(c net.Conn, ku *Kurafuto) (p *Player, err error) { p = &Player{ Id: uniuri.NewLen(8), ku: ku, hub: fmt.Sprintf("%s:%d", ku.Hub.Address, ku.Hub.Port), Client: BoundInfo{C: make(chan packets.Packet, 64)}, Server: BoundInfo{C: make(chan packets.Packet, 64)}, State: Connecting, qMutex: sync.Mutex{}, } return }
func (g ManfredGame) AddTestPlayer(game string, c redis.Conn) { twitchId := uniuri.NewLen(12) player := ManfredPlayer{} player.Handles = make(map[string]string) player.Handles["TWITCH"] = twitchId player.Handles[game] = twitchId SaveManfredPlayer(player, ConvertToTwitchUserKey(twitchId), c) _, err := c.Do("SADD", g.GetPossiblePlayersSetKey(), ConvertToTwitchUserKey(twitchId)) c.Do("EXPIRE", g.GetPossiblePlayersSetKey(), 43200) // Expire after 1 day if err != nil { log.Fatal(err) } }
func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h, ok := mux[r.URL.String()]; ok { h(w, r) return } formVals := map[string]string{} if err := r.ParseForm(); err == nil { for k, v := range r.Form { if len(v) >= 0 { formVals[k] = v[0] } } } t := time.Now().UnixNano() data := message.Message{ RequestId: fmt.Sprintf("%d-%s", t, uniuri.NewLen(5)), RequestPath: r.RequestURI, RequestParams: formVals, } b, err := json.Marshal(data) if err != nil { log.Panic(err) } chanMap[data.RequestId] = make(chan message.Response, 1) log.Printf("Notifying of '%s'", data.RequestId) tok := c.Publish("http/requests", 0, false, string(b)) tok.Wait() if err := tok.Error(); err != nil { log.Println(err) } select { case resp := <-chanMap[data.RequestId]: io.WriteString(w, resp.Data) close(chanMap[data.RequestId]) chanMap[data.RequestId] = nil log.Println("Done!") case <-time.After(5 * time.Second): http.Error(w, "Handler timed out", 500) } }