func SignUpload(c *gin.Context) { user, err := GetUserFromContext(c) if err != nil { c.Fail(500, err) } var json UploadJSON c.Bind(&json) key := `attachments/` + user.Id + `/` + uuid.NewUUID().String() + extensions[json.ContentType] f := &Form{ Key: key, ACL: "public-read", AWSAccessKeyId: os.Getenv("AWS_ACCESS_KEY_ID"), CacheControl: "max-age=31557600", ContentType: json.ContentType, } f.build() href := "https://s3.amazonaws.com/" + os.Getenv("S3_BUCKET") + "/" + key c.JSON(200, gin.H{"form": f, "href": href}) }
//POST account/register func (c Account) PostRegister(user models.User) revel.Result { user.Validate(c.Validation) if c.Validation.HasErrors() { //把错误信息存到flash c.Validation.Keep() //把参数存到flash //c.FlashParams() return c.Redirect(routes.Account.Register()) } user.GravatarUrl = genGravatarUrl(user.Email) code := uuid.NewUUID() user.ActiveCode = code.String() user.ActiveCodeCreatedTime = time.Now() if !user.Save() { c.Flash.Error("Registered user failed") return c.Redirect(routes.Account.Register()) } c.Session[USERNAME] = user.Name subject := "activate password" content := fmt.Sprintf(`<h2><a href="http://%s:%s/account/activate/%s">`+ `activate account</a></h2>`, appAddr, appPort, user.ActiveCode) err := SendMail( subject, content, smtpConfig.Username, []string{user.Email}, smtpConfig, true) if err != nil { fmt.Println(err) } c.Flash.Success("please check email to make your account active") return c.Redirect(routes.Account.Notice()) }
func getToken(w http.ResponseWriter, req *http.Request) { glog.Info("getToken") var cred struct { Username string Password string } d := json.NewDecoder(req.Body) if d == nil { w.WriteHeader(http.StatusInternalServerError) return } if err := d.Decode(&cred); err != nil { w.WriteHeader(http.StatusBadRequest) return } if cred.Username != "user" || cred.Password != "password" { glog.Infof("Bad credentials user: %s, pass: %s", cred.Username, cred.Password) w.WriteHeader(http.StatusUnauthorized) w.Write(unauthRes) return } token = uuid.NewUUID() b, err := json.Marshal(token.String()) if err != nil { w.WriteHeader(http.StatusBadRequest) return } w.Write(b) }
//POST /account/send-reset-email func (c Account) SendResetEmail(email string) revel.Result { var user models.User code := uuid.NewUUID() user.Email = email user.ResetCode = code.String() user.ResetCodeCreatedTime = time.Now() if user.HasEmail() { _, err := engine.Where("email = ?", email). Cols("reset_code", "reset_code_created_time"). Update(&user) if err != nil { fmt.Println(err) } subject := "reset password" content := fmt.Sprintf( `<h2><a href="http://%s:%s/account/reset/%s">Reset Password</a></h2>`, appAddr, appPort, user.ResetCode) SendMail( subject, content, smtpConfig.Username, []string{email}, smtpConfig, true) c.Flash.Success("Email has been sent, pleas check it.") return c.Redirect(routes.Account.Notice()) } else { c.Flash.Error("Incorrect Email") return c.Redirect(routes.Account.Notice()) } }
//注册 func (u *UserController) SignUp(user models.User) revel.Result { user.Validation(u.q, u.Validation) if u.Validation.HasErrors() { u.Validation.Keep() return u.Redirect(routes.UserController.SignUpRedirect()) } notEncrypted := user.Password user.Password = models.EncryptPassword(user.Password) user.ValidateCode = strings.Replace(uuid.NewUUID().String(), "-", "", -1) if !user.Save(u.q) { u.Flash.Error("注册用户失败") return u.Redirect(routes.UserController.SignUpRedirect()) } subject := "激活账号 —— 奇享-向世界分享我们" content := `这封信是由 奇享 发送的。 您收到这封邮件,是由于在 奇享 获取了新用户注册地址使用 了这个邮箱地址。如果您并没有访问过 奇享, 或没有进行上述操作,请忽 略这封邮件。 您不需要退订或进行其他进一步的操作。 ---------------------------------------------------------------------- 新用户注册说明 ---------------------------------------------------------------------- 如果您是 奇享 的新用户,或在修改您的注册 Email 时使用了本地址,我们需 要对您的地址有效性进行验证以避免垃圾邮件或地址被滥用。 您只需点击下面的链接即可进行用户注册, "http://localhost:9000/user/validate/` + user.ValidateCode + `" (如果上面不是链接形式,请将该地址手工粘贴到浏览器地址栏再访问) 感谢您的访问,祝您使用愉快!` //发送验证邮件 go sendMail(subject, content, []string{user.Email}) //注册成功登陆 return u.SignIn(user.Email, notEncrypted, "") }
// New Message will create a new message struct to send to nsq func (queue *NsqAdapter) NewMessage(topic string, messageType string, payload interface{}) *Message { // create a new Message message := Message{} // set a unique id for our message message.Id = uuid.NewUUID().String() // set the originating service message.From = queue.Name // set the message to send the data to message.To = topic // define the time until we need the response message.StartTime = time.Now().String() // set the payload message.Payload, _ = json.Marshal(payload) // set the type message.MessageType = messageType return &message }
func (c *User) SignupPost(user models.User) revel.Result { user.Validate(c.Validation) if c.Validation.HasErrors() { c.Validation.Keep() c.FlashParams() return c.Redirect(routes.User.Signup()) } user.Type = MemberGroup user.Avatar = defaultAvatar user.ValidateCode = strings.Replace(uuid.NewUUID().String(), "-", "", -1) if !user.Save() { c.Flash.Error("注册用户失败") return c.Redirect(routes.User.Signup()) } subject := "激活账号" content := `<h2><a href="http://gorevel.cn/user/validate/` + user.ValidateCode + `">激活账号</a></h2>` go sendMail(subject, content, []string{user.Email}) c.Flash.Success(fmt.Sprintf("%s 注册成功,请到您的邮箱 %s 激活账号!", user.Name, user.Email)) perm := new(models.Permissions) perm.UserId = user.Id perm.Perm = MemberGroup perm.Save() return c.Redirect(routes.User.Signin()) }
// URL: /user_center/change_password // 修改密码 func changePasswordHandler(handler *Handler) { user, _ := currentUser(handler) form := wtforms.NewForm( wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}), wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}), wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}), ) if handler.Request.Method == "POST" && form.Validate(handler.Request) { if form.Value("new_password") == form.Value("confirm_password") { currentPassword := encryptPassword(form.Value("current_password"), user.Password) if currentPassword == user.Password { c := handler.DB.C(USERS) salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1) c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{ "password": encryptPassword(form.Value("new_password"), salt), "salt": salt, }}) message(handler, "密码修改成功", `密码修改成功`, "success") return } else { form.AddError("current_password", "当前密码错误") } } else { form.AddError("confirm_password", "密码不匹配") } } handler.renderTemplate("user_center/change_password.html", BASE, map[string]interface{}{ "form": form, "active": "change_password", }) }
//忘记密码 func (u *UserController) Forgot(mail string) revel.Result { //重新生成验证码 user := new(models.User) user.ValidateCode = strings.Replace(uuid.NewUUID().String(), "-", "", -1) user.Email = mail _, err := u.q.Update(user) if err != nil { fmt.Println(err) } subject := "激活账号 —— 奇享-向世界分享我们" content := `这封信是由 奇享 发送的。 您收到这封邮件,是由于在 奇享 获取了新用户注册地址使用 了这个邮箱地址。如果您并没有访问过 奇享, 或没有进行上述操作,请忽 略这封邮件。 您不需要退订或进行其他进一步的操作。 ---------------------------------------------------------------------- 找回密码说明 ---------------------------------------------------------------------- 如果您是 奇享 的老用户,或在修改您的注册 Email 时使用了本地址,我们需 要对您的地址有效性进行验证以避免垃圾邮件或地址被滥用。 您只需点击下面的链接即可进行用户密码找回, "http://localhost:9000/user/forgot/` + user.ValidateCode + `" (如果上面不是链接形式,请将该地址手工粘贴到浏览器地址栏再访问) 感谢您的访问,祝您使用愉快!` //发送验证邮件 go sendMail(subject, content, []string{user.Email}) return u.Redirect(routes.UserController.ForgotRedirect()) }
func (s *Sidecar) run() { parts := strings.Split(s.address, ":") host := strings.Join(parts[:len(parts)-1], ":") port, _ := strconv.Atoi(parts[len(parts)-1]) id := s.name + "-" + uuid.NewUUID().String() node := ®istry.Node{ Id: id, Address: host, Port: port, } service := ®istry.Service{ Name: s.name, Nodes: []*registry.Node{node}, } log.Infof("Registering %s", node.Id) registry.Register(service) if len(s.hcUrl) > 0 { log.Info("Starting sidecar healthchecker") exitCh := make(chan bool, 1) go s.hcLoop(service, exitCh) defer func() { exitCh <- true }() } ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL) <-ch }
func (setting *ServiceSetting) GetID() string { if setting.ID == "" { setting.ID = uuid.NewUUID().String() } return setting.ID }
//添加测试内容 func insertTestData() { var affects int64 firstPost := &Post{} count, _ := Engine.Count(firstPost) if count == 0 { firstPost.Slug = strings.Replace(uuid.NewUUID().String(), "-", "", -1) firstPost.Title = "Hello world!" firstPost.Content = "第一篇测试内容,<strong>Hello world!</strong>" firstPost.Tags = "测试" firstPost.CommentCount = 0 firstPost.Created = time.Now() affects, _ = Engine.InsertOne(firstPost) if affects > 0 && firstPost.Id > 0 { firstComment := &Comment{} firstComment.PostId = firstPost.Id firstComment.Name = "System" firstComment.Message = "第一个评论测试" firstComment.Created = time.Now() affects, _ = Engine.InsertOne(firstComment) revel.TRACE.Println("insert first comment affects = ", affects) if affects > 0 { firstPost.CommentCount = 1 Engine.Update(firstPost) } } } }
func (driver *MesosSchedulerDriver) frameworkReregistered(from *upid.UPID, pbMsg proto.Message) { log.V(1).Infoln("Handling Scheduler re-registered event.") msg := pbMsg.(*mesos.FrameworkReregisteredMessage) if driver.Status() == mesos.Status_DRIVER_ABORTED { log.Infoln("Ignoring FrameworkReregisteredMessage from master, driver is aborted!") return } if driver.connected { log.Infoln("Ignoring FrameworkReregisteredMessage from master,driver is already connected!") return } if !driver.MasterPid.Equal(from) { log.Warningf("ignoring framework re-registered message because it was sent from '%v' instead of leading master '%v'", from, driver.MasterPid) return } // TODO(vv) detect if message was from leading-master (sched.cpp) log.Infof("Framework re-registered with ID [%s] ", msg.GetFrameworkId().GetValue()) driver.setConnected(true) driver.connection = uuid.NewUUID() driver.Scheduler.Reregistered(driver, msg.GetMasterInfo()) }
// ---------------------- Handlers for Events from Master --------------- // func (driver *MesosSchedulerDriver) frameworkRegistered(from *upid.UPID, pbMsg proto.Message) { log.V(2).Infoln("Handling scheduler driver framework registered event.") msg := pbMsg.(*mesos.FrameworkRegisteredMessage) masterInfo := msg.GetMasterInfo() masterPid := masterInfo.GetPid() frameworkId := msg.GetFrameworkId() if driver.Status() == mesos.Status_DRIVER_ABORTED { log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is aborted", masterPid) return } if driver.connected { log.Infoln("ignoring FrameworkRegisteredMessage from master, driver is already connected", masterPid) return } if driver.stopped { log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is stopped", masterPid) return } if !driver.MasterPid.Equal(from) { log.Warningf("ignoring framework registered message because it was sent from '%v' instead of leading master '%v'", from, driver.MasterPid) return } log.Infof("Framework registered with ID=%s\n", frameworkId.GetValue()) driver.FrameworkInfo.Id = frameworkId // generated by master. driver.setConnected(true) driver.connection = uuid.NewUUID() driver.Scheduler.Registered(driver, frameworkId, masterInfo) }
func (setting *EndpointSetting) GetID() string { if setting.ID == "" { setting.ID = uuid.NewUUID().String() } return setting.ID }
func stubReply(toMsgId uuid.UUID, message interface{}) SockMessage { return SockMessage{ Id: uuid.NewUUID(), ReplyTo: toMsgId, Body: message, } }
func GPGDecrypt(uid string, src io.Reader) ([]byte, error) { dstfile := path.Join(os.TempDir(), uuid.NewUUID().String()) srcfile := fmt.Sprintf("%s.gpg", dstfile) defer func() { os.RemoveAll(srcfile) os.RemoveAll(dstfile) }() // save data to srcfile wd, err := os.Create(srcfile) if err != nil { return nil, err } _, err = io.Copy(wd, src) if err != nil { return nil, err } wd.Close() // decrypt using gpg gpg := exec.Command(GPGPath, "-u", uid, "-o", dstfile, srcfile) err = gpg.Run() if err != nil { return nil, err } // read dstfile rd, err := os.Open(dstfile) if err != nil { return nil, err } defer rd.Close() return ioutil.ReadAll(rd) }
func GPGEncrypt(uid, recipient string, src io.Reader) ([]byte, error) { srcfile := path.Join(os.TempDir(), uuid.NewUUID().String()) dstfile := fmt.Sprintf("%s.gpg", srcfile) defer func() { os.RemoveAll(srcfile) os.RemoveAll(dstfile) }() // save data to srcfile wd, err := os.Create(srcfile) if err != nil { return nil, err } _, err = io.Copy(wd, src) if err != nil { return nil, err } wd.Close() // encrypt using gpg gpg := exec.Command(GPGPath, "--trust-model", "always", "-u", uid, "-se", "-r", recipient, "-o", dstfile, srcfile) gpg.Stdin = os.Stdin if err = gpg.Run(); err != nil { return nil, err } // read dstfile rd, err := os.Open(dstfile) if err != nil { return nil, err } defer rd.Close() return ioutil.ReadAll(rd) }
func (h *httpBroker) Init() error { if len(h.id) == 0 { h.id = "broker-" + uuid.NewUUID().String() } http.Handle(DefaultSubPath, h) return nil }
// URL: /upload/image // 编辑器上传图片,接收后上传到七牛 func uploadImageHandler(handler *Handler) { file, header, err := handler.Request.FormFile("editormd-image-file") if err != nil { panic(err) return } defer file.Close() // 检查是否是jpg或png文件 uploadFileType := header.Header["Content-Type"][0] filenameExtension := "" if uploadFileType == "image/jpeg" { filenameExtension = ".jpg" } else if uploadFileType == "image/png" { filenameExtension = ".png" } else if uploadFileType == "image/gif" { filenameExtension = ".gif" } if filenameExtension == "" { handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(0, "", "不支持的文件格式,请上传 jpg/png/gif 图片")) return } // 上传到七牛 // 文件名:32位uuid+后缀组成 filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension key := "upload/image/" + filename ret := new(qiniuIo.PutRet) var policy = rs.PutPolicy{ Scope: "gopher", } err = qiniuIo.Put( nil, ret, policy.Token(nil), key, file, nil, ) if err != nil { panic(err) handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(0, "", "图片上传到七牛失败")) return } handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(1, "http://7xj1eq.com1.z0.glb.clouddn.com/"+key, "")) }
/** * The UUID package is naive and can generate identical UUIDs if the time interval is quick enough. * Block subsequent UUIDs for 200 Nanoseconds, the UUID uses 100 ns increments, we block for 200 to be safe * Blocks in a go routine, so that the caller doesn't have to wait. * TODO: save old unused UUIDs so that no one has to block. */ func NewUUID() UUID { uuidLock.Lock() result := uuid.NewUUID() go func() { time.Sleep(200 * time.Nanosecond) uuidLock.Unlock() }() return result }
func issueHttpRequest(address string, timeoutInMilliseconds time.Duration, waitGroup *sync.WaitGroup) { // create a new request request := &Request{} request.Id = uuid.NewUUID().String() request.Url = address + "/" + request.Id request.Started = time.Now() responseChan := make(chan *Request) // run our request in a new go routine go func(request Request) { response, err := http.Get(request.Url) if err != nil { request.Status = StatusError request.Info = "Response error: " + err.Error() responseChan <- &request return } body, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { request.Status = StatusError request.Info = "Read response error: " + err.Error() responseChan <- &request return } request.Info = string(body) request.Status = StatusFinished responseChan <- &request return }(*request) select { case request = <-responseChan: request.Ended = time.Now() request.Duration = request.Ended.Sub(request.Started) case <-time.After(timeoutInMilliseconds * time.Millisecond): request.Status = StatusTimeout request.Info = "--" request.Ended = time.Now() request.Duration = request.Ended.Sub(request.Started) } var mutex = &sync.Mutex{} mutex.Lock() if verbose { fmt.Println(request.String()) } requests = append(requests, request) mutex.Unlock() waitGroup.Done() }
func NewFuture() *Future { f := &Future{ uuid: uuid.NewUUID().String(), Result: make(chan interface{}), } eventbus.EventBus.Subscribe(f.uuid, f.callback).Once() logrus.Debugf("Future: %s new future created", f.uuid) return f }
/** * The UUID package is naive and can generate identical UUIDs if the time interval is quick enough. * Block subsequent UUIDs for 200 Nanoseconds, the UUID uses 100 ns increments, we block for 200 to be safe * Blocks in a go routine, so that the caller doesn't have to wait. * TODO: save old unused UUIDs so that no one has to block. */ func NewUUID() types.UID { uuidLock.Lock() result := uuid.NewUUID() go func() { time.Sleep(200 * time.Nanosecond) uuidLock.Unlock() }() return types.UID(result.String()) }
func requestID(inner http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { uid := uuid.NewUUID() r.Header.Set("Request-Id", uid.String()) w.Header().Set("Request-Id", r.Header.Get("Request-Id")) inner.ServeHTTP(w, r) }) }
// Generate generates AccessToken. func Generate(seed []byte) AccessToken { id := uuid.NewUUID() for i := 0; i < 1000; i++ { sha := uuid.NewSHA1(id, seed) md5 := uuid.NewMD5(id, seed) seed = append(sha, md5...) } encoded := base58.Encode(seed) return New(encoded[:40]) }
// /mock // Creates a uuid endpoint which will always return 200 and the specified payload func (api *MockApi) MockHandler(rw http.ResponseWriter, req *http.Request) { api.EndpointsMutex.Lock() defer api.EndpointsMutex.Unlock() endpointName := uuid.NewUUID().String() endpoint := NewEndpoint() endpoint.AddResponse(req, "") api.Endpoints[endpointName] = endpoint rw.WriteHeader(http.StatusOK) rw.Write([]byte(endpointName)) }
func NewUniqueKey(horizon string) PrimaryKey { id := uuid.Parse(horizon) if id == nil { id = uuid.NewUUID() } return PrimaryKey{ keyType: unique, uniqueID: id.String(), } }
func NewGuild(name, ownerID string) *Guild { guild := &Guild{ ID: uuid.NewUUID().String(), Name: name, OwnerID: ownerID, MemberIDs: make([]string, 0), } db.Guilds[guild.ID] = guild return guild }
func UserAdd(u *User) error { ut := User{} err := DB.One("user", "WHERE name='"+u.Name+"'", &ut, []string{"tel"}) if err == nil { return errors.New("登陆账户为" + u.Name + "的账户已经存在") } u.Id = uuid.NewUUID().String() err = DB.Insert("user", u) return err }